Example usage for java.util GregorianCalendar get

List of usage examples for java.util GregorianCalendar get

Introduction

In this page you can find the example usage for java.util GregorianCalendar get.

Prototype

public int get(int field) 

Source Link

Document

Returns the value of the given calendar field.

Usage

From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java

@RequestMapping(value = "reports", produces = { "application/json" }, method = RequestMethod.GET)
@ResponseBody/*from w  w w  . j  av  a2  s.com*/
//@ApiOperation(value = "reports", httpMethod = "GET")
public Page<ReportDataSet> getReportDatasets(

        @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
        @RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
        @RequestParam(value = "properties", required = false, defaultValue = "id") String sort,
        @RequestParam(value = "direction", required = false, defaultValue = "ASC") String direction,

        @RequestParam(value = "timeUnit", required = false, defaultValue = "DAY") TimeUnit timeUnit,
        @RequestParam(value = "dateField", required = false, defaultValue = "createdDate") String dateField,
        @RequestParam(value = "period", required = false) String period,
        @RequestParam(value = "reportType", required = false) String reportType) {

    if (StringUtils.isBlank(period)) {
        GregorianCalendar now = new GregorianCalendar();
        StringBuffer buff = new StringBuffer();
        if (timeUnit.equals(TimeUnit.DAY)) {
            buff.append(now.get(Calendar.MONTH)).append('/');
        }
        period = buff.append(now.get(Calendar.YEAR)).toString();
    }
    LOGGER.info("getReportDatasets, timeUnit: " + timeUnit + ", dateField: " + dateField + ", period: " + period
            + ", reportName: " + reportType);
    GregorianCalendar start = null;
    GregorianCalendar end = null;
    if (timeUnit.equals(TimeUnit.DAY)) {
        String[] monthYear = period.split("/");
        start = new GregorianCalendar(Integer.parseInt(monthYear[1]), Integer.parseInt(monthYear[0]) - 1, 0);
        end = new GregorianCalendar(Integer.parseInt(monthYear[1]), Integer.parseInt(monthYear[0]) - 1, 0);
        end.set(Calendar.DAY_OF_MONTH, end.getActualMaximum(Calendar.DAY_OF_MONTH));
    } else {
        start = new GregorianCalendar(Integer.parseInt(period), 0, 0);
        end = new GregorianCalendar(Integer.parseInt(period), 11, 0);
        end.set(Calendar.DAY_OF_MONTH, end.getActualMaximum(Calendar.DAY_OF_MONTH));
    }

    start.set(Calendar.HOUR_OF_DAY, start.getMinimum(Calendar.HOUR_OF_DAY));
    start.set(Calendar.MINUTE, start.getMinimum(Calendar.MINUTE));
    start.set(Calendar.SECOND, start.getMinimum(Calendar.SECOND));
    start.set(Calendar.MILLISECOND, start.getMinimum(Calendar.MILLISECOND));

    end.set(Calendar.HOUR_OF_DAY, end.getMinimum(Calendar.HOUR_OF_DAY));
    end.set(Calendar.MINUTE, end.getMinimum(Calendar.MINUTE));
    end.set(Calendar.SECOND, end.getMinimum(Calendar.SECOND));
    end.set(Calendar.MILLISECOND, end.getMinimum(Calendar.MILLISECOND));

    Map<String, String[]> paramsMap = request.getParameterMap();
    LOGGER.info("getReportDatasets, timeUnit: " + timeUnit + ", dateField: " + dateField + ", dateFrom: "
            + start + ", dateTo: " + end + ", reportName: " + reportType);
    Pageable pageable = buildPageable(page, size, sort, direction, paramsMap);
    Page<ReportDataSet> results = this.service.getReportDatasets(pageable, timeUnit, dateField, start.getTime(),
            end.getTime(), reportType);
    LOGGER.info("getReportDatasets returning " + results.getTotalElements());
    return results;
}

From source file:edu.stanford.muse.index.EmailDocument.java

public String getSignature() {
    StringBuilder sb = new StringBuilder();
    StringBuilder timeSB = new StringBuilder();
    Formatter formatter = new Formatter(timeSB);
    if (this.date != null) {
        GregorianCalendar cc = new GregorianCalendar();
        cc.setTime(this.date);
        formatter.format("%02d:%02d",
                new Object[] { Integer.valueOf(cc.get(11)), Integer.valueOf(cc.get(12)) });
        sb.append("Date: " + cc.get(5) + " " + CalendarUtil.getDisplayMonth(cc) + " " + cc.get(1) + " " + timeSB
                + "\n");
    }/*from   ww  w. j  a va  2 s. co  m*/

    formatter.close();
    sb.append("From: " + this.getFromString() + "\n");
    sb.append("To: " + this.getToString() + "\n");
    String cc1 = this.getCcString();
    if (!Util.nullOrEmpty(cc1)) {
        sb.append("Cc: " + cc1 + "\n");
    }

    String bcc = this.getBccString();
    if (!Util.nullOrEmpty(bcc)) {
        sb.append("Bcc: " + bcc + "\n");
    }

    if (this.description == null) {
        this.description = "<None>";
    }

    sb.append("Subject: " + this.description + "\n");
    sb.append("\n");
    return sb.toString();
}

From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java

@SuppressWarnings("unchecked")
private static Attribute getAttribute(String attributeName, GregorianCalendar attributeValue) {

    Attribute attribute = buildXMLObject(Attribute.class, Attribute.DEFAULT_ELEMENT_NAME);
    attribute.setName(attributeName);/*w w  w  .j a v a2 s .  c o  m*/

    XMLObjectBuilder<XSDateTime> builder = Configuration.getBuilderFactory().getBuilder(XSDateTime.TYPE_NAME);
    XSDateTime xmlAttributeValue = builder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME,
            XSDateTime.TYPE_NAME);

    // convert to Zulu timezone
    int day = attributeValue.get(Calendar.DAY_OF_MONTH);
    int month = attributeValue.get(Calendar.MONTH);
    int year = attributeValue.get(Calendar.YEAR);
    LOG.debug("day: " + day + " month: " + month + " year: " + year);
    DateTime zulu = new DateTime(year, month + 1, day, 0, 0, 0, 0, ISOChronology.getInstanceUTC());
    xmlAttributeValue.setValue(zulu);
    attribute.getAttributeValues().add(xmlAttributeValue);

    LOG.debug("XmlAttributeValue: " + xmlAttributeValue.getValue());

    return attribute;
}

From source file:org.webical.test.web.component.WeekViewPanelTest.java

public void testWithoutEvents() {

    annotApplicationContextMock.putBean("eventManager", new MockEventManager());

    final GregorianCalendar currentDate = CalendarUtils.newTodayCalendar(getFirstDayOfWeek());

    // Create test page with a WeekViewPanel
    wicketTester.startPage(new ITestPageSource() {
        private static final long serialVersionUID = 1L;

        public Page getTestPage() {
            return new PanelTestPage(new WeekViewPanel(PanelTestPage.PANEL_MARKUP_ID, 7, currentDate) {
                private static final long serialVersionUID = 1L;

                @Override//w  w  w .  j a  va2  s.c o  m
                public void onAction(IAction action) {
                    /* NOTHING TO DO */ }
            });
        }
    });

    // Basic assertions
    wicketTester.assertRenderedPage(PanelTestPage.class);
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID, WeekViewPanel.class);

    // Assert number of days rendered
    GregorianCalendar weekFirstDayCalendar = CalendarUtils.duplicateCalendar(currentDate);
    weekFirstDayCalendar.setTime(CalendarUtils.getFirstDayOfWeek(currentDate.getTime(), getFirstDayOfWeek()));
    // Assert the first day in the view
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day"
            + weekFirstDayCalendar.get(GregorianCalendar.DAY_OF_YEAR), WeekDayPanel.class);

    GregorianCalendar weekLastDayCalendar = CalendarUtils.duplicateCalendar(currentDate);
    weekLastDayCalendar.setTime(CalendarUtils.getLastDayOfWeek(currentDate.getTime(), getFirstDayOfWeek()));
    // Assert the last day in the view
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day"
            + weekLastDayCalendar.get(GregorianCalendar.DAY_OF_YEAR), WeekDayPanel.class);

    // Assert the heading label
    DateFormat dateFormat = new SimpleDateFormat("E", getTestSession().getLocale());
    GregorianCalendar weekCal = CalendarUtils.duplicateCalendar(currentDate);
    weekCal.setTime(CalendarUtils.getFirstDayOfWeek(currentDate.getTime(), getFirstDayOfWeek()));
    for (int i = 0; i < 7; ++i) {
        wicketTester.assertLabel(PanelTestPage.PANEL_MARKUP_ID + ":dayHeadingRepeater:headerDay" + i,
                dateFormat.format(weekCal.getTime()));
        weekCal.add(GregorianCalendar.DAY_OF_WEEK, 1);
    }
}

From source file:ome.formats.importer.gui.HistoryTable.java

/**
 * Update the outlook bar with base data for appropriate dates
 *//*from  w  w w.  ja va 2 s .  co  m*/
public void updateOutlookBar() {
    GregorianCalendar newCal = new GregorianCalendar();
    int dayOfWeek = newCal.get(Calendar.DAY_OF_WEEK);
    int dayOfMonth = newCal.get(Calendar.DAY_OF_MONTH);

    DefaultListModel today = db.getBaseTableDataByDate(db.getStartOfDay(new Date()),
            db.getEndOfDay(new Date()));
    historyTaskBar.updateList(todayList, historyTaskBar.today, today);

    DefaultListModel yesterday = db.getBaseTableDataByDate(db.getStartOfDay(db.getYesterday()),
            db.getEndOfDay(db.getYesterday()));
    historyTaskBar.updateList(yesterdayList, historyTaskBar.yesterday, yesterday);

    DefaultListModel thisWeek = db.getBaseTableDataByDate(
            db.getStartOfDay(db.getDaysBefore(new Date(), -(dayOfWeek))), db.getEndOfDay(new Date()));
    historyTaskBar.updateList(thisWeekList, historyTaskBar.thisWeek, thisWeek);

    DefaultListModel lastWeek = db.getBaseTableDataByDate(
            db.getStartOfDay(db.getDaysBefore(new Date(), -(dayOfWeek + 7))),
            db.getEndOfDay(db.getDaysBefore(new Date(), -(dayOfWeek))));
    historyTaskBar.updateList(lastWeekList, historyTaskBar.lastWeek, lastWeek);

    DefaultListModel thisMonth = db.getBaseTableDataByDate(
            db.getStartOfDay(db.getDaysBefore(new Date(), -(dayOfMonth))), db.getEndOfDay(new Date()));
    historyTaskBar.updateList(thisMonthList, historyTaskBar.thisMonth, thisMonth);
}

From source file:org.mariotaku.twidere.api.twitter.util.TwitterDateConverter.java

private Date parseTwitterDate(String string) {
    final String[] segs = StringUtils.split(string, ' ');
    if (segs.length != 6) {
        return null;
    }//from w w  w  . java  2s.  c  o m
    final String[] timeSegs = StringUtils.split(segs[3], ':');
    if (timeSegs.length != 3) {
        return null;
    }

    final GregorianCalendar calendar = new GregorianCalendar(TIME_ZONE, LOCALE);
    calendar.clear();
    final int monthIdx = ArrayUtils.indexOf(MONTH_NAMES, segs[1]);
    if (monthIdx < 0) {
        return null;
    }
    calendar.set(Calendar.YEAR, Integer.parseInt(segs[5]));
    calendar.set(Calendar.MONTH, monthIdx);
    calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(segs[2]));
    calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSegs[0]));
    calendar.set(Calendar.MINUTE, Integer.parseInt(timeSegs[1]));
    calendar.set(Calendar.SECOND, Integer.parseInt(timeSegs[2]));
    calendar.set(Calendar.ZONE_OFFSET, SimpleTimeZone.getTimeZone("GMT" + segs[4]).getRawOffset());
    final Date date = calendar.getTime();
    if (!WEEK_NAMES[calendar.get(Calendar.DAY_OF_WEEK) - 1].equals(segs[0])) {
        AbsLogger.error("Week mismatch " + string + " => " + date);
        return null;
    }
    return date;
}

From source file:org.webical.test.web.component.WeekViewPanelTest.java

/**
 * Test week view with less then 7 days//from ww  w . jav a  2 s .c  o m
 * @throws WebicalException
 */
public void testNonWeekUse() throws WebicalException {

    MockCalendarManager mockCalendarManager = (MockCalendarManager) annotApplicationContextMock
            .getBean("calendarManager");
    Calendar calendar1 = mockCalendarManager.getCalendarById("1");

    MockEventManager mockEventManager = new MockEventManager();
    annotApplicationContextMock.putBean("eventManager", mockEventManager);

    // Define the current date
    final GregorianCalendar currentDate = CalendarUtils.newTodayCalendar(getFirstDayOfWeek());
    currentDate.setFirstDayOfWeek(GregorianCalendar.MONDAY);

    // The list containing the different events
    List<Event> allEvents = new ArrayList<Event>();

    GregorianCalendar refcal = CalendarUtils.duplicateCalendar(currentDate);
    refcal.add(GregorianCalendar.DAY_OF_MONTH, 1);
    refcal.set(GregorianCalendar.HOUR_OF_DAY, 12);
    refcal.set(GregorianCalendar.MINUTE, 0);
    refcal.set(GregorianCalendar.SECOND, 0);

    GregorianCalendar cal = CalendarUtils.duplicateCalendar(currentDate);

    // Add a normal event tomorrow
    Event event = new Event();
    event.setUid("e1");
    event.setCalendar(calendar1);
    event.setSummary("Normal Event Description");
    event.setLocation("Normal Event Location");
    event.setDescription("Event e1");
    cal.setTime(refcal.getTime());
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    event.setDtEnd(cal.getTime());
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Add a short recurring event, starting today, ending tomorrow
    event = new Event();
    event.setUid("e2");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Today");
    event.setLocation("Recurring Event Location");
    event.setDescription("Event e2");
    cal.setTime(refcal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, -1);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    cal.add(GregorianCalendar.DAY_OF_MONTH, 2);
    event.setDtEnd(cal.getTime());
    RecurrenceUtil.setRecurrenceRule(event,
            new Recurrence(Recurrence.DAILY, 1, CalendarUtils.getEndOfDay(cal.getTime())));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Add a long recurring event, starting last week, ending next week
    event = new Event();
    event.setUid("e3");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Last Month");
    event.setLocation("Recurring Event Location");
    event.setDescription("Event e3");
    cal.setTime(refcal.getTime());
    cal.add(GregorianCalendar.WEEK_OF_YEAR, -1);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    cal.add(GregorianCalendar.WEEK_OF_YEAR, 3);
    event.setDtEnd(cal.getTime());
    RecurrenceUtil.setRecurrenceRule(event,
            new Recurrence(Recurrence.DAILY, 1, CalendarUtils.getEndOfDay(cal.getTime())));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Add a (pseudo) all day event, starting day + 1 midnight, ending day + 2 00:00 hours
    event = new Event();
    event.setUid("e4");
    event.setCalendar(calendar1);
    event.setSummary("Pseudo All Day Event");
    event.setLocation("All Day Event Location");
    event.setDescription("Starting day + 1, ending day + 2 00:00 hours");
    cal.setTime(refcal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, 1);
    cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
    cal.set(GregorianCalendar.MINUTE, 0);
    cal.set(GregorianCalendar.SECOND, 0);
    cal.set(GregorianCalendar.MILLISECOND, 0);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, 1);
    event.setDtEnd(cal.getTime());
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Create test page with a WeekViewPanel
    wicketTester.startPage(new ITestPageSource() {
        private static final long serialVersionUID = 1L;

        public Page getTestPage() {
            return new PanelTestPage(new WeekViewPanel(PanelTestPage.PANEL_MARKUP_ID, 4, currentDate) {
                private static final long serialVersionUID = 1L;

                @Override
                public void onAction(IAction action) {
                    /* NOTHING TO DO */ }
            });
        }
    });

    // Basic assertions
    wicketTester.assertRenderedPage(PanelTestPage.class);
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID, WeekViewPanel.class);

    // Assert number of days rendered
    // Set the correct dates to find the first and last day of the week
    GregorianCalendar viewFirstDayCalendar = CalendarUtils.duplicateCalendar(currentDate);
    // Assert the first day in the view
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day"
            + viewFirstDayCalendar.get(GregorianCalendar.DAY_OF_YEAR), WeekDayPanel.class);

    GregorianCalendar viewLastDayCalendar = CalendarUtils.duplicateCalendar(currentDate);
    viewLastDayCalendar.add(GregorianCalendar.DAY_OF_MONTH, 3);
    // Assert the last day in the view
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day"
            + viewLastDayCalendar.get(GregorianCalendar.DAY_OF_YEAR), WeekDayPanel.class);

    // Events for days in this 4 day period
    List<Event> dayEvents = new ArrayList<Event>();
    // Assert weekday events
    GregorianCalendar weekCal = CalendarUtils.duplicateCalendar(currentDate);
    for (int i = 0; i < 4; ++i) {
        WeekDayPanel weekDayEventsListView = (WeekDayPanel) wicketTester.getLastRenderedPage()
                .get(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day"
                        + weekCal.get(GregorianCalendar.DAY_OF_YEAR));
        switch (i) {
        case 0:
            dayEvents.clear();
            dayEvents.add(allEvents.get(1)); // e2
            dayEvents.add(allEvents.get(2)); // e3
            break;
        case 1:
            dayEvents.clear();
            dayEvents.add(allEvents.get(0)); // e1
            dayEvents.add(allEvents.get(1)); // e2
            dayEvents.add(allEvents.get(2)); // e3
            break;
        case 2:
            dayEvents.clear();
            dayEvents.add(allEvents.get(1)); // e2
            dayEvents.add(allEvents.get(2)); // e3
            dayEvents.add(allEvents.get(3)); // e4
            break;
        case 3:
            dayEvents.clear();
            dayEvents.add(allEvents.get(2)); // e3
            break;
        }
        String path = weekDayEventsListView.getPageRelativePath() + ":eventItem";
        wicketTester.assertListView(path, dayEvents);

        ListView listView = (ListView) wicketTester.getComponentFromLastRenderedPage(path);
        Iterator<?> lvIt = listView.iterator();
        while (lvIt.hasNext()) {
            ListItem item = (ListItem) lvIt.next();
            Event evt = (Event) item.getModelObject();
            List<?> bhvs = item.getBehaviors();
            if (evt.getUid().equals("e4"))
                assertEquals(1, bhvs.size()); // e4 all day event
            else
                assertEquals(0, bhvs.size());
        }

        weekCal.add(GregorianCalendar.DAY_OF_WEEK, 1);
    }
}

From source file:gov.noaa.pfel.erddap.dataset.EDDTableFromHttpGet.java

/**
     * This figures out the name of the relevant file (which may or 
     * may not exist.//from  w w w.  ja v a  2  s  .c o  m
     *
     * @param startDir with trailing slash
     * @param tDirStructureColumnNames For each part, the variable's source column name
     *   or "" if not used for this part.
     *   Any column names here should be in requiredColumnNames.
     * @param tDirStructureNs     For each part, the number of YEAR, MONTH, ...
     *   or -1 if not used for this part
     * @param tDirStructureCalendars  For each part, 
     *   Calendar.YEAR, MONTH, DATE, HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND, 
     *   or -1 if not used for this part
     * @param tColumnNames  the source names of the columns
     * @param tColumnValues the source values associated with the tColumnNames.
     *    All should have the same size().
     *    Only values on the specified row will be used.
     * @param row the value of the rightmost array of tColumnSourceValues
     * @param timeEpSec the time value, in epoch seconds.
     *   It is usually a requiredColumn, but not always.
     *   It is an error if it is needed here, but timeEpSec is NaN.
     * @return the full file dir+name, starting with startDir.
     */
    public static String whichFile(String startDir, StringArray tDirStructureColumnNames, IntArray tDirStructureNs,
            IntArray tDirStructureCalendars, String tColumnNames[], PrimitiveArray tColumnValues[], int row,
            double timeEpSec) {

        StringBuilder dirSB = new StringBuilder(startDir);
        StringBuilder nameSB = new StringBuilder();
        int nParts = tDirStructureColumnNames.size();
        for (int i = 0; i < nParts; i++) {
            if (i > 0) {
                dirSB.append('/');
                nameSB.append('_');
            }
            int cal = tDirStructureCalendars.get(i);
            if (cal == -1) {
                //Find the var. Add its value.
                int sni = String2.indexOf(tColumnNames, tDirStructureColumnNames.get(i));
                if (sni < 0)
                    throw new SimpleException(String2.ERROR + " in directoryStructure part#" + i + ": column="
                            + tDirStructureColumnNames.get(i) + " isn't in columnNames="
                            + String2.toCSSVString(tColumnNames) + ".");
                //data value of "" is a valid value. It will be converted to something.
                String tp = String2.encodeFileNameSafe(tColumnValues[sni].getString(row));
                if (i < nParts - 1)
                    dirSB.append(tp);
                nameSB.append(tp);

            } else {
                //Find the time part. Round down to n'th precision. 
                //e.g., 17 seconds to 5seconds precision is 15 seconds.
                //(MONTH is 0-based, so that works correctly as is.)
                if (!Double.isFinite(timeEpSec))
                    throw new SimpleException(
                            String2.ERROR + " in directoryStructure part#" + i + ": time value is NaN!");
                //need a new gc for each part since gc is modified
                GregorianCalendar gc = Calendar2.epochSecondsToGc(timeEpSec);
                int n = tDirStructureNs.get(i);
                gc.set(cal, (gc.get(cal) / n) * n);
                //Get the ISO 8601 date/time string just to that precision/field.
                String s = Calendar2.formatAsISODateTimeT3(gc); //to millis 
                int nChar = s.length();
                if (cal == Calendar.YEAR)
                    nChar = 4;
                else if (cal == Calendar.MONTH)
                    nChar = 7;
                else if (cal == Calendar.DATE)
                    nChar = 10;
                else if (cal == Calendar.HOUR_OF_DAY)
                    nChar = 13;
                else if (cal == Calendar.MINUTE)
                    nChar = 16;
                else if (cal == Calendar.SECOND)
                    nChar = 19;
                //else to millis precision
                String tp = s.substring(0, nChar);
                tp = String2.replaceAll(tp, ':', '-'); //make fileNameSafe
                if (i < nParts - 1)
                    dirSB.append(tp);
                nameSB.append(tp);
            }
        }

        return dirSB.toString() + nameSB.toString() + ".nc";
    }

From source file:org.accada.epcis.repository.query.Schedule.java

/**
 * Returns true if the month and all smaller time units have been
 * successfully set to valid values.// www  . ja v a  2s  .  c o  m
 * 
 * @param nextSchedule
 *            The current candidate for the result.
 * @return True if month and smaller units successfully set to valid values.
 * @throws ImplementationException
 *             Almost any kind of error.
 */
private boolean monthMadeValid(final GregorianCalendar nextSchedule) throws ImplementationExceptionResponse {
    // check if the month of the current time is valid, i.e. there is a
    // month value in the schedule equal to the month value of the current
    // time
    while (!months.isEmpty() && !months.contains(Integer.valueOf(nextSchedule.get(MONTH)))) {
        // no, month value of the current time is invalid
        // roll the month (set it to the next value)
        if (!setFieldToNextValidRoll(nextSchedule, MONTH, DAY_OF_MONTH)) {
            return false;
        }
    }
    // now we're in a valid month, make smaller units valid as well or go to
    // next month
    while (!dayMadeValid(nextSchedule)) {
        // no valid day for this month, try next
        if (!setFieldToNextValidRoll(nextSchedule, MONTH, DAY_OF_MONTH)) {
            return false;
        }
        // reset all smaller units to minimum
        if (!setFieldsToMinimum(nextSchedule, DAY_OF_MONTH)) {
            return false;
        }
    }
    return true;
}

From source file:org.opendatakit.aggregate.externalservice.REDCapServer.java

@Override
protected void insertData(Submission submission, CallingContext cc) throws ODKExternalServiceException {

    try {// www. j av a2  s.  c  om
        // an empty map to hold our values
        String study_id = null;

        // create a hash to hold the blobs for later processing
        Map<String, BlobSubmissionType> blobs = new HashMap<String, BlobSubmissionType>();

        StringBuilder b = new StringBuilder();

        Map<FormElementModel, SubmissionValue> valuesMap = submission.getSubmissionValuesMap();

        for (FormElementModel element : valuesMap.keySet()) {
            SubmissionValue value = valuesMap.get(element);
            if (value == null) {
                continue;
            }
            if (element.isMetadata()) {
                // handle metadata specially
            } else {
                switch (element.getElementType()) {
                case METADATA:
                    // This keeps lint warnings down...
                    break;
                case STRING: {
                    StringSubmissionType str = (StringSubmissionType) value;
                    String strValue = str.getValue();
                    if (element.getElementName().equals("study_id")) {
                        // Piece of crap parser in REDCap requires study id to be first
                        // element
                        study_id = strValue;
                    } else if (strValue != null) {
                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case JRDATETIME: {
                    JRDateTimeType dt = (JRDateTimeType) value;
                    Date dtValue = dt.getValue();

                    if (dtValue != null) {
                        GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
                        g.setTime(dtValue);

                        String strValue = String.format(FormatConsts.REDCAP_DATE_TIME_FORMAT_STRING,
                                g.get(Calendar.YEAR), g.get(Calendar.MONTH) + 1, g.get(Calendar.DAY_OF_MONTH),
                                g.get(Calendar.HOUR_OF_DAY), g.get(Calendar.MINUTE), g.get(Calendar.SECOND));

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");

                    }
                }
                    break;

                case JRDATE: {
                    JRDateType dt = (JRDateType) value;
                    Date dtValue = dt.getValue();

                    if (dtValue != null) {
                        GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
                        g.setTime(dtValue);

                        String strValue = String.format(FormatConsts.REDCAP_DATE_ONLY_FORMAT_STRING,
                                g.get(Calendar.YEAR), g.get(Calendar.MONTH) + 1, g.get(Calendar.DAY_OF_MONTH));

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case JRTIME: {
                    JRTimeType dt = (JRTimeType) value;
                    Date dtValue = dt.getValue();

                    if (dtValue != null) {
                        GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
                        g.setTime(dtValue);

                        String strValue = String.format(FormatConsts.REDCAP_TIME_FORMAT_STRING,
                                g.get(Calendar.HOUR_OF_DAY), g.get(Calendar.MINUTE));

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case INTEGER: {
                    LongSubmissionType longVal = (LongSubmissionType) value;
                    if (longVal.getValue() != null) {
                        String strValue = longVal.getValue().toString();

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case DECIMAL: {
                    DecimalSubmissionType dec = (DecimalSubmissionType) value;
                    if (dec.getValue() != null) {
                        String strValue = dec.getValue().toString();

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case GEOPOINT: {
                    // TODO: should not have gps_ prefix on tag...
                    String strippedElementName = element.getElementName().replace("gps_", "");
                    GeoPointSubmissionType submissionValue = (GeoPointSubmissionType) value;
                    GeoPoint coors = submissionValue.getValue();
                    if (coors.getLatitude() != null) {
                        b.append("<").append("gps_lat_" + strippedElementName).append(">")
                                .append(StringEscapeUtils.escapeXml10(coors.getLatitude().toString()))
                                .append("</").append("gps_lat_" + strippedElementName).append(">");

                        b.append("<").append("gps_lon_" + strippedElementName).append(">")
                                .append(StringEscapeUtils.escapeXml10(coors.getLongitude().toString()))
                                .append("</").append("gps_lon_" + strippedElementName).append(">");

                        b.append("<").append("gps_alt_" + strippedElementName).append(">")
                                .append(StringEscapeUtils.escapeXml10(coors.getAltitude().toString()))
                                .append("</").append("gps_alt_" + strippedElementName).append(">");

                        b.append("<").append("gps_acc_" + strippedElementName).append(">")
                                .append(StringEscapeUtils.escapeXml10(coors.getAccuracy().toString()))
                                .append("</").append("gps_acc_" + strippedElementName).append(">");
                    }
                }
                    break;

                case BINARY: {
                    String file_field = element.getElementName();
                    BlobSubmissionType blob_value = (BlobSubmissionType) value;
                    if (blob_value.getAttachmentCount(cc) == 1) {
                        blobs.put(file_field, blob_value);
                    }
                    // upload these after we have successfully imported the record
                }
                    break;

                case BOOLEAN: {
                    String strippedElementName = element.getElementName().replace("slct-", "");
                    BooleanSubmissionType bType = (BooleanSubmissionType) value;
                    if (bType.getValue() != null) {
                        b.append("<").append(strippedElementName + "___" + bType.getValue().toString())
                                .append(">").append(StringEscapeUtils.escapeXml10("1")).append("</")
                                .append(strippedElementName + "___" + bType.getValue().toString()).append(">");
                    }
                }
                    break;

                case SELECT1:
                case SELECTN: {
                    // TODO: it's not necessary to add (or remove) 'slct-' from
                    // the field name anymore
                    String formatElementName = element.getElementName().replace("slct-", "");
                    ChoiceSubmissionType choice = (ChoiceSubmissionType) value;
                    for (String choiceVal : choice.getValue()) {
                        b.append("<").append(formatElementName + "___" + choiceVal).append(">")
                                .append(StringEscapeUtils.escapeXml10("1")).append("</")
                                .append(formatElementName + "___" + choiceVal).append(">");
                    }
                }
                    break;

                case REPEAT: {
                    logger.warn("Unable to publish repeat groups to REDCap");
                    // REDCap does not handle repeat groups.
                }
                    break;

                case GROUP:
                    logger.warn("The GROUP submission type is not implemented");
                    break;

                }
            }
        }

        b.append("</item></records>");

        if (study_id == null) {
            throw new IllegalStateException("Form does not contain a study_id field -- cannot publish!");
        }

        String submissionsListString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><records><item><study_id>"
                + StringEscapeUtils.escapeXml10(study_id) + "</study_id>" + b.toString();

        List<NameValuePair> eparams = new ArrayList<NameValuePair>();
        eparams.add(new BasicNameValuePair("token", getApiKey()));
        eparams.add(new BasicNameValuePair("content", "record"));
        eparams.add(new BasicNameValuePair("format", "xml"));
        eparams.add(new BasicNameValuePair("overwriteBehavior", "overwrite"));
        eparams.add(new BasicNameValuePair("data", submissionsListString));
        eparams.add(new BasicNameValuePair("returnContent", "ids"));
        eparams.add(new BasicNameValuePair("returnFormat", "xml"));

        HttpEntity postentity = new UrlEncodedFormEntity(eparams, UTF_CHARSET);

        submitPost("Publishing", postentity, null, cc);

        // send the files if they exist
        for (Map.Entry<String, BlobSubmissionType> e : blobs.entrySet()) {
            System.out.println("Processing media attachment....");
            BlobSubmissionType blob = e.getValue();
            submitFile(study_id, e.getKey(), blob, cc);
        }

    } catch (Exception e) {
        throw new ODKExternalServiceException(e);
    }

}