Example usage for java.util GregorianCalendar setTime

List of usage examples for java.util GregorianCalendar setTime

Introduction

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

Prototype

public final void setTime(Date date) 

Source Link

Document

Sets this Calendar's time with the given Date.

Usage

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

public void testWithEvents() throws WebicalException {

    // Get the CalendarManager.
    MockCalendarManager mockCalendarManager = (MockCalendarManager) annotApplicationContextMock
            .getBean("calendarManager");
    Calendar calendar1 = mockCalendarManager.getCalendarById("1");

    // Add an EventManager for the test Events.
    MockEventManager mockEventManager = new MockEventManager();
    annotApplicationContextMock.putBean("eventManager", mockEventManager);

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

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

    // Create list with events for the manager
    final List<Event> events = new ArrayList<Event>();
    // Add a normal event
    Event event = new Event();
    event.setUid("e1");
    event.setCalendar(calendar1);//from   w  ww  .j  a v  a 2  s. c  o  m
    event.setSummary("Normal Event Summary");
    event.setLocation("Normal Event Location");
    event.setDescription("Normal Event Description");
    event.setDtStart(refcal.getTime());
    event.setDtEnd(CalendarUtils.addHours(refcal.getTime(), 2));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Add a recurring event, starting yesterday, ending tommorrow
    event = new Event();
    event.setUid("e2");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Yesterday Summary");
    event.setLocation("Recurring Event Location");
    event.setDescription("Recurring Event Yesterday Description");
    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(0, 1, cal.getTime()));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

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

    // Add a (pseudo) all day event, starting today 00:00 hours, ending today 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 yesterday midnight, ending today 00:00 hours");
    cal.setTime(refcal.getTime());
    cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
    cal.set(GregorianCalendar.MINUTE, 0);
    cal.set(GregorianCalendar.SECOND, 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());
    events.add(event);
    mockEventManager.storeEvent(event);

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

        public Page getTestPage() {
            return new PanelTestPage(new DayViewPanel(PanelTestPage.PANEL_MARKUP_ID, 1, 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, DayViewPanel.class);

    // Assert the heading label
    DateFormat dateFormat = new SimpleDateFormat("EEEE", getTestSession().getLocale());
    wicketTester.assertLabel(PanelTestPage.PANEL_MARKUP_ID + ":dayLink",
            dateFormat.format(currentDate.getTime()));

    // Assert the number of events rendered
    String panelPath = PanelTestPage.PANEL_MARKUP_ID + ":eventItem";
    wicketTester.assertListView(panelPath, events);
}

From source file:org.opendatakit.aggregate.odktables.api.perf.AggregateSynchronizer.java

/**
 * Simple Resource for all server interactions.
 * /*from  w  ww . jav a 2  s .  co m*/
 * @param uri
 * @return
 * @throws InvalidAuthTokenException 
 */
private Resource buildBasicResource(URI uri) throws InvalidAuthTokenException {

    Resource rsc = rt.resource(uri);

    // report our locale... (not currently used by server)
    rsc.acceptLanguage(Locale.getDefault());

    // set the access token...
    rsc.header(ApiConstants.ACCEPT_CONTENT_ENCODING_HEADER, ApiConstants.GZIP_CONTENT_ENCODING);
    rsc.header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION);
    rsc.header(HttpHeaders.USER_AGENT, "Sync it (gzip)");
    GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    Date now = new Date();
    g.setTime(now);
    SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz", Locale.US);
    formatter.setCalendar(g);
    rsc.header(ApiConstants.DATE_HEADER, formatter.format(now));

    if (accessToken != null && baseUri != null) {
        if (uri.getHost().equals(baseUri.getHost()) && uri.getPort() == baseUri.getPort()) {
            rsc.header("Authorization", "Bearer " + accessToken);
        }
    }

    return rsc;
}

From source file:org.fosstrak.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * {@inheritDoc}/* w w  w . j  av  a2 s.  c o m*/
 */
public Map<String, QuerySubscriptionScheduled> fetchSubscriptions(final QueryOperationsSession session)
        throws SQLException, ImplementationExceptionResponse {
    String query = "SELECT * FROM subscription";
    LOG.debug("SQL: " + query);
    Statement stmt = session.getConnection().createStatement();
    QuerySubscriptionScheduled storedSubscription;
    GregorianCalendar initrectime = new GregorianCalendar();

    ResultSet rs = stmt.executeQuery(query);
    Map<String, QuerySubscriptionScheduled> subscribedMap = new HashMap<String, QuerySubscriptionScheduled>();
    while (rs.next()) {
        try {
            String subscrId = rs.getString("subscriptionid");

            ObjectInput in = new ObjectInputStream(rs.getBinaryStream("params"));
            QueryParams params = (QueryParams) in.readObject();

            String dest = rs.getString("dest");

            in = new ObjectInputStream(rs.getBinaryStream("sched"));
            Schedule sched = (Schedule) in.readObject();

            initrectime.setTime(rs.getTimestamp("initialrecordingtime"));

            boolean exportifempty = rs.getBoolean("exportifempty");

            String queryName = rs.getString("queryname");
            String trigger = rs.getString("trigg");

            if (trigger == null || trigger.length() == 0) {
                storedSubscription = new QuerySubscriptionScheduled(subscrId, params, dest,
                        Boolean.valueOf(exportifempty), initrectime, new GregorianCalendar(), sched, queryName);
            } else {
                storedSubscription = new QuerySubscriptionTriggered(subscrId, params, dest,
                        Boolean.valueOf(exportifempty), initrectime, new GregorianCalendar(), queryName,
                        trigger, sched);
            }
            subscribedMap.put(subscrId, storedSubscription);
        } catch (SQLException e) {
            // sql exceptions are passed on
            throw e;
        } catch (Exception e) {
            // all other exceptions are caught
            String msg = "Unable to restore subscribed queries from the database.";
            LOG.error(msg, e);
            ImplementationException iex = new ImplementationException();
            iex.setReason(msg);
            iex.setSeverity(ImplementationExceptionSeverity.ERROR);
            throw new ImplementationExceptionResponse(msg, iex, e);
        }
    }
    return subscribedMap;
}

From source file:de.tuttas.servlets.DokuServlet.java

private Document createVertretungsliste(Date parsedFrom, Date parsedTo, OutputStream out)
        throws DocumentException, BadElementException, IOException {
    Document document = new Document();
    Log.d("create Vertretungsliste von " + parsedFrom.toString() + " bis" + parsedTo.toString());
    GregorianCalendar cf = (GregorianCalendar) GregorianCalendar.getInstance();
    cf.setTime(parsedFrom);
    GregorianCalendar ct = (GregorianCalendar) GregorianCalendar.getInstance();
    ct.setTime(parsedTo);/*w ww.j a  v  a  2 s.  c om*/
    /* Basic PDF Creation inside servlet */
    PdfWriter writer = PdfWriter.getInstance(document, out);
    StringBuilder htmlString = new StringBuilder();
    String kopf = "";
    kopf += ("<table border='1' align='center' width='100%'>");
    kopf += ("<tr>");
    kopf += ("<td rowspan=\"3\" width='150px'></td>");
    kopf += ("<td align='center'><h2>Multi Media Berufsbildende Schulen Hannover</h2></td>");

    kopf += ("<td colspan=\"2\" align='center'><b>Digitales Klassenbuch Vertretungsliste</b></td>");
    kopf += ("</tr>");
    kopf += ("<tr>");
    kopf += ("<td  align='center' rowspan=\"2\"><h3>von " + toReadableDate(cf) + " bis " + toReadableDate(ct)
            + "</h3></td>");
    kopf += ("<td  style=\"font-size: 11;padding:4px;height:30px;\">Verantwortlicher: BO&nbsp;</td>");
    kopf += ("<td  style=\"font-size: 11;padding:4px;\">geprft</td>");
    kopf += ("</tr>");
    kopf += ("<tr>");
    DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
    Calendar c = df.getCalendar();
    c.setTimeInMillis(System.currentTimeMillis());
    String dat = c.get(Calendar.DAY_OF_MONTH) + "." + (c.get(Calendar.MONTH) + 1) + "." + c.get(Calendar.YEAR);
    kopf += ("<td  style=\"font-size: 11;\">Ausdruck am: " + dat + "</td>");
    kopf += ("<td  style=\"font-size: 11;\">Datum</td>");
    kopf += ("</tr>");
    kopf += ("</table>");
    kopf += ("<p>&nbsp;</p>");
    htmlString.append(kopf);
    document.open();

    Query qb = em.createNamedQuery("findVertretungbyDate");
    qb.setParameter("paramFromDate", parsedFrom);
    qb.setParameter("paramToDate", parsedTo);
    List<Vertretung> vl = qb.getResultList();
    Log.d("Result Liste = " + vl);

    for (Vertretung v : vl) {
        htmlString.append("<h3>Absenz von " + v.getAbsenzVon() + " am " + toReadableFromat(v.getAbsenzAm())
                + " eingereicht von " + v.getEingereichtVon() + " am " + toReadableFromat(v.getEingereichtAm())
                + "</h3>");
        htmlString.append("<h4>" + v.getKommentar() + "</h4>");
        htmlString.append("<p> </p>");
        htmlString.append("<table border='0.5' align='center' width='100%'>");
        htmlString.append("<tr>");
        htmlString.append(
                "<td width='10%' style=\"padding:4px;\">Stunde</td><td width='15%' style=\"padding:4px;\">Klasse</td><td width='15%' style=\"padding:4px;\">Aktion</td><td width='10%' style=\"padding:4px;\">Vertreter</td><td style=\"padding:4px;\">Kommentar</td>");
        htmlString.append("</tr>");
        JSONParser jsonParser = new JSONParser();
        try {
            JSONArray ja = (JSONArray) jsonParser.parse(v.getJsonString());

            for (int i = 0; i < ja.size(); i++) {
                JSONObject jo = (JSONObject) ja.get(i);
                htmlString.append("<tr>");
                htmlString.append(
                        "<td style=\"font-size: 11;padding:4px;\" width='10%'>" + jo.get("stunde") + "</td>");
                htmlString.append(
                        "<td style=\"font-size: 11;padding:4px;\" width='15%'>" + jo.get("Klasse") + "</td>");
                htmlString.append(
                        "<td style=\"font-size: 11;padding:4px;\" width='15%'>" + jo.get("Aktion") + "</td>");
                htmlString.append("<td style=\"font-size: 11;padding:4px;\" width='10%'>" + jo.get("Vertreter")
                        + "</td>");
                htmlString.append("<td style=\"font-size: 11;padding:4px;\">" + jo.get("Kommentar") + "</td>");
                htmlString.append("</tr>");
            }

        } catch (org.json.simple.parser.ParseException ex) {
            ex.printStackTrace();
            Logger.getLogger(DokuServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        htmlString.append("</table>");
        htmlString.append("<p></p>");
    }

    //document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));
    InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
    // Bild einfgen
    String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
    Image image = Image.getInstance(url);
    image.setAbsolutePosition(45f, 720f);
    image.scalePercent(50f);
    document.add(image);
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    return document;
}

From source file:phenoviewer.ReNameJFrame.java

private String replaceTokens(Date date, int counter, String path) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);

    Map<String, Object> tokens = new HashMap<String, Object>();
    tokens.put("ERA", getText(gc.get(Calendar.ERA), "BC", "AD"));
    tokens.put("YEAR", getString(gc.get(Calendar.YEAR), 4, "0"));
    tokens.put("MONTH", getString(gc.get(Calendar.MONTH) + 1, 2, "0"));
    tokens.put("WEEK_OF_YEAR", getString(gc.get(Calendar.WEEK_OF_YEAR), 2, "0"));
    tokens.put("WEEK_OF_MONTH", getString(gc.get(Calendar.WEEK_OF_MONTH), 0, ""));
    tokens.put("DATE", getString(gc.get(Calendar.DATE), 2, "0"));
    tokens.put("DAY_OF_MONTH", getString(gc.get(Calendar.DAY_OF_MONTH), 2, "0"));
    tokens.put("DAY_OF_YEAR", getString(gc.get(Calendar.DAY_OF_YEAR), 3, "0"));
    tokens.put("DAY_OF_WEEK", getString(gc.get(Calendar.DAY_OF_WEEK), 0, ""));
    tokens.put("DAY_OF_WEEK_IN_MONTH", getString(gc.get(Calendar.DAY_OF_WEEK_IN_MONTH), 0, ""));
    tokens.put("AM_PM", getText(gc.get(Calendar.AM_PM), "AM", "PM"));
    tokens.put("HOUR", getString(gc.get(Calendar.HOUR), 2, "0"));
    tokens.put("HOUR_OF_DAY", getString(gc.get(Calendar.HOUR_OF_DAY), 2, "0"));
    tokens.put("MINUTE", getString(gc.get(Calendar.MINUTE), 2, "0"));
    tokens.put("SECOND", getString(gc.get(Calendar.SECOND), 2, "0"));
    tokens.put("MILLISECOND", getString(gc.get(Calendar.MILLISECOND), 3, "0"));
    // tokens.put("ZONE_OFFSET", getString((gc.get(Calendar.ZONE_OFFSET)/(60*60*1000)), 0, ""));
    // tokens.put("DST_OFFSET", getString((gc.get(Calendar.DST_OFFSET)/(60*60*1000)), 0, ""));
    tokens.put("COUNTER", getString(counter, 0, ""));

    return processParams(path, tokens);
}

From source file:org.opendatakit.sync.aggregate.AggregateSynchronizer.java

/**
 * Simple Resource for all server interactions.
 * //from  w  w  w  . ja v  a 2 s.  c om
 * @param uri
 * @return
 * @throws InvalidAuthTokenException
 */
private Resource buildBasicResource(URI uri) throws InvalidAuthTokenException {

    Resource rsc = rt.resource(uri);

    // report our locale... (not currently used by server)
    rsc.acceptLanguage(Locale.getDefault());

    // set the access token...
    rsc.header(ApiConstants.ACCEPT_CONTENT_ENCODING_HEADER, ApiConstants.GZIP_CONTENT_ENCODING);
    rsc.header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION);
    rsc.header(HttpHeaders.USER_AGENT, "Sync " + Sync.getInstance().getVersionCodeString() + " (gzip)");
    GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    Date now = new Date();
    g.setTime(now);
    SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz", Locale.US);
    formatter.setCalendar(g);
    rsc.header(ApiConstants.DATE_HEADER, formatter.format(now));

    if (accessToken != null && baseUri != null) {
        if (uri.getHost().equals(baseUri.getHost()) && uri.getPort() == baseUri.getPort()) {
            rsc.header("Authorization", "Bearer " + accessToken);
        }
    }

    return rsc;
}

From source file:org.i4change.app.data.user.Usermanagement.java

public void sendMailsToPendingUser() {
    try {/* ww w . jav  a 2  s  .c o  m*/
        //List<Organisation> orgList = this.getPendingOrganisationsForSendingMail();
        List<Users> userList = this.userDaoImpl.getPendingUsersForSendingMail();

        Date now = new Date();

        Long default_lang_id = Long
                .valueOf(this.configurationmanagement.getConfKey(3, "default_lang_id").getConf_value())
                .longValue();

        LinkedList<LinkedHashMap<String, String>> sendedReminderOrgs = new LinkedList<LinkedHashMap<String, String>>();

        for (Iterator<Users> iter = userList.iterator(); iter.hasNext();) {
            Users user = iter.next();

            GregorianCalendar cal = new GregorianCalendar();

            if (user.getLastMailSend() == null) {
                cal.setTime(user.getStarttime());
            } else {
                cal.setTime(user.getLastMailSend());
            }
            long dt = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH), 0, 0).getTimeInMillis();

            Long timeDifferenceInMilliSeconds = now.getTime() - dt;

            log.debug("timeDifferenceInMilliSeconds: " + timeDifferenceInMilliSeconds);
            //daily send
            //if (timeDifferenceInMilliSeconds >= 86400000) {

            if (timeDifferenceInMilliSeconds >= 86400000) {

                log.debug("Found Org to send reminder" + user.getUser_id() + " Name: " + user.getLogin());
                System.out.println(
                        "Found Org to send reminder" + user.getUser_id() + " Name: " + user.getLogin());

                log.debug("Send Mail to Moderator: " + user.getUser_id() + " name: " + user.getLogin());

                Adresses_Emails mail = null;
                Iterator<Adresses_Emails> it = user.getAdresses().getEmails().iterator();
                if (it.hasNext()) {
                    mail = it.next();
                }

                String reminderUsers = user.getLogin() + " (" + user.getUser_id() + ") ("
                        + mail.getMail().getEmail() + ") (" + user.getReceivePendingReminder() + ")";

                LinkedHashMap<String, String> sendedReminderOrg = new LinkedHashMap<String, String>();
                sendedReminderOrg.put("orgName", user.getLogin());
                sendedReminderOrg.put("orgId", "");
                sendedReminderOrg.put("orgCreationDate",
                        CalendarPatterns.getDateWithTimeByMiliSeconds(user.getStarttime()));
                sendedReminderOrg.put("reminderUsers", reminderUsers);

                sendedReminderOrgs.add(sendedReminderOrg);

                String receipent = mail.getMail().getEmail();

                log.debug("Send Mail to: " + receipent);

                Long langId = user.getLanguage_id();
                if (langId == null) {
                    langId = default_lang_id;
                }

                if (user.getReceivePendingReminder() == null || user.getReceivePendingReminder()) {
                    this.mailmanagement.addMailToSpoolAboutPendingOrganization(user.getUser_id(), receipent,
                            user.getLogin(), user.getStarttime(), langId, user.getUserHash());
                }

            }

            //Update Org to do not send twice
            user.setLastMailSend(new Date());
            this.userDaoImpl.updateUser(user);

        }

        //send Report to Administrators:
        List<Users> admins = this.userDaoImpl.getAdmins();

        for (Users admin : admins) {

            log.debug("Send Mail to Administrator: " + admin.getUser_id() + " name: " + admin.getLogin());

            Adresses_Emails mail = null;
            Iterator<Adresses_Emails> it = admin.getAdresses().getEmails().iterator();
            if (it.hasNext()) {
                mail = it.next();
            }

            this.mailmanagement.addMailToSpoolAboutReportOfPendingOrganizations(admin.getUser_id(),
                    mail.getMail().getEmail(), sendedReminderOrgs, default_lang_id);

        }

    } catch (Exception ex2) {
        log.error("[sendMailsToPendingOrgs]", ex2);
    }
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_//from   w  w  w . j  a  v a  2  s . co  m
 *
 * @param date _more_
 *
 * @return _more_
 */
public static int getYear(Date date) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);

    return cal.get(cal.YEAR);
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_/*www.j av a 2  s .c om*/
 *
 * @param date _more_
 *
 * @return _more_
 */
public static int getMonth(Date date) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);

    return cal.get(cal.MONTH);
}

From source file:org.obm.icalendar.Ical4jHelper.java

private void addMonthlyOffsetToRecurDayList(Date eventStartDate, Recur recur) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(eventStartDate);
    recur.getDayList().add(WeekDay.getMonthlyOffset(cal));
}