Example usage for java.util Calendar getTimeInMillis

List of usage examples for java.util Calendar getTimeInMillis

Introduction

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

Prototype

public long getTimeInMillis() 

Source Link

Document

Returns this Calendar's time value in milliseconds.

Usage

From source file:com.flexive.core.security.FxDBAuthentication.java

/**
 * Login a user using flexive's database
 *
 * @param loginname name of the user/*w w w .  j  av  a 2  s .  c  om*/
 * @param password plaintext password
 * @param callback callback providing datasource, ejb context and "take over"
 * @return Authenticated UserTicket
 * @throws FxAccountInUseException   on errors
 * @throws FxLoginFailedException    on errors
 * @throws FxAccountExpiredException on errors
 */
public static UserTicket login(String loginname, String password, FxCallback callback)
        throws FxAccountInUseException, FxLoginFailedException, FxAccountExpiredException {
    final long SYS_UP = CacheAdmin.getInstance().getSystemStartTime();
    FxContext inf = FxContext.get();

    // Avoid null pointer exceptions
    if (password == null)
        password = "";
    if (loginname == null)
        loginname = "";

    final String applicationId = StringUtils.defaultString(inf.getApplicationId());
    if (StringUtils.isBlank(applicationId)) {
        LOG.warn("Login: application ID is not set");
    }

    String curSql;
    PreparedStatement ps = null;
    Connection con = null;
    try {
        // Obtain a database connection
        con = callback.getDataSource().getConnection();
        //               1-6 7      8           9              10                 11           12       13      14         15       16
        curSql = "SELECT d.*,a.ID,a.IS_ACTIVE,a.IS_VALIDATED,a.ALLOW_MULTILOGIN,a.VALID_FROM,a.VALID_TO,NOW(),a.PASSWORD,a.MANDATOR,a.LOGIN_NAME "
                + "FROM " + TBL_ACCOUNTS + " a " + "LEFT JOIN "
                + " (SELECT ID,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC FROM "
                + TBL_ACCOUNT_DETAILS
                + " WHERE APPLICATION=? ORDER BY LAST_LOGIN DESC) d ON a.ID=d.ID WHERE UPPER(a.LOGIN_NAME)=UPPER(?)";
        ps = con.prepareStatement(curSql);
        ps.setString(1, applicationId);
        ps.setString(2, loginname);
        final ResultSet rs = ps.executeQuery();

        // Anything found?
        if (rs == null || !rs.next())
            throw new FxLoginFailedException("Login failed (invalid user or password)",
                    FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED);

        // check if the hashed password matches the hash stored in the database
        final long id = rs.getLong(7);
        final String dbLoginName = rs.getString(16); // use DB login name for non-lowercase login names
        final String dbPassword = rs.getString(14);
        boolean passwordMatches = FxSharedUtils.hashPassword(id, dbLoginName, password).equals(dbPassword);
        if (!passwordMatches && "supervisor".equalsIgnoreCase(loginname)) {
            // before 3.2.0 the default supervisor password was incorrectly hashed against the lower-cased login name
            passwordMatches = FxSharedUtils.hashPassword(id, "supervisor", password).equals(dbPassword);
        }
        if (!passwordMatches && !callback.isCalledAsGlobalSupervisor()) {
            increaseFailedLoginAttempts(con, id);
            throw new FxLoginFailedException("Login failed (invalid user or password)",
                    FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED);
        }

        // Read data
        final boolean loggedIn = rs.getBoolean(2);
        final Date lastLogin = new Date(rs.getLong(3));
        final String lastLoginFrom = rs.getString(4);
        final long failedAttempts = rs.getLong(5);
        final boolean active = rs.getBoolean(8);
        final boolean validated = rs.getBoolean(9);
        final boolean allowMultiLogin = rs.getBoolean(10);
        final Date validFrom = new Date(rs.getLong(11));
        final Date validTo = new Date(rs.getLong(12));
        final Date dbNow = rs.getTimestamp(13);
        final long mandator = rs.getLong(15);

        // Account active?
        if (!active || !validated || (CacheAdmin.isEnvironmentLoaded()
                && !CacheAdmin.getEnvironment().getMandator(mandator).isActive())) {
            if (LOG.isDebugEnabled())
                LOG.debug("Login for user [" + loginname + "] failed, account is inactive. Active=" + active
                        + ", Validated=" + validated + ", Mandator active: "
                        + CacheAdmin.getEnvironment().getMandator(mandator).isActive());
            increaseFailedLoginAttempts(con, id);
            throw new FxLoginFailedException("Login failed, account is inactive.",
                    FxLoginFailedException.TYPE_INACTIVE_ACCOUNT);
        }

        // Account date from-to valid?
        //Compute the day AFTER the dValidTo
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(validTo);
        endDate.add(Calendar.DAY_OF_MONTH, 1);
        if (validFrom.getTime() > dbNow.getTime() || endDate.getTimeInMillis() < dbNow.getTime()) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            if (LOG.isDebugEnabled())
                LOG.debug("Login for user [" + loginname + "] failed, from/to date not valid. from='"
                        + sdf.format(validFrom) + "' to='" + validTo + "'");
            increaseFailedLoginAttempts(con, id);
            throw new FxAccountExpiredException(loginname, dbNow);
        }

        // Check 'Account in use and takeOver false'
        if (!allowMultiLogin && !callback.getTakeOverSession() && loggedIn && lastLogin != null) {
            // Only if the last login time was AFTER the system started
            if (lastLogin.getTime() >= SYS_UP) {
                FxAccountInUseException aiu = new FxAccountInUseException(loginname, lastLoginFrom, lastLogin);
                if (LOG.isInfoEnabled())
                    LOG.info(aiu);
                // don't log this as an invalid login attempt - this happens routinely when a session times
                // out and the cached session data has not been evicted by the maintenance task yet

                //increaseFailedLoginAttempts(con, id);
                throw aiu;
            }
        }

        // Clear any old data
        curSql = "DELETE FROM " + TBL_ACCOUNT_DETAILS + " WHERE ID=? AND APPLICATION=?";
        ps.close();
        ps = con.prepareStatement(curSql);
        ps.setLong(1, id);
        ps.setString(2, applicationId);
        ps.executeUpdate();

        // Mark user as active in the database
        // This can lead to duplicate rows for a user/application for concurrent logins (e.g. WebDAV clients),
        // but we prefer this to actually locking the complete table before updates. (FX-868)
        curSql = "INSERT INTO " + TBL_ACCOUNT_DETAILS
                + " (ID,APPLICATION,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC) "
                + "VALUES (?,?,?,?,?,?,?)";
        ps.close();
        ps = con.prepareStatement(curSql);
        ps.setLong(1, id);
        ps.setString(2, applicationId);
        ps.setBoolean(3, true);
        ps.setLong(4, System.currentTimeMillis());
        ps.setString(5, inf.getRemoteHost());
        ps.setLong(6, 0); //reset failed attempts
        ps.setString(7, AuthenticationSource.Database.name());
        ps.executeUpdate();

        // Load the user and construct a user ticket
        try {
            final UserTicketImpl ticket = (UserTicketImpl) UserTicketStore.getUserTicket(loginname);
            ticket.setFailedLoginAttempts(failedAttempts);
            ticket.setAuthenticationSource(AuthenticationSource.Database);
            return ticket;
        } catch (FxApplicationException e) {
            if (callback.getSessionContext() != null)
                callback.getSessionContext().setRollbackOnly();
            throw new FxLoginFailedException(
                    e.getExceptionMessage().getLocalizedMessage(
                            CacheAdmin.getEnvironment().getLanguage(FxLanguage.DEFAULT_ID)),
                    FxLoginFailedException.TYPE_UNKNOWN_ERROR);
        }
    } catch (SQLException exc) {
        if (callback.getSessionContext() != null)
            callback.getSessionContext().setRollbackOnly();
        throw new FxLoginFailedException("Database error: " + exc.getMessage(),
                FxLoginFailedException.TYPE_SQL_ERROR);
    } finally {
        Database.closeObjects(FxDBAuthentication.class, con, ps);
    }
}

From source file:Main.java

public static long getPeriodEnd(int periodType, long date) {
    final Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(getPeriodStart(periodType, date));

    switch (periodType) {
    case TYPE_DAY: {
        cal.add(Calendar.DAY_OF_YEAR, 1);
        break;/*from  w  w w. j a  v  a2 s.  com*/
    }

    case TYPE_WEEK: {
        cal.add(Calendar.WEEK_OF_YEAR, 1);
        break;
    }

    case TYPE_MONTH: {
        cal.add(Calendar.MONTH, 1);
        break;
    }

    case TYPE_YEAR: {
        cal.add(Calendar.YEAR, 1);
        break;
    }
    }

    cal.add(Calendar.MILLISECOND, -1);
    return cal.getTimeInMillis();
}

From source file:ips1ap101.lib.base.util.TimeUtils.java

public static Date newDate(java.util.Date date) {
    if (date == null) {
        return null;
    } else {//from   w w  w.  j  a va2  s  .co m
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(date.getTime());
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return new Date(c.getTimeInMillis());
    }
}

From source file:com.mozilla.socorro.hadoop.CrashReportJob.java

/**
 * @param args//from w w w.  j ava  2 s .  co  m
 * @return
 * @throws IOException
 * @throws ParseException
 */
public static Job initJob(String jobName, Configuration conf, Class<?> mainClass,
        Class<? extends TableMapper> mapperClass, Class<? extends Reducer> combinerClass,
        Class<? extends Reducer> reducerClass, Map<byte[], byte[]> columns,
        Class<? extends WritableComparable> keyOut, Class<? extends Writable> valueOut, Path outputPath)
        throws IOException, ParseException {
    // Set both start/end time and start/stop row
    Calendar startCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    String startDateStr = conf.get(START_DATE);
    String endDateStr = conf.get(END_DATE);
    if (!StringUtils.isBlank(startDateStr)) {
        startCal.setTime(sdf.parse(startDateStr));
    }
    if (!StringUtils.isBlank(endDateStr)) {
        endCal.setTime(sdf.parse(endDateStr));
    }

    conf.setLong(START_TIME, startCal.getTimeInMillis());
    conf.setLong(END_TIME, DateUtil.getEndTimeAtResolution(endCal.getTimeInMillis(), Calendar.DATE));

    Job job = new Job(conf);
    job.setJobName(jobName);
    job.setJarByClass(mainClass);

    // input table configuration
    Scan[] scans = MultiScanTableMapReduceUtil.generateScans(startCal, endCal, columns, 100, false);
    MultiScanTableMapReduceUtil.initMultiScanTableMapperJob(TABLE_NAME_CRASH_REPORTS, scans, mapperClass,
            keyOut, valueOut, job);

    if (combinerClass != null) {
        job.setCombinerClass(combinerClass);
    }

    if (reducerClass != null) {
        job.setReducerClass(reducerClass);
    } else {
        job.setNumReduceTasks(0);
    }

    FileOutputFormat.setOutputPath(job, outputPath);

    return job;
}

From source file:com.esri.cordova.geolocation.utils.JSONHelper.java

/**
 * Converts GpsStatus into JSON./*from  w ww . j a va 2  s  . com*/
 * @param gpsStatus Send a GpsStatus whenever the GPS fires
 * @return JSON representation of the satellite data
 */
public static String satelliteDataJSON(GpsStatus gpsStatus) {

    final Calendar calendar = Calendar.getInstance();
    final JSONObject json = new JSONObject();

    try {
        json.put("provider", SATELLITE_PROVIDER);
        json.put("timestamp", calendar.getTimeInMillis());

        if (gpsStatus.getSatellites() != null) {
            int count = 0;
            final int timeToFirstFix = gpsStatus.getTimeToFirstFix();

            for (GpsSatellite sat : gpsStatus.getSatellites()) {
                final JSONObject satelliteInfo = new JSONObject();

                satelliteInfo.put("PRN", sat.getPrn());
                satelliteInfo.put("timeToFirstFix", timeToFirstFix);
                satelliteInfo.put("usedInFix", sat.usedInFix());
                satelliteInfo.put("azimuth", sat.getAzimuth());
                satelliteInfo.put("elevation", sat.getElevation());
                satelliteInfo.put("hasEphemeris", sat.hasEphemeris());
                satelliteInfo.put("hasAlmanac", sat.hasAlmanac());
                satelliteInfo.put("SNR", sat.getSnr());

                json.put(Integer.toString(count), satelliteInfo);

                count++;
            }
        }
    } catch (JSONException exc) {
        logJSONException(exc);
    }

    return json.toString();
}

From source file:helper.util.DateHelper.java

/**
 * @return the days between two calendars, including dealing with year boundary
 **//*from  www .  ja  v  a 2s.  c  o  m*/
public static int calculateIntervalInDays(CalendarRange range) {
    Calendar start = range.getStart();
    Calendar end = range.getEnd();
    int startYear = start.get(Calendar.YEAR);
    int endYear = end.get(Calendar.YEAR);
    if (startYear == endYear) {
        if (start.get(Calendar.DAY_OF_YEAR) == end.get(Calendar.DAY_OF_YEAR)) {
            return 0;
        }
        return end.get(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);
    } else if (start.getTimeInMillis() < end.getTimeInMillis()) {
        // let the calendar do the thinking, just increment date until we hit our end date
        Calendar startCopy = (Calendar) start.clone();
        int days = 0;
        while (true) {
            startCopy.add(Calendar.DATE, 1);
            days++;
            if (startCopy.get(Calendar.DAY_OF_YEAR) == end.get(Calendar.DAY_OF_YEAR)) {
                return days;
            }
        }
    } else {
        // let the calendar do the thinking, just increment date until we hit our end date
        Calendar startCopy = (Calendar) start.clone();
        int days = 0;
        while (true) {
            startCopy.add(Calendar.DATE, -1);
            days--;
            if (startCopy.get(Calendar.DAY_OF_YEAR) == end.get(Calendar.DAY_OF_YEAR)) {
                return days;
            }
        }
    }
}

From source file:dsd.dao.WorstCaseDAO.java

public static ArrayList<WorstPylonCase> GetAllForPeriod(Calendar startDate, Calendar endDate, boolean traffic,
        boolean debris) {
    try {//  www  .  ja  v  a  2  s .  c  o  m
        Connection con = DAOProvider.getDataSource().getConnection();
        ArrayList<WorstPylonCase> worstCaseDataList = new ArrayList<WorstPylonCase>();
        try {
            String tableName = GetTableNameForDataType(traffic, debris);
            Object[] parameters = new Object[2];
            parameters[0] = new Timestamp(startDate.getTimeInMillis());
            parameters[1] = new Timestamp(endDate.getTimeInMillis());
            ResultSet results = DAOProvider.SelectTableSecure(tableName, "*",
                    " timestamp >= ? and timestamp <= ? ", "", con, parameters);
            while (results.next()) {
                WorstPylonCase dataTuple = new WorstPylonCase(results.getInt(fields[0]));

                Pylon pylon = new Pylon(results.getInt(fields[0]));
                pylon.setN(results.getFloat(fields[1]));
                pylon.setTx(results.getFloat(fields[2]));
                pylon.setTy(results.getFloat(fields[3]));
                pylon.setMx(results.getFloat(fields[4]));
                pylon.setMy(results.getFloat(fields[5]));
                pylon.setM(results.getFloat(fields[6]));

                dataTuple.setPylon(pylon);

                dataTuple.setID(results.getLong("ID"));
                dataTuple.setComboNumber(results.getInt(fields[8]));
                dataTuple.setSafetyFactor(results.getFloat(fields[7]));
                dataTuple.setTimestamp(results.getTimestamp(fields[9]).getTime());

                worstCaseDataList.add(dataTuple);
            }
        } catch (Exception exc) {
            exc.printStackTrace();
        }
        con.close();
        return worstCaseDataList;
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    return null;

}

From source file:com.mozilla.hadoop.hbase.mapreduce.MultiScanTableMapReduceUtil.java

/**
 * Generates an array of scans for hex character and date prefixed ranges for the given dates (e.g. 16 buckets)
 * @param startCal//from  w  w w .  j  av a  2  s  .c om
 * @param endCal
 * @param dateFormat
 * @param columns
 * @param caching
 * @param cacheBlocks
 * @return
 */
public static Scan[] generateHexPrefixScans(Calendar startCal, Calendar endCal, String dateFormat,
        List<Pair<String, String>> columns, int caching, boolean cacheBlocks) {
    ArrayList<Scan> scans = new ArrayList<Scan>();
    String[] salts = new String[16];
    for (int i = 0; i < 16; i++) {
        salts[i] = Integer.toHexString(i);
    }

    SimpleDateFormat rowsdf = new SimpleDateFormat(dateFormat);
    long endTime = DateUtil.getEndTimeAtResolution(endCal.getTimeInMillis(), Calendar.DATE);

    while (startCal.getTimeInMillis() < endTime) {
        int d = Integer.parseInt(rowsdf.format(startCal.getTime()));

        for (int i = 0; i < salts.length; i++) {
            Scan s = new Scan();
            s.setCaching(caching);
            s.setCacheBlocks(cacheBlocks);

            // add columns
            for (Pair<String, String> pair : columns) {
                s.addColumn(pair.getFirst().getBytes(), pair.getSecond().getBytes());
            }

            s.setStartRow(Bytes.toBytes(salts[i] + String.format("%06d", d)));
            s.setStopRow(Bytes.toBytes(salts[i] + String.format("%06d", d + 1)));

            if (LOG.isDebugEnabled()) {
                LOG.debug("Adding start-stop range: " + salts[i] + String.format("%06d", d) + " - " + salts[i]
                        + String.format("%06d", d + 1));
            }

            scans.add(s);
        }

        startCal.add(Calendar.DATE, 1);
    }

    return scans.toArray(new Scan[scans.size()]);
}

From source file:Main.java

public static boolean isToday(long dateUtc) {
    final long currentTime = System.currentTimeMillis();
    final Calendar calendarBefore = Calendar.getInstance();
    calendarBefore.setTimeInMillis(currentTime);
    calendarBefore.set(Calendar.HOUR_OF_DAY, 0);
    calendarBefore.set(Calendar.MINUTE, 0);
    calendarBefore.set(Calendar.SECOND, 0);
    calendarBefore.set(Calendar.MILLISECOND, 0);

    //// w  w  w . ja v  a  2 s .  c o  m
    final Calendar calendarAfter = Calendar.getInstance();
    calendarAfter.setTimeInMillis(currentTime);
    calendarAfter.set(Calendar.HOUR_OF_DAY, 23);
    calendarAfter.set(Calendar.MINUTE, 59);
    calendarAfter.set(Calendar.SECOND, 59);
    calendarAfter.set(Calendar.MILLISECOND, 250);
    if ((dateUtc >= calendarBefore.getTimeInMillis()) && (dateUtc <= calendarAfter.getTimeInMillis())) {
        return true;
    }
    return false;
}

From source file:de.fahrgemeinschaft.FahrgemeinschaftConnector.java

public static long getNextDayMorning(long dep) {
    if (dep != 0) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(dep + 25 * 3600000); // plus one(!) day
        c.set(Calendar.HOUR_OF_DAY, 0); // reset
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTimeInMillis();
    } else//from   www.  j  a v  a2 s . co m
        return 0;
}