Example usage for java.util Calendar DATE

List of usage examples for java.util Calendar DATE

Introduction

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

Prototype

int DATE

To view the source code for java.util Calendar DATE.

Click Source Link

Document

Field number for get and set indicating the day of the month.

Usage

From source file:org.openmrs.module.clinicalsummary.web.controller.response.SearchMedicationResponseController.java

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Map<Integer, List<MedicationResponseForm>> searchResponses(
        final @RequestParam(required = true, value = "locationId") String locationId,
        final @RequestParam(required = false, value = "displayType") ResponseDisplayType displayType) {

    // TODO: add another grouping by provider name to this json and then in the jsp, add another jQuery.each call!
    Map<Integer, List<MedicationResponseForm>> responseMap = new HashMap<Integer, List<MedicationResponseForm>>();
    if (Context.isAuthenticated()) {
        // prepare the calendar to limit the returned responses
        Calendar calendar = Calendar.getInstance();
        // end date are determined by the parameter value passed by the user
        Date startDate;//w ww  . j av  a  2  s . c o  m
        switch (displayType) {
        case DISPLAY_PAST_WEEK_RESPONSES:
            calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -7);
            startDate = calendar.getTime();
            break;
        case DISPLAY_PAST_MONTH_RESPONSES:
            calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -1);
            startDate = calendar.getTime();
            break;
        case DISPLAY_PAST_2_MONTHS_RESPONSES:
            calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -2);
            startDate = calendar.getTime();
            break;
        case DISPLAY_PAST_6_MONTHS_RESPONSES:
            calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -6);
            startDate = calendar.getTime();
            break;
        case DISPLAY_PAST_12_MONTHS_RESPONSES:
            calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -12);
            startDate = calendar.getTime();
            break;
        default:
            startDate = null;
        }
        // search for the location passed by the user
        Location location = Context.getLocationService().getLocation(NumberUtils.toInt(locationId, 0));
        // search for all matching responses from the database
        UtilService service = Context.getService(UtilService.class);
        List<MedicationResponse> responses = service.getResponses(MedicationResponse.class, location, startDate,
                new Date());
        for (MedicationResponse response : responses) {
            try {
                Integer patientId = response.getPatient().getPatientId();
                // search if the medication forms for teh patient is already in the map or not
                List<MedicationResponseForm> responseForms = responseMap.get(patientId);
                if (responseForms == null) {
                    // initialize when we don't have the list yet
                    responseForms = new ArrayList<MedicationResponseForm>();
                    responseMap.put(patientId, responseForms);
                }
                // add the current response to the list
                MedicationResponseForm responseForm = new MedicationResponseForm();
                BeanUtils.copyProperties(responseForm, response);
                responseForm.setPatientId(response.getPatient().getPatientId());
                responseForm.setPatientName(response.getPatient().getPersonName().getFullName());
                responseForm.setProviderName(response.getProvider().getPersonName().getFullName());
                responseForm.setLocationName(response.getLocation().getName());
                responseForm.setMedicationName(response.getMedication().getName(Context.getLocale()).getName());
                responseForm.setDatetime(Context.getDateFormat().format(response.getDatetime()));
                if (response.getActionType() != null)
                    responseForm.setAction(response.getActionType().getValue());
                // add to the output list
                responseForms.add(responseForm);
            } catch (Exception e) {
                log.error("Exception thrown when serializing responses", e);
            }
        }
    }
    // return the formatted output
    return responseMap;
}

From source file:DateUtils.java

/**
 * Get ISO 8601 timestamp./*from  w ww  .  j a  v  a2s.c  o m*/
 */
public final static String getISO8601Date(long millis) {
    StringBuffer sb = new StringBuffer(19);
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(millis);

    // year
    sb.append(cal.get(Calendar.YEAR));

    // month
    sb.append('-');
    int month = cal.get(Calendar.MONTH) + 1;
    if (month < 10) {
        sb.append('0');
    }
    sb.append(month);

    // date
    sb.append('-');
    int date = cal.get(Calendar.DATE);
    if (date < 10) {
        sb.append('0');
    }
    sb.append(date);

    // hour
    sb.append('T');
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    if (hour < 10) {
        sb.append('0');
    }
    sb.append(hour);

    // minute
    sb.append(':');
    int min = cal.get(Calendar.MINUTE);
    if (min < 10) {
        sb.append('0');
    }
    sb.append(min);

    // second
    sb.append(':');
    int sec = cal.get(Calendar.SECOND);
    if (sec < 10) {
        sb.append('0');
    }
    sb.append(sec);

    return sb.toString();
}

From source file:fr.ortolang.diffusion.statistics.PiwikAllCollector.java

@Override
public void run() {
    PiwikTracker tracker = new PiwikTracker(host + "index.php");
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    int currentYear = calendar.get(Calendar.YEAR);
    int currentMonth = calendar.get(Calendar.MONTH);
    for (int year = 2015; year <= currentYear; year++) {
        for (int month = 0; year == currentYear ? month <= currentMonth : month <= 11; month++) {
            calendar.set(year, month, 1);
            String start = dateFormat.format(calendar.getTime());
            calendar.add(Calendar.MONTH, 1);
            calendar.add(Calendar.DATE, -1);
            String end = dateFormat.format(calendar.getTime());
            String range = start + "," + end;
            SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyyMM");
            long timestamp = Long.parseLong(timestampFormat.format(calendar.getTime()));
            for (String alias : workspaces) {
                try {
                    LOGGER.log(Level.INFO, "Collect stats for workspace with alias [" + alias + "] (range: "
                            + start + "," + end + " [" + timestamp + "])");
                    // Views
                    PiwikRequest request = makePiwikRequestForViews(siteId, authToken, alias, range);
                    HttpResponse viewsResponse = tracker.sendRequest(request);
                    // Downloads
                    request = makePiwikRequestForDownloads(siteId, authToken, alias, range);
                    HttpResponse downloadsResponse = tracker.sendRequest(request);
                    // Single Downloads
                    request = makePiwikRequestForSingleDownloads(siteId, authToken, alias, range);
                    HttpResponse singleDownloadsResponse = tracker.sendRequest(request);
                    compileResults(alias, timestamp, viewsResponse, downloadsResponse, singleDownloadsResponse);
                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE, "Could not probe Piwik stats for workspace with alias [" + alias
                            + "]: " + e.getMessage(), e);
                }/* w  w w  .ja  v  a 2  s.com*/
            }
        }
    }
}

From source file:com.datatorrent.flume.source.HdfsTestSource.java

public HdfsTestSource() {
    super();/*from  w  w  w  .  java  2  s .  co m*/
    this.rate = 2500;
    dataFiles = Lists.newArrayList();
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -1);
    oneDayBack = calendar.getTimeInMillis();
    configuration = new Configuration();
    events = Lists.newArrayList();
}

From source file:com.salesmanager.core.util.FileUtil.java

public static String getAdminPasswordResetUrl(MerchantUserInformation information, MerchantStore store)
        throws Exception {

    Configuration conf = PropertiesUtil.getConfiguration();

    StringBuffer urlconstruct = new StringBuffer();
    StringBuffer downloadurl = new StringBuffer();
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.DATE, conf.getInt("core.product.file.downloadmaxdays", 2)); // add 2 days
    Date denddate = endDate.getTime();
    String sedate = DateUtil.formatDate(denddate);

    // order id and, expiration date and language
    urlconstruct.append(information.getMerchantUserId()).append("|").append(sedate);

    String lang = conf.getString("core.system.defaultlanguage", "en");
    if (information != null) {
        lang = information.getUserlang();
    }//  www  .j a v a 2  s. c om

    String file = EncryptionUtil.encrypt(EncryptionUtil.generatekey(SecurityConstants.idConstant),
            urlconstruct.toString());

    downloadurl.append(ReferenceUtil.buildCentralUri(store))
            .append("/anonymous" + conf.getString("core.salesmanager.core.resetPasswordAction"))
            .append("?urlId=").append(file).append("&lang=").append(lang);

    return downloadurl.toString();

}

From source file:org.openmrs.module.kenyaemr.calculation.library.mchms.EddEstimateFromMchmsProgramCalculationTest.java

@Test
public void evaluate_shouldEstimateEddFromLmp() {

    Program mchmsProgram = MetadataUtils.existing(Program.class, MchMetadata._Program.MCHMS);

    //get female patients
    Patient p7 = TestUtils.getPatient(7);
    Patient p8 = TestUtils.getPatient(8);
    //enroll patient 7 into program
    TestUtils.enrollInProgram(p7, mchmsProgram, TestUtils.date(2014, 6, 1));
    TestUtils.enrollInProgram(p8, mchmsProgram, TestUtils.date(2014, 6, 1));
    //give p7 an lmp on date and expect edd to be 280 days later
    Date lmp = TestUtils.date(2014, 5, 1);
    Date edd = new Date();
    TestUtils.saveObs(p7, Dictionary.getConcept(Dictionary.LAST_MONTHLY_PERIOD), lmp,
            TestUtils.date(2014, 6, 1));
    //add 208 days on lmp to get edd
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(lmp);/* w  w w .j  a va2s. c  o m*/
    calendar.add(Calendar.DATE, 280);
    edd = calendar.getTime();

    List<Integer> cohort = Arrays.asList(6, 7, 8, 9);
    CalculationResultMap resultMap = new EddEstimateFromMchmsProgramCalculation().evaluate(cohort, null,
            Context.getService(PatientCalculationService.class).createCalculationContext());
    Assert.assertEquals(edd, resultMap.get(7).getValue()); //had lmp hence edd and eventually tally to date 280 days
    Assert.assertThat(resultMap.get(8).isEmpty(), is(false));

}

From source file:com.lohika.alp.reporter.fe.controller.TestController.java

private void setDefaultPeriod(TestFilter filter) {
    Calendar cal = Calendar.getInstance();

    // Set one day period if period is not set      
    if (filter.getFrom() == null || filter.getTill() == null) {
        filter.setTill(cal.getTime());/*w  ww. ja v  a2 s  . c o m*/
        cal.add(Calendar.DATE, -1);
        filter.setFrom(cal.getTime());
    }
}

From source file:com.cemeterylistingswebtest.test.services.ViewListingsBySubscriberServiceTest.java

@Test(enabled = false)
public void hello() {
    subserv = ctx.getBean(ViewListingBySubscriberService.class);
    repoList = ctx.getBean(PublishedDeceasedListingRepository.class);
    subRepo = ctx.getBean(SubscriberRepository.class);
    userRepo = ctx.getBean(UserRoleRepository.class);

    //Initialise date
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, 2008);
    calendar.set(Calendar.MONTH, Calendar.MARCH);
    calendar.set(Calendar.DATE, 5);

    java.sql.Date javaSqlDate = new java.sql.Date(calendar.getTime().getTime());

    //Initialise date
    Calendar calendar2 = Calendar.getInstance();
    calendar2.set(Calendar.YEAR, 2014);
    calendar2.set(Calendar.MONTH, Calendar.JUNE);
    calendar2.set(Calendar.DATE, 20);

    java.sql.Date validDate = new java.sql.Date(calendar2.getTime().getTime());

    //Initialise user role                
    UserRole userRole = new UserRole.Builder().setLevel(2).build();
    //userRepo.save(userRole);
    //userRoleID = userRole.getUserRoleID();

    //Initialise subscriber
    Subscriber newSub = new Subscriber.Builder().setEmail("jackieChan@yahoo.com").setFirstName("jackie")
            .setSurname("Chan").setPwd("whaa").setUsername("jChan").setSubscriptionDate(javaSqlDate)
            .setUserRoleID(userRole).setValidUntil(validDate).build();
    subRepo.save(newSub);// ww  w.  j  a  v  a 2 s.  c o m
    subID = newSub.getSubscriberID();

    PublishedDeceasedListing newListing = new PublishedDeceasedListing.Builder().setFirstName("Julie")
            .setSurname("Romanov").setMaidenName("black").setGender("Female").setDateOfBirth("08/06/1974")
            .setDateOfDeath("14/02/2009").setGraveInscription("triple agent").setGraveNumber("2986")
            .setImageOfBurialSite("/images/001.jpg")

            .setSubscriberSubmitID(subID).build();

    repoList.save(newListing);

    List<PublishedDeceasedListing> pubListDod = subserv.findListingBySubscriber(javaSqlDate, validDate);
    Assert.assertFalse(pubListDod.isEmpty());
    //Assert.assertTrue(pubListDod.isEmpty());
    repoList.delete(newListing);
    subRepo.delete(newSub);

}

From source file:com.lohika.alp.reporter.fe.controller.TestMethodController.java

private void setDefaultPeriod(TestMethodFilter filter) {
    Calendar cal = Calendar.getInstance();
    // Set one day period if period is not set
    if (filter.getFrom() == null || filter.getTill() == null) {
        filter.setTill(cal.getTime());/*from  w  ww .  ja v a  2s.  c om*/
        cal.add(Calendar.DATE, -1);
        filter.setFrom(cal.getTime());
    }
}

From source file:net.sourceforge.eclipsetrader.borsaitalia.HistoryFeed.java

public void updateHistory(Security security, int interval) {
    History history = null;//from  ww  w.  ja va  2s.  c o m
    Calendar from = Calendar.getInstance();
    from.set(Calendar.MILLISECOND, 0);

    if (interval < IHistoryFeed.INTERVAL_DAILY) {
        history = security.getIntradayHistory();
        from.set(Calendar.HOUR_OF_DAY, 0);
        from.set(Calendar.MINUTE, 0);
        from.set(Calendar.SECOND, 0);
        log.info("Updating intraday data for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        history = security.getHistory();
        if (history.size() == 0)
            from.add(Calendar.YEAR, -CorePlugin.getDefault().getPreferenceStore()
                    .getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
        else {
            Bar cd = history.getLast();
            from.setTime(cd.getDate());
            from.add(Calendar.DATE, 1);
        }
        log.info("Updating historical data for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
    }

    String symbol = null;
    if (security.getHistoryFeed() != null)
        symbol = security.getHistoryFeed().getSymbol();
    if (symbol == null || symbol.length() == 0)
        symbol = security.getCode();

    String code = security.getCode();
    if (code.indexOf('.') != -1)
        code = code.substring(0, code.indexOf('.'));

    try {
        String host = "194.185.192.223"; // "grafici.borsaitalia.it";
        StringBuffer url = new StringBuffer(
                "http://" + host + "/scripts/cligipsw.dll?app=tic_d&action=dwnld4push&cod=" + code + "&codneb=" //$NON-NLS-1$//$NON-NLS-2$
                        + symbol + "&req_type=GRAF_DS&ascii=1&form_id=");
        if (interval < IHistoryFeed.INTERVAL_DAILY)
            url.append("&period=1MIN"); //$NON-NLS-1$
        else {
            url.append("&period=1DAY"); //$NON-NLS-1$
            url.append("&From=" + df.format(from.getTime())); //$NON-NLS-1$
        }
        log.debug(url);

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = BorsaitaliaPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

        // The first line is the header, ignoring
        String inputLine = in.readLine();
        log.trace(inputLine);

        while ((inputLine = in.readLine()) != null) {
            log.trace(inputLine);
            if (inputLine.startsWith("@") == true || inputLine.length() == 0) //$NON-NLS-1$
                continue;
            String[] item = inputLine.split("\\|"); //$NON-NLS-1$

            Bar bar = new Bar();
            bar.setDate(df.parse(item[0]));
            bar.setOpen(Double.parseDouble(item[1]));
            bar.setHigh(Double.parseDouble(item[2]));
            bar.setLow(Double.parseDouble(item[3]));
            bar.setClose(Double.parseDouble(item[4]));
            bar.setVolume((long) Double.parseDouble(item[5]));

            // Remove the old bar, if exists
            int index = history.indexOf(bar.getDate());
            if (index != -1)
                history.remove(index);

            history.add(bar);
        }

        in.close();

    } catch (Exception e) {
        CorePlugin.logException(e);
    }

    CorePlugin.getRepository().save(history);
}