Example usage for java.util GregorianCalendar GregorianCalendar

List of usage examples for java.util GregorianCalendar GregorianCalendar

Introduction

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

Prototype

public GregorianCalendar() 

Source Link

Document

Constructs a default GregorianCalendar using the current time in the default time zone with the default Locale.Category#FORMAT FORMAT locale.

Usage

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method./* w ww. java 2 s  .c  o  m*/
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}

From source file:com.owly.srv.RemoteBasicStat.java

/**
 * Constructor for RemoteBasicStat//w  w w  .j a v  a  2 s .  com
 */
public RemoteBasicStat() {
    Logger log = Logger.getLogger(RemoteBasicStat.class);

    log.debug("Calling RemoteBasicStat constructor");

    GregorianCalendar currentDate = new GregorianCalendar();
    statServerDate = currentDate.getTime();

    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    log.debug("Actual date is " + dateFormat.format(statServerDate));
}

From source file:no.dusken.aranea.admin.editor.CalendarEditor.java

@Override
public void setAsText(String string) throws IllegalArgumentException {

    DateFormat formatter = new SimpleDateFormat(format, new Locale("no"));
    Date date;/*from ww w.  jav a  2  s . c  o  m*/
    try {
        date = formatter.parse(string);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Not in right format: " + format);
    }

    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    setValue(cal);
}

From source file:TimeUtil.java

public static String windowFormat(long msecs) {
    Date tDate = new Date(msecs);
    long now = System.currentTimeMillis();
    long diff = now - msecs;
    // start with the last 24 hours
    long comp = MS_PER_DAY;
    // start comparing
    if (diff < comp) {
        // it's within the last 24 hours - just return the time
        DateFormat formatter = DateFormat.getTimeInstance(DateFormat.SHORT);
        return formatter.format(tDate);
    }/*  w w  w  . ja  v a 2  s  . c  o m*/
    // now expand to another day
    comp += MS_PER_DAY;
    if (diff < comp) {
        // it's within the last 48 hours - just return the time
        DateFormat formatter = DateFormat.getTimeInstance(DateFormat.SHORT);
        return "Yesterday " + formatter.format(tDate);
    }
    // now up it to a week
    comp += 5 * MS_PER_DAY;
    if (diff < comp) {
        // return the day of the week and the time
        // get time to be formatted into a calendar
        GregorianCalendar tCal = new GregorianCalendar();
        tCal.setTime(tDate);
        SimpleDateFormat formatter = new SimpleDateFormat("EEEE");
        return formatter.format(tDate);
    }
    // just return full date
    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
    return formatter.format(tDate);
}

From source file:com.himanshu.um.impl.user.db.dao.UserDaoTest.java

@Test
public void createUser() throws UserCreationException, DatatypeConfigurationException, InterruptedException {
    ApplicationContext context = new ClassPathXmlApplicationContext("um-spring.xml");

    IManager manager = context.getBean(DatabaseManagerImpl.class);
    com.himanshu.um.api.model.User user = new com.himanshu.um.api.model.User();
    user.setUsername("himanshu");
    user.setPassword("password");
    user.setStatus(true);// w  ww.j  a  v a 2 s .c  o m
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTimeInMillis(new Date().getTime());
    try {
        user.setCreatedDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
        throw e;
    }

    Thread.sleep(3000); //3 seconds sleep to demonstrate last modified date lag

    cal.setTimeInMillis(new Date().getTime());
    try {
        user.setLastModifiedDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
        throw e;
    }

    manager.addNewUser(user);
}

From source file:TimePeriod.java

/**
 * Ohne einen Parameter wird von und bis auf jetzt gesetzt
 *///from  ww w . ja  v a2 s.c o  m
public TimePeriod() {
    from = new GregorianCalendar();
    to = new GregorianCalendar();
}

From source file:com.taurus.compratae.test.ArchivoDbServiceTestCase.java

public void testBuscarTodo() {
    log.debug("Inicio testRecarga");
    setup();/* w  w  w  .j ava 2  s  .  co m*/
    Date fecha1 = new Date();
    SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd");
    String fecha = formatoDelTexto.format(fecha1);

    Date fechaEnviar = null;
    try {
        fechaEnviar = formatoDelTexto.parse(fecha);
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(fechaEnviar.getTime());
    cal.add(Calendar.MINUTE, 1439);
    Date fecha2 = new java.sql.Date(cal.getTimeInMillis());
    Archivo archivo = archivoDbService.buscarEntreFechas(fechaEnviar, fecha2);
    log.debug("Fin testRecarga");
}

From source file:com.fatminds.vaadin.cmis.property.CalendarPropertyConverter.java

@Override
public GregorianCalendar parse(Date value) throws ConversionException {
    if (value == null) {
        return null;
    }//from  www . ja v a2  s .c  o  m
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(value);
    return cal;
}

From source file:ma.glasnost.orika.test.converter.CloneableConverterTestCase.java

@Test
public void cloneableConverter() throws DatatypeConfigurationException {

    CloneableConverter cc = new CloneableConverter(SampleCloneable.class);

    MapperFactory factory = MappingUtil.getMapperFactory();
    factory.getConverterFactory().registerConverter(cc);

    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.YEAR, 10);/*  w  w  w.  j a v a  2 s.  c o m*/
    XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar((GregorianCalendar) cal);
    cal.add(Calendar.MONTH, 3);

    ClonableHolder source = new ClonableHolder();
    source.value = new SampleCloneable();
    source.value.id = 5L;
    source.date = new Date(System.currentTimeMillis() + 100000);
    source.timestamp = new Timestamp(System.currentTimeMillis() + 50000);
    source.calendar = cal;
    source.xmlCalendar = xmlCal;

    ClonableHolder dest = factory.getMapperFacade().map(source, ClonableHolder.class);
    Assert.assertEquals(source.value, dest.value);
    Assert.assertNotSame(source.value, dest.value);
    Assert.assertEquals(source.date, dest.date);
    Assert.assertNotSame(source.date, dest.date);
    Assert.assertEquals(source.timestamp, dest.timestamp);
    Assert.assertNotSame(source.timestamp, dest.timestamp);
    Assert.assertEquals(source.calendar, dest.calendar);
    Assert.assertNotSame(source.calendar, dest.calendar);
    Assert.assertEquals(source.xmlCalendar, dest.xmlCalendar);
    Assert.assertNotSame(source.xmlCalendar, dest.xmlCalendar);
}

From source file:model.listini.Period.java

public Integer getStartYear() {
    Calendar calendar = new GregorianCalendar();

    calendar.setTime(this.getStartDate());
    return calendar.get(Calendar.YEAR);
}