Example usage for java.util Calendar roll

List of usage examples for java.util Calendar roll

Introduction

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

Prototype

public void roll(int field, int amount) 

Source Link

Document

Adds the specified (signed) amount to the specified calendar field without changing larger fields.

Usage

From source file:org.infoglue.calendar.actions.ViewEventSearchAction.java

public String doExternalBindingSearch() throws Exception {
    setExportResult(false);// w  w  w.j a v a 2s .co  m
    setSortAscending(false);
    setStateId(Event.STATE_PUBLISHED);
    initialize();

    List<Long> eventIds = getEventIds();
    if (startDateTime == null && eventIds != null) {
        currentExternalEvents = EventController.getController().getEventList(eventIds, getSession());
    }

    if (startDateTime != null) {
        execute();
        if (this.events != null) {
            log.info("Filtering event results. We only want one post even if there are more versions...");
            // Remove duplicates
            HashSet<Long> currentIds = new HashSet<Long>();
            @SuppressWarnings("unchecked")
            Iterator<Event> eventIterator = this.events.iterator();
            while (eventIterator.hasNext()) {
                Event event = (Event) eventIterator.next();
                if (!currentIds.add(event.getId())) // if the id already exists
                {
                    log.debug("Found duplicate event: " + event.getId());
                    eventIterator.remove();
                }
            }
        }
    } else {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        startDateTime = dateFormatter.format(calendar.getTime());
        calendar.roll(Calendar.WEEK_OF_YEAR, 1);
        endDateTime = dateFormatter.format(calendar.getTime());

        startTime = "00:00";
        endTime = "23:59";
    }
    return "successExternalBinding";
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

@RequestMapping(value = "/EajaxtestNoL", method = RequestMethod.GET)
public @ResponseBody String ajaxtestNoL(Principal principal) {
    String name = principal.getName();
    String result = "";
    try {/*from  w  ww.  ja v  a  2 s .com*/
        users u = usuarioService.getByLogin(name);

        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                /*System.out.println("DATE: "+message.getSentDate().toString());
                System.out.println("FROM: "+message.getFrom()[0].toString());            
                System.out.println("SUBJECT: "+message.getSubject().toString());
                System.out.println("CONTENT: "+message.getContent().toString());
                System.out.println("******************************************");
                */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>"
                        + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString()
                        + "</span>" +

                        message.getSubject().toString() + "</span>" +

                        "</span>" + "</a>" + "</li> ";
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("No Information");
            }
        }

    } catch (Exception ex) {
    }

    return result;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public correoNoLeidos ltaRecibidos2(String name, int num) {
    correoNoLeidos lta = new correoNoLeidos();
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {//from w  ww.j a  v a2 s .  c  om
        users u = usuarioService.getByLogin(name);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                if (num == message.getMessageNumber()) {
                    //message.setFlag(Flags.Flag.SEEN, true);
                    lta.setNum(message.getMessageNumber());
                    lta.setFecha(message.getSentDate().toString());
                    lta.setDe(message.getFrom()[0].toString());
                    lta.setAsunto(message.getSubject().toString());
                    correoNoLeidos co = new correoNoLeidos();
                    List<String> arc = new ArrayList<String>();
                    List<String> rar = new ArrayList<String>();
                    correoNoLeidos cc = analizaParteDeMensaje2(co, arc, rar, message);
                    lta.setImagenes(cc.getImagenes());
                    lta.setRar(cc.getRar());
                    lta.setContenido(cc.getContenido());
                    String cont = "";

                    String contenido = "";

                    //lta.setContenido(analizaParteDeMensaje2(message));
                }
            } catch (Exception e) {
                System.out.println("No Information");
            }

        }
    } catch (MessagingException e) {
        System.out.println(e.toString());
    }

    return lta;
}

From source file:de.iteratec.iteraplan.businesslogic.service.FastExportServiceImplTest.java

/**
 * Test method for {@link de.iteratec.iteraplan.businesslogic.service.FastExportServiceImpl#getEncompassingRuntimePeriod(java.util.List)}.
 *///from  ww  w. j  av a 2s.  c  o m
@Test
public void testGetEncompassingRuntimePeriodNoStartWithEnd() {
    InformationSystemRelease isr1 = mtdf.getInformationSystemReleaseTestData();
    InformationSystemRelease isr2 = mtdf.getInformationSystemReleaseTestData();

    Date now = new Date();
    Date latest = DateUtils.addMonths(now, HALF_YEAR_IN_MONTHS);
    Date someEnd1 = DateUtils.addMonths(now, QUARTER_YEAR_IN_MONTHS);

    RuntimePeriod period1 = new RuntimePeriod(null, latest);
    isr1.setRuntimePeriod(period1);
    RuntimePeriod period2 = new RuntimePeriod(null, someEnd1);
    isr2.setRuntimePeriod(period2);

    Calendar yearBeforeLatest = Calendar.getInstance();
    yearBeforeLatest.setTime(latest);
    yearBeforeLatest.roll(Calendar.YEAR, -1);

    List<BuildingBlock> bbList = new ArrayList<BuildingBlock>();
    bbList.add(isr2);
    bbList.add(isr1);

    RuntimePeriod res = fastExportServiceImpl.getEncompassingRuntimePeriod(bbList);
    RuntimePeriod exp = new RuntimePeriod(yearBeforeLatest.getTime(), latest);
    assertEquals(exp, res);
}

From source file:de.iteratec.iteraplan.businesslogic.service.FastExportServiceImplTest.java

/**
 * Test method for {@link de.iteratec.iteraplan.businesslogic.service.FastExportServiceImpl#getEncompassingRuntimePeriod(java.util.List)}.
 *//*from w  w w  . j a  v  a  2  s.c o  m*/
@Test
public void testGetEncompassingRuntimePeriodWithStartNoEnd() {
    InformationSystemRelease isr1 = mtdf.getInformationSystemReleaseTestData();
    InformationSystemRelease isr2 = mtdf.getInformationSystemReleaseTestData();

    Date now = new Date();
    Date earliest = DateUtils.addMonths(now, -HALF_YEAR_IN_MONTHS);
    Date someStart1 = DateUtils.addMonths(now, -QUARTER_YEAR_IN_MONTHS);

    RuntimePeriod period1 = new RuntimePeriod(someStart1, null);
    isr1.setRuntimePeriod(period1);
    RuntimePeriod period2 = new RuntimePeriod(earliest, null);
    isr2.setRuntimePeriod(period2);

    Calendar yearAfterEarliest = Calendar.getInstance();
    yearAfterEarliest.setTime(earliest);
    yearAfterEarliest.roll(Calendar.YEAR, 1);

    List<BuildingBlock> bbList = new ArrayList<BuildingBlock>();
    bbList.add(isr2);
    bbList.add(isr1);

    RuntimePeriod res = fastExportServiceImpl.getEncompassingRuntimePeriod(bbList);
    RuntimePeriod exp = new RuntimePeriod(earliest, yearAfterEarliest.getTime());
    assertEquals(exp, res);
}

From source file:com.intranet.intr.inbox.SupControllerInbox.java

@RequestMapping(value = "/ajaxtestNoL", method = RequestMethod.GET)
public @ResponseBody String ajaxtestNoL(Principal principal) {
    String name = principal.getName();
    String result = "";
    try {//from ww w .  j  av  a2 s.  com
        users u = usuarioService.getByLogin(name);

        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                /*System.out.println("DATE: "+message.getSentDate().toString());
                System.out.println("FROM: "+message.getFrom()[0].toString());            
                System.out.println("SUBJECT: "+message.getSubject().toString());
                System.out.println("CONTENT: "+message.getContent().toString());
                System.out.println("******************************************");
                */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>"
                        + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString()
                        + "</span>" +

                        message.getSubject().toString() + "</span>" +

                        "</span>" + "</a>" + "</li> ";
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("No Information");
            }
        }

    } catch (Exception ex) {
    }

    return result;
}

From source file:org.jasig.portal.rest.StatsLayoutModificationsController.java

@RequestMapping(value = "/userLayoutModificationsCounts")
public ModelAndView getEventCounts(HttpServletRequest req, HttpServletResponse res) throws ServletException {

    // Days parameter
    int days = 30; // default
    if (req.getParameter("days") != null) {
        String daysParam = req.getParameter("days").trim();
        try {/*w w  w .  j a va 2s. co  m*/
            days = Integer.parseInt(daysParam);
        } catch (NumberFormatException nfe) {
            String msg = "Unrecognizable days parameter (must be a valid integer): " + daysParam;
            log.warn(msg, nfe);
            throw new ServletException(msg, nfe);
        }
    }

    // fromDate parameter
    Calendar dateOnOrBefore = Calendar.getInstance();
    dateOnOrBefore.set(Calendar.HOUR_OF_DAY, 0);
    dateOnOrBefore.set(Calendar.MINUTE, 0);
    dateOnOrBefore.set(Calendar.SECOND, 0);
    dateOnOrBefore.set(Calendar.MILLISECOND, 0);
    dateOnOrBefore.roll(Calendar.DATE, true); // default is tomorrow with time fields cleared
    if (req.getParameter("fromDate") != null) {
        String fromDateParam = req.getParameter("fromDate").trim();
        // If the user doesn't enter a date, the UI sends "today" (or other 
        // string), so ignore anything that's not even close...
        if (datePattern.matcher(fromDateParam).matches()) {
            try {
                Date fromDate = format.parse(fromDateParam);
                // Need to add one day, since the report is inclusive
                Calendar cal = Calendar.getInstance();
                cal.setTime(fromDate);
                cal.add(Calendar.DATE, 1);
                dateOnOrBefore = cal;
            } catch (ParseException pe) {
                // Passing a bad date is ok, it just results in the default
                if (log.isInfoEnabled()) {
                    String msg = "Unrecognizable fromDate parameter (format 'mm/dd/yyyy'): " + fromDateParam;
                    log.info(msg, pe);
                }
            }
        }
    }

    // Be certain days is within prescribed limits
    if (days < MIN_DAYS) {
        days = MIN_DAYS;
    } else if (days > maxDays) {
        days = maxDays;
    }

    List<CountingTuple> completeList = factory.getEventCounts(dateOnOrBefore.getTime(), days);

    IPerson user = personManager.getPerson(req);
    List<CountingTuple> filteredList = filterByPermissions(user, completeList);

    return new ModelAndView("jsonView", "counts", filteredList);

}

From source file:org.jasig.portlet.calendar.adapter.OracleICalAdapter.java

/**
 * Retrieve calendar data from Oracle and use it to
 * build an iCal4j Calendar object./*from   ww  w. ja  va2 s.  c  o m*/
 * 
 * @param url URL of the calendar to be retrieved
 * @param username Username to use to login to Oracle Calendar using Oracle's BasicAuth
 * @param password Password to use to login to Oracle Calendar using Oracle's BasicAuth
 * @return ical4j Calendar object
 */
protected net.fortuna.ical4j.model.Calendar getCalendar(String url, String username, String password,
        Period period) throws CalendarException {
    // initialize the authentication information and set the user id
    BasicAuth auth = new BasicAuth();

    auth.setName(username);
    auth.setPassword(password);

    // initialize the event search command and query
    SearchCommand search = new SearchCommand();
    search.setCmdId("uPortal");

    // create a query to retrieve unconfirmed events
    vQuery query = new vQuery();
    query.setFrom(vQuery.k_queryFromEvent);
    // query.setFrom(vQuery.k_queryFromTodo);

    //java.util.Calendar today = CalendarUtils.getToday(); 
    //java.util.Calendar begin = (java.util.Calendar) today.clone(); 

    Calendar beginPeriod = Calendar.getInstance();
    beginPeriod.setTime(period.getStart());
    beginPeriod.set(Calendar.HOUR_OF_DAY, 0);
    beginPeriod.set(Calendar.MINUTE, 0);
    beginPeriod.set(Calendar.SECOND, 0);
    beginPeriod.set(Calendar.MILLISECOND, 0);

    Calendar endPeriod = Calendar.getInstance();
    endPeriod.setTime(period.getEnd());
    endPeriod.set(Calendar.HOUR_OF_DAY, 0);
    endPeriod.set(Calendar.MINUTE, 0);
    endPeriod.set(Calendar.SECOND, 0);
    endPeriod.set(Calendar.MILLISECOND, 0);

    query.setWhere(CalendarUtils.getDateRangeQuery(beginPeriod, endPeriod));

    search.setQuery(query);

    // create the calendar client SOAP stub
    // and set the basic authentication header
    Calendarlet cws = new Calendarlet();

    // set the Web Services host URL
    cws.setEndPointURL(url);
    cws.setAuthenticationHeader(auth.getElement());
    cws.setWantIOBuffers(log.isDebugEnabled());
    cws.setWantIOBuffers(true);

    // make the SOAP call
    try {
        CalendaringResponse response = cws.Search(search.getElement());

        if (log.isDebugEnabled()) {
            log.debug(response.getSendBuffer());
            log.debug("\n-----------------------------");
            log.debug(response.getReceiveBuffer());
        }

        // get the SOAP reply
        Reply reply = (Reply) response.getCalendarReply();
        if (reply == null) {
            throw new CalendarException("Response could not be parsed");
        }

        net.fortuna.ical4j.model.Calendar iCal4j = new net.fortuna.ical4j.model.Calendar();
        iCal4j.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
        iCal4j.getProperties().add(Version.VERSION_2_0);
        iCal4j.getProperties().add(CalScale.GREGORIAN);

        // traverse all the iCalendar objects
        Vector entries = reply.getEntries();
        Vector someiCalendars = iCalendar.unmarshallVector(entries);
        int numiCalendars = someiCalendars.size();
        log.debug(numiCalendars + " iCalendar entries found.");
        for (int i = 0; i < numiCalendars; i++) {
            iCalendar iCalObj = (iCalendar) someiCalendars.get(i);
            Vector somevCalendars = iCalObj.getvCalendars();
            int numvCalendars = somevCalendars.size();
            log.debug(numvCalendars + " vCalendar entries found.");
            for (int ii = 0; ii < numvCalendars; ii++) {
                vCalendar vCalObj = (vCalendar) somevCalendars.get(ii);
                Vector somevEvents = vCalObj.getComponents();
                int numvEvents = somevEvents.size();
                log.debug(numvEvents + " vEvents entries found.");

                for (int iii = 0; iii < numvEvents; iii++) {
                    try {
                        vEvent vEventObj = (vEvent) somevEvents.get(iii);
                        log.debug("vEvents is " + vEventObj.getSummary());
                        log.debug("vEvents DT start " + vEventObj.getDtStart());
                        log.debug("vEvents DT end " + vEventObj.getDtEnd());

                        if (vEventObj.getXEventType().equals(vEvent.k_eventTypeDayEvent)) {
                            DateFormat parser = new SimpleDateFormat("yyyyMMdd");
                            Calendar endEvent = Calendar.getInstance();
                            endEvent.setTime(parser.parse(vEventObj.getDtStart()));
                            endEvent.roll(Calendar.DATE, true);

                            VEvent iCal4jEvent = new VEvent(new Date(vEventObj.getDtStart()),
                                    new Date(endEvent.getTime()), vEventObj.getSummary());
                            iCal4jEvent.getProperties().add(new Location(vEventObj.getLocation()));
                            iCal4j.getComponents().add(iCal4jEvent);
                        } else {
                            VEvent iCal4jEvent = new VEvent(new DateTime(vEventObj.getDtStart()),
                                    new DateTime(vEventObj.getDtEnd()), vEventObj.getSummary());
                            iCal4jEvent.getProperties().add(new Location(vEventObj.getLocation()));
                            iCal4j.getComponents().add(iCal4jEvent);
                        }
                    } catch (ParseException parseException) {
                        log.error("Problem parsing DateTime");
                    }
                }
            }
        }
        return iCal4j;
    } catch (Exception ex) {
        log.error("SOAP call failed", ex);
        throw new CalendarException("SOAP call failed");
    }
}

From source file:org.polymap.kaps.exporter.VertragStaBuExporter.java

private void write(FeatureCollection features, OutputStream out, IProgressMonitor monitor) throws IOException {

    final KapsRepository repo = KapsRepository.instance();

    FeatureIterator it = null;/*from  w  w w  . j a v  a2s  .co m*/

    StreamResult result = new StreamResult(out);

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElementNS("http://www.destatis.de/schema/datml-raw/2.0/de",
                "DatML-RAW-D");
        rootElement.setAttribute("version", "2.0");
        doc.appendChild(rootElement);

        // optionen elements
        Element optionen = doc.createElement("optionen");
        rootElement.appendChild(optionen);

        rootElement.appendChild(createProtokoll(doc));

        rootElement.appendChild(createAbsender(doc));

        rootElement.appendChild(createEmpfaenger(doc));

        Element nachricht = doc.createElement("nachricht");
        rootElement.appendChild(nachricht);

        it = features.features();
        Calendar cal = new GregorianCalendar();
        // quartal zurckrollen
        cal.roll(Calendar.MONTH, -3);
        if (it.hasNext()) {
            VertragComposite vertrag = repo.findEntity(VertragComposite.class,
                    it.next().getIdentifier().getID());
            cal.setTime(vertrag.vertragsDatum().get());
        }
        Element datenSegment = createDatenSegment(nachricht, cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH) / 3);

        // reload the iterator
        it = features.features();
        int count = 0;
        while (it.hasNext()) {
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            if ((++count % 100) == 0) {
                monitor.subTask("Objekte: " + count++);
                monitor.worked(100);
            }
            Feature feature = it.next();

            VertragComposite vertrag = repo.findEntity(VertragComposite.class, feature.getIdentifier().getID());
            // all properties
            createSegment(datenSegment, vertrag);

        }

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        if (it != null) {
            it.close();
        }
    }
}

From source file:lineage2.gameserver.network.telnet.commands.TelnetServer.java

/**
 * Constructor for TelnetServer.//from ww  w.j  ava  2  s.c om
 */
public TelnetServer() {
    _commands.add(new TelnetCommand("version", "ver") {
        @Override
        public String getUsage() {
            return "version";
        }

        @Override
        public String handle(String[] args) {
            return "Rev." + GameServer.getInstance().getVersion().getRevisionNumber() + " Builded : "
                    + GameServer.getInstance().getVersion().getBuildDate() + "\n";
        }
    });
    _commands.add(new TelnetCommand("uptime") {
        @Override
        public String getUsage() {
            return "uptime";
        }

        @Override
        public String handle(String[] args) {
            return DurationFormatUtils.formatDurationHMS(ManagementFactory.getRuntimeMXBean().getUptime())
                    + "\n";
        }
    });
    _commands.add(new TelnetCommand("restart") {
        @Override
        public String getUsage() {
            return "restart <seconds>|now>";
        }

        @Override
        public String handle(String[] args) {
            if (args.length == 0) {
                return null;
            }
            StringBuilder sb = new StringBuilder();
            if (NumberUtils.isNumber(args[0])) {
                int val = NumberUtils.toInt(args[0]);
                Shutdown.getInstance().schedule(val, Shutdown.RESTART);
                sb.append("Server will restart in ").append(Shutdown.getInstance().getSeconds())
                        .append(" seconds!\n");
                sb.append("Type \"abort\" to abort restart!\n");
            } else if (args[0].equalsIgnoreCase("now")) {
                sb.append("Server will restart now!\n");
                Shutdown.getInstance().schedule(0, Shutdown.RESTART);
            } else {
                String[] hhmm = args[0].split(":");
                Calendar date = Calendar.getInstance();
                Calendar now = Calendar.getInstance();
                date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hhmm[0]));
                date.set(Calendar.MINUTE, hhmm.length > 1 ? Integer.parseInt(hhmm[1]) : 0);
                date.set(Calendar.SECOND, 0);
                date.set(Calendar.MILLISECOND, 0);
                if (date.before(now)) {
                    date.roll(Calendar.DAY_OF_MONTH, true);
                }
                int seconds = (int) ((date.getTimeInMillis() / 1000L) - (now.getTimeInMillis() / 1000L));
                Shutdown.getInstance().schedule(seconds, Shutdown.RESTART);
                sb.append("Server will restart in ").append(Shutdown.getInstance().getSeconds())
                        .append(" seconds!\n");
                sb.append("Type \"abort\" to abort restart!\n");
            }
            return sb.toString();
        }
    });
    _commands.add(new TelnetCommand("shutdown") {
        @Override
        public String getUsage() {
            return "shutdown <seconds>|now|<hh:mm>";
        }

        @Override
        public String handle(String[] args) {
            if (args.length == 0) {
                return null;
            }
            StringBuilder sb = new StringBuilder();
            if (NumberUtils.isNumber(args[0])) {
                int val = NumberUtils.toInt(args[0]);
                Shutdown.getInstance().schedule(val, Shutdown.SHUTDOWN);
                sb.append("Server will shutdown in ").append(Shutdown.getInstance().getSeconds())
                        .append(" seconds!\n");
                sb.append("Type \"abort\" to abort shutdown!\n");
            } else if (args[0].equalsIgnoreCase("now")) {
                sb.append("Server will shutdown now!\n");
                Shutdown.getInstance().schedule(0, Shutdown.SHUTDOWN);
            } else {
                String[] hhmm = args[0].split(":");
                Calendar date = Calendar.getInstance();
                Calendar now = Calendar.getInstance();
                date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hhmm[0]));
                date.set(Calendar.MINUTE, hhmm.length > 1 ? Integer.parseInt(hhmm[1]) : 0);
                date.set(Calendar.SECOND, 0);
                date.set(Calendar.MILLISECOND, 0);
                if (date.before(now)) {
                    date.roll(Calendar.DAY_OF_MONTH, true);
                }
                int seconds = (int) ((date.getTimeInMillis() / 1000L) - (now.getTimeInMillis() / 1000L));
                Shutdown.getInstance().schedule(seconds, Shutdown.SHUTDOWN);
                sb.append("Server will shutdown in ").append(Shutdown.getInstance().getSeconds())
                        .append(" seconds!\n");
                sb.append("Type \"abort\" to abort shutdown!\n");
            }
            return sb.toString();
        }
    });
    _commands.add(new TelnetCommand("abort") {
        @Override
        public String getUsage() {
            return "abort";
        }

        @Override
        public String handle(String[] args) {
            Shutdown.getInstance().cancel();
            return "Aborted.\n";
        }
    });
}