Example usage for java.util Calendar setTimeInMillis

List of usage examples for java.util Calendar setTimeInMillis

Introduction

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

Prototype

public void setTimeInMillis(long millis) 

Source Link

Document

Sets this Calendar's current time from the given long value.

Usage

From source file:org.esupportail.portlet.filemanager.services.sardine.SardineAccessImpl.java

private JsTreeFile resourceAsJsTreeFile(DavResource resource, boolean folderDetails, boolean fileDetails) {

    // lid must be a relative path from rootPath
    String lid = resource.getHref().getRawPath();

    if (lid.startsWith(this.rootPath))
        lid = lid.substring(rootPath.length());
    if (lid.startsWith("/"))
        lid = lid.substring(1);/*from w ww  . j av a  2  s .  c  o m*/

    String title = resource.getName();
    String type = resource.isDirectory() ? "folder" : "file";

    if ("".equals(lid))
        type = "drive";

    JsTreeFile file = new JsTreeFile(title, lid, type);

    if (fileDetails && "file".equals(type)) {
        String icon = resourceUtils.getIcon(title);
        file.setIcon(icon);
        file.setSize(resource.getContentLength().longValue());
        file.setOverSizeLimit(file.getSize() > resourceUtils.getSizeLimit(title));
    }

    try {
        if (folderDetails && resource.isDirectory()) {
            List<DavResource> children;
            children = root.list(this.uri + lid);
            long totalSize = 0;
            long fileCount = 0;
            long folderCount = -1; // Don't count the parent folder
            for (DavResource child : children) {
                if (child.isDirectory()) {
                    ++folderCount;
                } else {
                    ++fileCount;
                    totalSize += child.getContentLength().longValue();
                }
                file.setTotalSize(totalSize);
                file.setFileCount(fileCount);
                file.setFolderCount(folderCount);
            }
        }
    } catch (SardineException ex) {
        log.warn("Error retrying children of this resource : " + this.uri + lid, ex);
    } catch (IOException ioe) {
        log.error("IOException retrieving children  : " + this.uri + lid, ioe);
    }

    if (resource.getModified() != null) {

        final Calendar date = Calendar.getInstance();
        date.setTimeInMillis(resource.getModified().getTime());
        // In order to have a readable date
        file.setLastModifiedTime(new SimpleDateFormat(this.datePattern).format(date.getTime()));
    }
    return file;
}

From source file:com.wildplot.android.ankistats.WeeklyBreakdown.java

public boolean calculateBreakdown(int type) {
    mTitle = R.string.stats_weekly_breakdown;
    mAxisTitles = new int[] { R.string.stats_day_of_week, R.string.stats_percentage_correct,
            R.string.stats_reviews };//from   w  w w .  ja v  a2s  .com

    mValueLabels = new int[] { R.string.stats_percentage_correct, R.string.stats_answers };
    mColors = new int[] { R.color.stats_counts, R.color.stats_hours };

    mType = type;
    String lim = _revlogLimitWholeOnly().replaceAll("[\\[\\]]", "");

    if (lim.length() > 0) {
        lim = " and " + lim;
    }

    Calendar sd = GregorianCalendar.getInstance();
    sd.setTimeInMillis(mCollectionData.getDayCutoff() * 1000);

    int pd = _periodDays();
    if (pd > 0) {
        lim += " and id > " + ((mCollectionData.getDayCutoff() - (86400 * pd)) * 1000);
    }

    long cutoff = mCollectionData.getDayCutoff();
    long cut = cutoff - sd.get(Calendar.HOUR_OF_DAY) * 3600;

    ArrayList<double[]> list = new ArrayList<double[]>();
    Cursor cur = null;
    String query = "SELECT strftime('%w',datetime( cast(id/ 1000  -" + sd.get(Calendar.HOUR_OF_DAY) * 3600
            + " as int), 'unixepoch')) as wd, " + "sum(case when ease = 1 then 0 else 1 end) / "
            + "cast(count() as float) * 100, " + "count() " + "from revlog " + "where type in (0,1,2) " + lim
            + " " + "group by wd " + "order by wd";
    Log.d(AnkiStatsApplication.TAG,
            sd.get(Calendar.HOUR_OF_DAY) + " : " + cutoff + " weekly breakdown query: " + query);
    try {
        cur = mAnkiDb.getDatabase().rawQuery(query, null);
        while (cur.moveToNext()) {
            list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) });
        }

    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }

    //TODO adjust for breakdown, for now only copied from intervals
    // small adjustment for a proper chartbuilding with achartengine
    //        if (list.size() == 0 || list.get(0)[0] > 0) {
    //            list.add(0, new double[] { 0, 0, 0 });
    //        }
    //        if (num == -1 && list.size() < 2) {
    //            num = 31;
    //        }
    //        if (type != Utils.TYPE_LIFE && list.get(list.size() - 1)[0] < num) {
    //            list.add(new double[] { num, 0, 0 });
    //        } else if (type == Utils.TYPE_LIFE && list.size() < 2) {
    //            list.add(new double[] { Math.max(12, list.get(list.size() - 1)[0] + 1), 0, 0 });
    //        }

    mSeriesList = new double[4][list.size()];
    mPeak = 0.0;
    mMcount = 0.0;
    double minHour = Double.MAX_VALUE;
    double maxHour = 0;
    for (int i = 0; i < list.size(); i++) {
        double[] data = list.get(i);
        int hour = (int) data[0];

        //double hour = data[0];
        if (hour < minHour)
            minHour = hour;

        if (hour > maxHour)
            maxHour = hour;

        double pct = data[1];
        if (pct > mPeak)
            mPeak = pct;

        mSeriesList[0][i] = hour;
        mSeriesList[1][i] = pct;
        mSeriesList[2][i] = data[2];
        if (i == 0) {
            mSeriesList[3][i] = pct;
        } else {
            double prev = mSeriesList[3][i - 1];
            double diff = pct - prev;
            diff /= 3.0;
            diff = Math.round(diff * 10.0) / 10.0;

            mSeriesList[3][i] = prev + diff;
        }

        if (data[2] > mMcount)
            mMcount = data[2];
        if (mSeriesList[1][i] > mMaxCards)
            mMaxCards = (int) mSeriesList[1][i];
    }

    mMaxElements = (int) (maxHour - minHour);
    return list.size() > 0;
}

From source file:py.una.pol.karaku.dao.where.DateClauses.java

@Nonnull
private Calendar getEpoch() {

    Calendar epoch = Calendar.getInstance();
    epoch.setTimeInMillis(EPOCH_MILISECONDS);
    return epoch;
}

From source file:net.audumla.climate.bom.BOMStatisticalClimateDataObserver.java

private WritableClimateObservation getObservation(WritableClimateData bomdata, int hour) {
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(0);
    c.set(Calendar.HOUR_OF_DAY, hour);
    Date requiredTime = c.getTime();
    WritableClimateObservation obs = null;
    try {// w ww  .ja v  a 2  s.  c o  m
        obs = ClimateDataFactory.convertToWritableClimateObservation(
                bomdata.getObservation(requiredTime, ClimateData.ObservationMatch.CLOSEST));
        if (obs != null && DateUtils.getFragmentInHours(obs.getTime(), Calendar.DAY_OF_YEAR) == hour) {
            return obs;
        }
    } catch (Exception ignored) {
        logger.error(ignored);
        ignored.printStackTrace();
    }
    obs = ClimateDataFactory.newWritableClimateObservation(this, getSource());
    obs.setTime(requiredTime);
    bomdata.addObservation(obs);
    return obs;
}

From source file:DateTime.java

/** Formats the value as an RFC 3339 date/time string. */
public String toStringRfc3339() {

    StringBuilder sb = new StringBuilder();

    Calendar dateTime = new GregorianCalendar(GMT);
    long localTime = value;
    Integer tzShift = this.tzShift;
    if (tzShift != null) {
        localTime += tzShift.longValue() * 60000;
    }//w ww. j av a2s. c o  m
    dateTime.setTimeInMillis(localTime);

    appendInt(sb, dateTime.get(Calendar.YEAR), 4);
    sb.append('-');
    appendInt(sb, dateTime.get(Calendar.MONTH) + 1, 2);
    sb.append('-');
    appendInt(sb, dateTime.get(Calendar.DAY_OF_MONTH), 2);

    if (!dateOnly) {

        sb.append('T');
        appendInt(sb, dateTime.get(Calendar.HOUR_OF_DAY), 2);
        sb.append(':');
        appendInt(sb, dateTime.get(Calendar.MINUTE), 2);
        sb.append(':');
        appendInt(sb, dateTime.get(Calendar.SECOND), 2);

        if (dateTime.isSet(Calendar.MILLISECOND)) {
            sb.append('.');
            appendInt(sb, dateTime.get(Calendar.MILLISECOND), 3);
        }
    }

    if (tzShift != null) {

        if (tzShift.intValue() == 0) {

            sb.append('Z');

        } else {

            int absTzShift = tzShift.intValue();
            if (tzShift > 0) {
                sb.append('+');
            } else {
                sb.append('-');
                absTzShift = -absTzShift;
            }

            int tzHours = absTzShift / 60;
            int tzMinutes = absTzShift % 60;
            appendInt(sb, tzHours, 2);
            sb.append(':');
            appendInt(sb, tzMinutes, 2);
        }
    }

    return sb.toString();
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskXMsgClient.CFAsteriskXMsgClientSchema.java

public static Calendar convertTimeString(String val) {
    if ((val == null) || (val.length() == 0)) {
        return (null);
    } else if (val.length() != 8) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(CFAsteriskXMsgClientSchema.class,
                "convertTimeString", "Value must be in HH24:MI:SS format, \"" + val + "\" is invalid");
    } else if (((val.charAt(0) >= '0') && (val.charAt(0) <= '2'))
            && ((val.charAt(1) >= '0') && (val.charAt(1) <= '9')) && (val.charAt(2) == ':')
            && ((val.charAt(3) >= '0') && (val.charAt(3) <= '5'))
            && ((val.charAt(4) >= '0') && (val.charAt(4) <= '9')) && (val.charAt(5) == ':')
            && ((val.charAt(6) >= '0') && (val.charAt(6) <= '5'))
            && ((val.charAt(7) >= '0') && (val.charAt(7) <= '9'))) {
        /*//from w w  w  . jav  a  2  s  . c om
         *   NOTE:
         *      .Net uses substring( startcol, lengthOfSubstring )
         *      Java uses substring( startcol, endcol ) and does not
         *         include charAt( endcol );
         */
        int hour = Integer.parseInt(val.substring(0, 2));
        int minute = Integer.parseInt(val.substring(3, 5));
        int second = Integer.parseInt(val.substring(6, 8));
        Calendar retval = new GregorianCalendar(CFLibDbUtil.getDbServerTimeZone());
        retval.set(Calendar.YEAR, 2000);
        retval.set(Calendar.MONTH, 0);
        retval.set(Calendar.DAY_OF_MONTH, 1);
        retval.set(Calendar.HOUR_OF_DAY, hour);
        retval.set(Calendar.MINUTE, minute);
        retval.set(Calendar.SECOND, second);
        Calendar local = new GregorianCalendar();
        local.setTimeInMillis(retval.getTimeInMillis());
        return (local);
    } else {
        throw CFLib.getDefaultExceptionFactory().newUsageException(CFAsteriskXMsgClientSchema.class,
                "convertTimeString", "Value must be in HH24:MI:SS format \"" + val + "\" is invalid");
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskXMsgClient.CFAsteriskXMsgClientSchema.java

public static Calendar convertDateString(String val) {
    if ((val == null) || (val.length() == 0)) {
        return (null);
    } else if (val.length() != 10) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(CFAsteriskXMsgClientSchema.class,
                "convertDateString", "Value must be in YYYY-MM-DD format, \"" + val + "\" is invalid");
    } else if (((val.charAt(0) >= '0') && (val.charAt(0) <= '9'))
            && ((val.charAt(1) >= '0') && (val.charAt(1) <= '9'))
            && ((val.charAt(2) >= '0') && (val.charAt(2) <= '9'))
            && ((val.charAt(3) >= '0') && (val.charAt(3) <= '9')) && (val.charAt(4) == '-')
            && ((val.charAt(5) >= '0') && (val.charAt(5) <= '1'))
            && ((val.charAt(6) >= '0') && (val.charAt(6) <= '9')) && (val.charAt(7) == '-')
            && ((val.charAt(8) >= '0') && (val.charAt(8) <= '3'))
            && ((val.charAt(9) >= '0') && (val.charAt(9) <= '9'))) {
        /*//from w  ww . jav  a 2  s  .  c o m
         *   NOTE:
         *      .Net uses substring( startcol, lengthOfSubstring )
         *      Java uses substring( startcol, endcol ) and does not
         *         include charAt( endcol );
         */
        int year = Integer.parseInt(val.substring(0, 4));
        int month = Integer.parseInt(val.substring(5, 7));
        int day = Integer.parseInt(val.substring(8, 10));
        Calendar retval = new GregorianCalendar(CFLibDbUtil.getDbServerTimeZone());
        retval.set(Calendar.YEAR, year);
        retval.set(Calendar.MONTH, month - 1);
        retval.set(Calendar.DAY_OF_MONTH, day);
        retval.set(Calendar.HOUR_OF_DAY, 0);
        retval.set(Calendar.MINUTE, 0);
        retval.set(Calendar.SECOND, 0);
        Calendar local = new GregorianCalendar();
        local.setTimeInMillis(retval.getTimeInMillis());
        return (local);
    } else {
        throw CFLib.getDefaultExceptionFactory().newUsageException(CFAsteriskXMsgClientSchema.class,
                "convertDateString", "Value must be in YYYY-MM-DD format, \"" + val + "\" is invalid");
    }
}

From source file:me.neatmonster.spacertk.scheduler.Job.java

/**
 * Creates a new Job/*from   ww w  . ja va 2 s.  co  m*/
 * @param actionName Action to preform
 * @param actionArguments Arguments to preform the action with
 * @param timeType Type of time to schedule the action with
 * @param timeArgument Argument of time to schedule the action with
 * @param loading If the job is being loaded
 * @throws UnSchedulableException If the action cannot be scheduled
 * @throws UnhandledActionException If the action is unknown
 */
public Job(final String actionName, final Object[] actionArguments, final String timeType,
        final String timeArgument, final boolean loading)
        throws UnSchedulableException, UnhandledActionException {
    if (!SpaceRTK.getInstance().actionsManager.contains(actionName)) {
        if (!loading) {
            final String result = Utilities.sendMethod("isSchedulable", "[\"" + actionName + "\"]");
            if (result == null || !result.equals("true"))
                if (result == null || result.equals(""))
                    throw new UnhandledActionException();
                else
                    throw new UnSchedulableException("Action " + actionName + " isn't schedulable!");
        }
    } else if (!SpaceRTK.getInstance().actionsManager.isSchedulable(actionName))
        throw new UnSchedulableException("Action " + actionName + " isn't schedulable!");
    this.actionName = actionName;
    this.actionArguments = actionArguments;
    this.timeType = timeType;
    this.timeArgument = timeArgument;
    if (timeType.equals("EVERYXHOURS"))
        timer.scheduleAtFixedRate(this, Integer.parseInt(timeArgument) * 3600000L,
                Integer.parseInt(timeArgument) * 3600000L);
    else if (timeType.equals("EVERYXMINUTES"))
        timer.scheduleAtFixedRate(this, Integer.parseInt(timeArgument) * 60000L,
                Integer.parseInt(timeArgument) * 60000L);
    else if (timeType.equals("ONCEPERDAYAT")) {
        Calendar nextOccurence = Calendar.getInstance();
        nextOccurence.set(Calendar.HOUR, Integer.parseInt(timeArgument.split(":")[0]));
        nextOccurence.set(Calendar.MINUTE, Integer.parseInt(timeArgument.split(":")[1]));
        if (nextOccurence.before(new Date()))
            nextOccurence = Calendar.getInstance();
        nextOccurence.setTimeInMillis(nextOccurence.getTimeInMillis() + 86400000L);
        timer.scheduleAtFixedRate(this, nextOccurence.getTime(), 86400000L);
    } else if (timeType.equals("XMINUTESPASTEVERYHOUR")) {
        Calendar nextOccurence = Calendar.getInstance();
        nextOccurence.set(Calendar.MINUTE, Integer.parseInt(timeArgument));
        if (nextOccurence.before(new Date()))
            nextOccurence = Calendar.getInstance();
        nextOccurence.setTimeInMillis(nextOccurence.getTimeInMillis() + 3600000L);
        timer.scheduleAtFixedRate(this, nextOccurence.getTime(), 3600000L);
    }
    Scheduler.saveJobs();
}

From source file:fr.paris.lutece.plugins.extend.modules.rating.service.security.RatingSecurityService.java

/**
 * {@inheritDoc}// w  ww .  ja v  a2s.c o  m
 * @throws UserNotSignedException
 */
@Override
public boolean canVote(HttpServletRequest request, String strIdExtendableResource,
        String strExtendableResourceType) throws UserNotSignedException {
    // Check if the config exists
    RatingExtenderConfig config = _configService.find(RatingResourceExtender.RESOURCE_EXTENDER,
            strIdExtendableResource, strExtendableResourceType);

    if (config == null || isVoteClosed(config)) {
        return false;
    }

    // Only connected user can vote
    if (config.isLimitedConnectedUser() && SecurityService.isAuthenticationEnable()) {
        LuteceUser user = SecurityService.getInstance().getRegisteredUser(request);

        if (user == null) {
            throw new UserNotSignedException();
        }
    }

    // User can vote a limited time per ressource
    if (config.getNbVotePerUser() > 0) {
        ResourceExtenderHistoryFilter filter = new ResourceExtenderHistoryFilter();

        filter.setExtendableResourceType(strExtendableResourceType);

        if (SecurityService.isAuthenticationEnable()) {
            LuteceUser user = SecurityService.getInstance().getRegisteredUser(request);

            if (user != null) {
                filter.setUserGuid(user.getName());
            }
        } else {
            filter.setIpAddress(request.getRemoteAddr());
        }

        List<ResourceExtenderHistory> listHistories = _resourceExtenderHistoryService.findByFilter(filter);

        if (listHistories.size() >= config.getNbVotePerUser()) {
            // User has already use all is vote
            return false;
        }
    }

    ResourceExtenderDTOFilter extenderFilter = new ResourceExtenderDTOFilter();
    extenderFilter.setFilterExtendableResourceType(strExtendableResourceType);

    List<ResourceExtenderDTO> extenders = _extenderService.findByFilter(extenderFilter);

    if (CollectionUtils.isNotEmpty(extenders)) {
        for (ResourceExtenderDTO extender : extenders) {
            if (!extender.isIsActive()) {
                return false;
            }
        }
    }

    Rating rating = _ratingService.findByResource(strIdExtendableResource, strExtendableResourceType);

    // Check if the rating exists
    if (rating == null) {
        // It is the first time the ressource is being voted
        return true;
    }

    // If it is set as unlimited vote, then the user can vote anytime
    if (config.isUnlimitedVote()) {
        return true;
    }

    // Search the voting histories of the user
    ResourceExtenderHistoryFilter filter = new ResourceExtenderHistoryFilter();
    filter.setIdExtendableResource(rating.getIdExtendableResource());

    if (SecurityService.isAuthenticationEnable()) {
        LuteceUser user = SecurityService.getInstance().getRegisteredUser(request);

        if (user != null) {
            filter.setUserGuid(user.getName());
        }
    } else {
        filter.setIpAddress(request.getRemoteAddr());
    }
    filter.setSortedAttributeName(FILTER_SORT_BY_DATE_VOTE);
    filter.setAscSort(false);

    List<ResourceExtenderHistory> listHistories = _resourceExtenderHistoryService.findByFilter(filter);

    if ((listHistories != null) && !listHistories.isEmpty()) {
        // If unique vote, then the user is prohibited to vote
        if (config.isUniqueVote()) {
            return false;
        }

        // Get the last vote history
        ResourceExtenderHistory ratingHistory = listHistories.get(0);

        Calendar calendarToday = new GregorianCalendar();
        Calendar calendarVote = new GregorianCalendar();
        Date dateVote = ratingHistory.getDateCreation();
        calendarVote.setTimeInMillis(dateVote.getTime());
        calendarVote.add(Calendar.DATE, config.getNbDaysToVote());

        // The date of last vote must be < today
        if (calendarToday.getTimeInMillis() < calendarVote.getTimeInMillis()) {
            return false;
        }
    }

    // No history found, then it is the first time the user is voting the resource
    return true;
}

From source file:info.raack.appliancelabeler.service.DefaultDataService.java

@Override
@Transactional// w ww. j  a va 2  s.  co m
public void createUserGeneratedLabelsSurroundingAnonymousTransition(int transitionId, int userApplianceId) {
    // get transition
    GenericStateTransition transition = database.getAnonymousApplianceStateTransitionById(transitionId);

    // generate on and off labels 2 seconds before and after transition
    Calendar before = new GregorianCalendar();
    before.setTimeInMillis(transition.getTime());
    before.add(Calendar.SECOND, -2);

    Calendar after = new GregorianCalendar();
    after.setTimeInMillis(transition.getTime());
    after.add(Calendar.SECOND, 2);

    // generate the labels and save them
    UserAppliance userAppliance = database.getUserApplianceById(userApplianceId);

    List<ApplianceStateTransition> transitions = new ArrayList<ApplianceStateTransition>();

    ApplianceStateTransition onTransition = new GenericStateTransition(-1, userAppliance, 0, true,
            before.getTime().getTime());

    ApplianceStateTransition offTransition = new GenericStateTransition(-1, userAppliance, 0, false,
            after.getTime().getTime());
    transitions.add(onTransition);
    transitions.add(offTransition);
    database.storeUserOnOffLabels(transitions);

    // delete the anonymous transition - it will be labeled as a true appliance transition in the next retraining pass
    database.removeTransition(transition);
}