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.linuxbox.enkive.statistics.gathering.past.PastGatherer.java

public List<Map<String, Object>> consolidatePast(int grain, Calendar c) {
    List<Map<String, Object>> result = new LinkedList<Map<String, Object>>();

    while (c.getTimeInMillis() > endDate.getTime()) {
        Date end = c.getTime();/*from   w  ww .j  av a  2s.co  m*/
        if (grain == CONSOLIDATION_HOUR) {
            c.add(Calendar.HOUR_OF_DAY, -1);
        } else if (grain == CONSOLIDATION_DAY) {
            c.add(Calendar.DATE, -1);
        } else if (grain == CONSOLIDATION_WEEK) {
            c.add(Calendar.DATE, -7);
        } else if (grain == CONSOLIDATION_MONTH) {
            c.add(Calendar.MONTH, -1);
        }
        Date start = c.getTime();
        try {
            Map<String, Object> consolidated = getConsolidatedData(start, end, grain);
            if (consolidated != null) {
                result.add(consolidated);
            } else {
                break;
            }
        } catch (GathererException e) {
            LOGGER.error("Consolidated gatherer error on range " + start + " to " + end, e);
        }
    }
    return result;
}

From source file:com.milos.neo4j.dao.impl.GameDAOImpl.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override/*  w  w w . ja  va2 s .  com*/
public void endOldGames() {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.HOUR, -1);
    String updateQuery = "MATCH (g:Game) where g.ended = false and g.roundStartDate <= {date} set g.ended = true";
    Map<String, Long> params = new HashMap<>();
    params.put("date", calendar.getTimeInMillis());
    session.query(updateQuery, params, false);
}

From source file:org.kuali.mobility.socialmedia.service.TwitterServiceImpl.java

@SuppressWarnings("unchecked")
private TwitterFeed updateFeed(TwitterFeed feedToUpdate) {
    try {//from w w w  . java  2s  .  c  o  m
        LOG.info("Updating Twitter feed: " + feedToUpdate.getTwitterId());
        URL url = new URL("http://api.twitter.com/1/statuses/user_timeline.json?screen_name="
                + feedToUpdate.getTwitterId() + "&exclude_replies=true&include_entities=true");
        URLConnection conn = url.openConnection();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        String json = sb.toString();

        JSONArray tweetArray = (JSONArray) JSONSerializer.toJSON(json);
        List<Tweet> tweets = new ArrayList<Tweet>();
        for (Iterator<JSONObject> iter = tweetArray.iterator(); iter.hasNext();) {
            try {
                JSONObject tweetObject = iter.next();
                JSONObject user = tweetObject.getJSONObject("user");
                JSONObject entities = tweetObject.getJSONObject("entities");
                JSONArray hashTags = entities.getJSONArray("hashtags");
                JSONArray urls = entities.getJSONArray("urls");
                JSONArray mentions = entities.getJSONArray("user_mentions");

                Tweet tweet = new Tweet();
                tweet.setProfileImageUrl(user.getString("profile_image_url_https"));
                tweet.setScreenName(user.getString("screen_name"));
                tweet.setUserName(user.getString("name"));
                tweet.setId(tweetObject.getString("id_str"));

                String text = tweetObject.getString("text");
                text = fixEntities(text, hashTags, urls, mentions);
                tweet.setText(text);

                String publishDate = tweetObject.getString("created_at").replace("+0000", "GMT");
                tweet.setTimestamp(twitterDateFormat.parse(publishDate).getTime());

                tweets.add(tweet);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }
        if (!tweets.isEmpty()) {
            feedToUpdate.setTweets(tweets);
            Calendar currentDate = Calendar.getInstance();
            feedToUpdate.setLastUpdated(currentDate.getTimeInMillis());
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

    return feedToUpdate;
}

From source file:com.milos.neo4j.dao.impl.GameDAOImpl.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override//from  www.j ava 2 s.  co m
public void deleteOldGames() {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.WEEK_OF_MONTH, -1);
    String deleteQuery = "MATCH (n:UserGameScores)--(g:Game) where g.creationDate <= {date} detach delete n, g";
    Map<String, Long> params = new HashMap<>();
    params.put("date", calendar.getTimeInMillis());
    session.query(deleteQuery, params, false);
}

From source file:eu.planets_project.tb.gui.backing.exp.EvaluationPropertyResultsBean.java

public void addMeasurementResult(Calendar runDate, String stageName, MeasurementImpl result) {
    //fetch the hm and add an additional stageName that shall be compared for the propertyID
    if (runDate != null && this.evalresults.get(runDate.getTimeInMillis()) != null) {
        this.evalresults.get(runDate.getTimeInMillis()).put(stageName, new EvalRecordBean(result));
    }//from  w  ww  .j  a v  a 2 s  .  com
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java

public Bitmap getDMPicture(String picUrl, Twitter twitter) {

    try {/*from  www .j  a  v  a 2  s .c o m*/
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = picUrl;
        String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "")
                .replace("/", "");
        String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", "");
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host);
        Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path);

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);

        StatusLine statusLine = response2.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200 || statusCode == 302) {
            HttpEntity entity = response2.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmap;
        } else {
            Log.v("talon_dm_image", statusCode + "");
        }

        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.l2jfree.gameserver.instancemanager.GameTimeManager.java

private GameTimeManager() {
    new File("data/serial").mkdirs();

    final Calendar cal = loadData();

    if (cal != null) {
        _calendar.setTimeInMillis(cal.getTimeInMillis());
    } else {/*  w  w w  . ja v a 2s  .  c o  m*/
        _calendar.set(Calendar.YEAR, 1281);
        _calendar.set(Calendar.MONTH, 5);
        _calendar.set(Calendar.DAY_OF_MONTH, 5);
        _calendar.set(Calendar.HOUR_OF_DAY, 23);
        _calendar.set(Calendar.MINUTE, 45);

        saveData();
    }

    ThreadPoolManager.getInstance().scheduleAtFixedRate(new MinuteCounter(), 0, 60000 / Config.DATETIME_MULTI);

    _log.info("GameTimeController: Initialized.");
}

From source file:com.QuarkLabs.BTCeClient.fragments.HistoryFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mDateFormat = android.text.format.DateFormat.getDateFormat(getActivity());
    mHistoryType = (ListType) getArguments().getSerializable(mListTypeTag);
    mLoaderId = mHistoryType.ordinal();//from   ww w . j  a  v  a 2  s. com
    //if we have StartDate and EndDate selected before
    if (savedInstanceState != null) {
        try {
            mStartDateValue = mDateFormat.parse(savedInstanceState.getString("startDate"));
            mEndDateValue = mDateFormat.parse(savedInstanceState.getString("endDate"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } else {
        Calendar calendar = Calendar.getInstance();
        mStartDateValue = new Date(calendar.getTimeInMillis() - WEEK);
        mEndDateValue = new Date(calendar.getTimeInMillis());
    }

    //creating bundle for loader
    Bundle bundle = new Bundle();
    bundle.putString("startDate", String.valueOf(mStartDateValue.getTime() / 1000));
    bundle.putString("endDate", String.valueOf(mEndDateValue.getTime() / 1000));
    getLoaderManager().initLoader(mLoaderId, bundle, this);
}

From source file:com.hihframework.core.utils.DateUtils.java

/**
 * ??//from  www  .  j av  a  2 s .  com
 *
 * @return ?
 */
public static java.sql.Date getNowDate() {
    Calendar cal = Calendar.getInstance();
    return new java.sql.Date(cal.getTimeInMillis());
}

From source file:com.evolveum.midpoint.repo.sql.CleanupTest.java

License:asdf

@Test
public void testAuditCleanup() throws Exception {
    //GIVEN//from w  w  w . j a  va2s .  c  o m
    Calendar calendar = create_2013_07_12_12_00_Calendar();
    for (int i = 0; i < 3; i++) {
        long timestamp = calendar.getTimeInMillis();
        AuditEventRecord record = new AuditEventRecord();
        record.addDelta(createObjectDeltaOperation(i));
        record.setTimestamp(timestamp);
        LOGGER.info("Adding audit record with timestamp {}", new Object[] { new Date(timestamp) });

        auditService.audit(record, new SimpleTaskAdapter());
        calendar.add(Calendar.HOUR_OF_DAY, 1);
    }

    Session session = getFactory().openSession();
    try {
        session.beginTransaction();

        Query query = session.createQuery("select count(*) from " + RAuditEventRecord.class.getSimpleName());
        Long count = (Long) query.uniqueResult();

        AssertJUnit.assertEquals(3L, (long) count);
        session.getTransaction().commit();
    } finally {
        session.close();
    }

    //WHEN
    calendar = create_2013_07_12_12_00_Calendar();
    calendar.add(Calendar.HOUR_OF_DAY, 1);
    calendar.add(Calendar.MINUTE, 1);

    final long NOW = System.currentTimeMillis();
    CleanupPolicyType policy = createPolicy(calendar, NOW);

    OperationResult result = new OperationResult("Cleanup audit");
    auditService.cleanupAudit(policy, result);
    result.recomputeStatus();

    //THEN
    AssertJUnit.assertTrue(result.isSuccess());

    session = getFactory().openSession();
    try {
        session.beginTransaction();

        Query query = session.createQuery("from " + RAuditEventRecord.class.getSimpleName());
        List<RAuditEventRecord> records = query.list();

        AssertJUnit.assertEquals(1, records.size());
        RAuditEventRecord record = records.get(0);

        Date finished = new Date(record.getTimestamp().getTime());

        Date mark = new Date(NOW);
        Duration duration = policy.getMaxAge();
        duration.addTo(mark);

        AssertJUnit.assertTrue("finished: " + finished + ", mark: " + mark, finished.after(mark));

        session.getTransaction().commit();
    } finally {
        session.close();
    }
}