Example usage for java.util Calendar HOUR

List of usage examples for java.util Calendar HOUR

Introduction

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

Prototype

int HOUR

To view the source code for java.util Calendar HOUR.

Click Source Link

Document

Field number for get and set indicating the hour of the morning or afternoon.

Usage

From source file:com.versobit.weatherdoge.WeatherUtil.java

private static String convertYahooCode(String code, String weatherTime, String sunrise, String sunset) {
    Date weatherDate = new Date();
    try {//  w ww.  jav a 2  s  . c o  m
        weatherDate = YAHOO_DATE_FORMAT.parse(weatherTime);
    } catch (ParseException ex) {
        Log.e(TAG, "Yahoo date format failed!", ex);
    }
    Calendar weatherCal = new GregorianCalendar();
    Calendar sunriseCal = new GregorianCalendar();
    Calendar sunsetCal = new GregorianCalendar();
    weatherCal.setTime(weatherDate);
    sunriseCal.setTime(weatherDate);
    sunsetCal.setTime(weatherDate);

    Matcher sunriseMatch = YAHOO_TIME.matcher(sunrise);
    Matcher sunsetMatch = YAHOO_TIME.matcher(sunset);
    if (!sunriseMatch.matches() || !sunsetMatch.matches()) {
        Log.e(TAG, "Failed to find sunrise/sunset. Using defaults.");
        sunriseMatch = YAHOO_TIME.matcher("6:00 am");
        sunsetMatch = YAHOO_TIME.matcher("6:00 pm");
        sunriseMatch.matches();
        sunsetMatch.matches();
    }
    // Set the sunrise to the correct hour and minute of the same day
    sunriseCal.set(Calendar.HOUR, Integer.parseInt(sunriseMatch.group(1)));
    sunriseCal.set(Calendar.MINUTE, Integer.parseInt(sunriseMatch.group(2)));
    sunriseCal.set(Calendar.SECOND, 0);
    sunriseCal.set(Calendar.MILLISECOND, 0);
    sunriseCal.set(Calendar.AM_PM, "am".equals(sunriseMatch.group(3)) ? Calendar.AM : Calendar.PM);

    // Set the sunset to the correct hour and minute of the same day
    sunsetCal.set(Calendar.HOUR, Integer.parseInt(sunsetMatch.group(1)));
    sunsetCal.set(Calendar.MINUTE, Integer.parseInt(sunsetMatch.group(2)));
    sunsetCal.set(Calendar.SECOND, 0);
    sunsetCal.set(Calendar.MILLISECOND, 0);
    sunsetCal.set(Calendar.AM_PM, "am".equals(sunsetMatch.group(3)) ? Calendar.AM : Calendar.PM);

    boolean isDaytime = true;
    if (weatherCal.before(sunriseCal) || weatherCal.after(sunsetCal)) {
        isDaytime = false;
    }

    String owmCode = "01";
    switch (Integer.parseInt(code)) {
    // Thunderstorms
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 17:
    case 37:
    case 38:
    case 39:
    case 45:
    case 47:
        owmCode = "11";
        break;
    // Snow
    case 5:
    case 7:
    case 13:
    case 14:
    case 15:
    case 16:
    case 18:
    case 41:
    case 42:
    case 43:
    case 46:
        owmCode = "13";
        break;
    // Rain
    case 6:
    case 10:
    case 35:
        owmCode = "09";
        break;
    // Light-ish Rain
    case 8:
    case 9:
    case 11:
    case 12:
    case 40:
        owmCode = "10";
        break;
    // Fog
    case 19:
    case 20:
    case 21:
    case 22:
        owmCode = "50";
        break;
    // Cloudy
    case 27:
    case 28:
        owmCode = "04";
        break;
    // (Other) Cloudy
    case 26:
        owmCode = "03";
        break;
    // Partly Cloudy
    case 23:
    case 24:
    case 25:
    case 29:
    case 30:
    case 44:
        owmCode = "02";
        break;
    // Clear
    case 31:
    case 32:
    case 33:
    case 34:
    case 36:
        owmCode = "01";
        break;
    }
    return owmCode + (isDaytime ? "d" : "n");
}

From source file:com.ltmonitor.jt808.service.impl.CommandService.java

 /**
 * ??// www.  java 2  s  . c  om
 * 
 * @param cmdType
 * @return
 */
public final TerminalCommand getLatestCommand(int cmdType,String simNo) {
   try {
      String hsql = "from TerminalCommand where cmdType = ? and simNo = ? and createDate > ? order by createDate desc";
      TerminalCommand tc = (TerminalCommand) getBaseDao()
            .find(hsql,
                  new Object[] {
                        cmdType, simNo,
                        DateUtil.getDate(DateUtil.now(),
                              Calendar.HOUR, -1) });
      return tc;
   } catch (Exception ex) {
      logger.error(ex.getMessage(), ex);
   }
   return null;
}

From source file:com.sube.daos.mongodb.StatisticDaoTest.java

private void generateUsages() throws InvalidSubeCardException, InvalidProviderException {
    for (int i = 0; i < usagesSize; i++) {
        SubeCardUsage usage = new SubeCardUsage();
        usage.setCard((SubeCard) getRandom(cards));
        Date randomDate = DateUtils.round(
                DateUtils.round(DateUtils.round(getRandomDate(FROM, TO), Calendar.SECOND), Calendar.MINUTE),
                Calendar.HOUR);
        usage.setDatetime(randomDate);//  w ww  .  ja  va  2s.  co m
        if ((randomDate.after(TO_DIFF) || DateUtils.isSameDay(randomDate, TO_DIFF))
                && (randomDate.before(TO) || DateUtils.isSameDay(randomDate, TO))) {
            Long count = usages1.get(randomDate);
            if (count != null) {
                count++;
            } else {
                count = Long.valueOf(1l);
            }
            usages1.put(randomDate, count);
        } else if ((randomDate.after(FROM) || DateUtils.isSameDay(randomDate, FROM))
                && (randomDate.before(FROM_DIFF) || DateUtils.isSameDay(randomDate, FROM_DIFF))) {
            Long count = usages2.get(randomDate);
            if (count != null) {
                count++;
            } else {
                count = Long.valueOf(1l);
            }
            usages2.put(randomDate, count);
        }
        if (random.nextInt() % 2 == 0) {
            //Charge Money
            usage.setMoney((random.nextDouble() + 0.1d) * MONEY_LAMBDA); // 3.1
            // max,
            // min
            // 0.1
            usage.setPerformer((Provider) getRandom(cashierProviders));
            cardUsagesDao.chargeMoney(usage);
        } else {
            //Charge Service
            usage.setMoney((random.nextDouble() + 0.1d) * -MONEY_LAMBDA); // -3.1
            // min,
            // max
            // -0.1
            usage.setPerformer((Provider) getRandom(serviceProviders));
            cardUsagesDao.chargeService(usage);
            Long travelsCount = travels.get(usage.getCard());
            if (travelsCount == null) {
                travelsCount = Long.valueOf(1l);
            } else {
                travelsCount++;
            }
            travels.put(usage.getCard(), travelsCount);
        }
        Double totalMoney = usages.get(usage.getPerformer());
        if (totalMoney == null) {
            usages.put(usage.getPerformer(), Math.abs(usage.getMoney()));
        } else {
            totalMoney += Math.abs(usage.getMoney());
            usages.put(usage.getPerformer(), totalMoney);
        }
        registerMoneyExpended(usage);
    }
}

From source file:com.useeasy.auction.action.GuestApplicationAction.java

public String showApply() {
    logger.info(/*from   ww w  .  j av a  2s . com*/
            "" + ((SessionContainer) ActionContext.getContext().getSession().get(Constants.SESEION_LISTENER))
                    .getAuctionAccount().getId());
    String applyFlag = ServletActionContext.getRequest().getParameter("applyFlag");
    if (applyFlag == null) {
        return "sessionDestory";
    }
    SessionContainer sessionContainer = (SessionContainer) ActionContext.getContext().getSession()
            .get(Constants.SESEION_LISTENER);
    String account_id = "" + sessionContainer.getAuctionAccount().getId();

    ApplicationInfo applicationInfo = iApplication.getApply(applyFlag);
    if (applicationInfo == null || ("1").equals(applicationInfo.getDeleteFlag())
            || !(applicationInfo.getAccountId()).equals(account_id)) {
        return "sessionDestory";
    }
    AuctionInfo auctionInfo = iAuctionInfo.getAuctionInfo(applicationInfo.getAuctionId());
    if (auctionInfo == null || ("1").equals(auctionInfo.getDeleteFlag())
            || ("0").equals(auctionInfo.getPublishFlag())) {
        return "sessionDestory";
    }

    List<PayRecordInfo> marginList = iPayRecordInfo.getCheckedPayRecordList("" + auctionInfo.getId(),
            account_id, "2");
    if (marginList != null && marginList.size() != 0) {
        String marginOrders = "";
        for (int i = 0; i < marginList.size(); i++) {
            PayRecordInfo payRecordInfo = (PayRecordInfo) marginList.get(i);
            marginOrders = marginOrders + payRecordInfo.getOrderId() + "|";
        }
        String companyLiscence = iCompanyInfo.getCompanyInfo(auctionInfo.getAuctionCompanyId())
                .getCompanyLicense();
        List<PaySearchBean> queryList = PayMent.batchorderquery(companyLiscence, marginOrders);
        for (int j = 0; j < queryList.size(); j++) {
            PaySearchBean paySearchBean = (PaySearchBean) queryList.get(j);
            if (paySearchBean.getTranState().equals("1")) {
                PayRecordInfo payRecordInfo = iPayRecordInfo
                        .getPayRecordInfoByOrderId(paySearchBean.getOrder());
                payRecordInfo.setPayStatus("1");
                iPayRecordInfo.savePayRecordInfo(payRecordInfo);

                ItemMargin itemMargin = new ItemMargin();
                itemMargin.setId(null);
                itemMargin.setCreateTime(new Date());
                itemMargin.setAccountId(applicationInfo.getAccountId());
                itemMargin.setAuctionId(applicationInfo.getAuctionId());
                itemMargin.setCompanyId(applicationInfo.getCompanyId());
                itemMargin.setMarginType("2");
                itemMargin.setMarginVal(payRecordInfo.getPayMoney());
                itemMargin.setOrderId(payRecordInfo.getOrderId());
                iItemMargin.saveItemMargin(itemMargin);

                if ("2".equals(auctionInfo.getAuctionWebPayCheck())
                        && !"2".equals(applicationInfo.getApplyStatus())) { //?
                    applicationInfo.setCheckTime(new Date());
                    applicationInfo.setBidNum(auctionInfo.getAutoBidNum());
                    applicationInfo.setTeamAuthority("0");
                    applicationInfo.setApplyStatus("2");
                    String guestNum = Tools.dateToString(new Date(), "yyyyMMddhhmmss")
                            + RandomStringUtils.random(6, true, true);
                    applicationInfo.setGuestNumFlag(guestNum);
                    iApplication.saveApplication(applicationInfo);

                    auctionInfo.setAutoBidNum("" + (Long.parseLong(auctionInfo.getAutoBidNum()) + 1));
                    iAuctionInfo.saveAuctionInfo(auctionInfo);
                }
            } else { //?
                //AuctionPay pi = iPayInfo.getPayInfoByOrderId(paySearchBean.getOrder());
                //iPayInfo.deletePayInfo(pi);
            }
        }
    }

    ServletActionContext.getRequest().setAttribute("userName",
            sessionContainer.getAuctionGuest().getGuestName());
    ServletActionContext.getRequest().setAttribute("auctionName", auctionInfo.getAuctionName());

    String aliveMargin = iItemMargin.getMarginVal(applicationInfo.getAccountId(),
            applicationInfo.getAuctionId(), "1");
    ServletActionContext.getRequest().setAttribute("aliveMargin", aliveMargin);
    String webMargin = iItemMargin.getMarginVal(applicationInfo.getAccountId(), applicationInfo.getAuctionId(),
            "2");
    ServletActionContext.getRequest().setAttribute("webMargin", webMargin);

    ServletActionContext.getRequest().setAttribute("auctionInfo_flag", auctionInfo);
    ServletActionContext.getRequest().setAttribute("applyInfo_flag", applicationInfo);

    ServletActionContext.getRequest().setAttribute("accountFlag", applicationInfo.getAccountId());
    ServletActionContext.getRequest().setAttribute("auctionFlag", applicationInfo.getAuctionId());
    ServletActionContext.getRequest().setAttribute("companyFlag", applicationInfo.getCompanyId());

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DATE);
    int hours = cal.get(Calendar.HOUR);
    int minutes = cal.get(Calendar.MINUTE);
    int seconds = cal.get(Calendar.SECOND);

    String monthVal = ((month < 10) ? "0" : "") + month;
    String dayVal = ((day < 10) ? "0" : "") + day;
    String hoursVal = ((hours < 10) ? "0" : "") + hours;
    String minutesVal = ((minutes < 10) ? "0" : "") + minutes;
    String secondsVal = ((seconds < 10) ? "0" : "") + seconds;

    String orderId = year + monthVal + dayVal + hoursVal + minutesVal + secondsVal;
    String orderDate = year + monthVal + dayVal;
    String orderTime = hoursVal + minutesVal + secondsVal;
    ServletActionContext.getRequest().setAttribute("orderId", orderId);
    ServletActionContext.getRequest().setAttribute("orderDate", orderDate);
    ServletActionContext.getRequest().setAttribute("orderTime", orderTime);

    return "showApply";
}

From source file:com.digitalpebble.stormcrawler.bolt.SiteMapParserBolt.java

private List<Outlink> parseSiteMap(String url, byte[] content, String contentType, Metadata parentMetadata)
        throws UnknownFormatException, IOException {

    crawlercommons.sitemaps.SiteMapParser parser = new crawlercommons.sitemaps.SiteMapParser(strictMode);

    URL sURL = new URL(url);
    AbstractSiteMap siteMap;//from  www.ja v  a 2  s . c o  m
    // let the parser guess what the mimetype is
    if (StringUtils.isBlank(contentType) || contentType.contains("octet-stream")) {
        siteMap = parser.parseSiteMap(content, sURL);
    } else {
        siteMap = parser.parseSiteMap(contentType, content, sURL);
    }

    List<Outlink> links = new ArrayList<>();

    if (siteMap.isIndex()) {
        SiteMapIndex smi = (SiteMapIndex) siteMap;
        Collection<AbstractSiteMap> subsitemaps = smi.getSitemaps();
        // keep the subsitemaps as outlinks
        // they will be fetched and parsed in the following steps
        Iterator<AbstractSiteMap> iter = subsitemaps.iterator();
        while (iter.hasNext()) {
            AbstractSiteMap asm = iter.next();
            String target = asm.getUrl().toExternalForm();

            // build an absolute URL
            try {
                target = URLUtil.resolveURL(sURL, target).toExternalForm();
            } catch (MalformedURLException e) {
                LOG.debug("MalformedURLException on {}", target);
                continue;
            }

            Date lastModified = asm.getLastModified();
            if (lastModified != null) {
                // filter based on the published date
                if (filterHoursSinceModified != -1) {
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.add(Calendar.HOUR, -filterHoursSinceModified);
                    if (lastModified.before(rightNow.getTime())) {
                        LOG.info("{} has a modified date {} which is more than {} hours old", target,
                                lastModified.toString(), filterHoursSinceModified);
                        continue;
                    }
                }
            }

            // apply filtering to outlinks
            target = urlFilters.filter(sURL, parentMetadata, target);

            if (StringUtils.isBlank(target))
                continue;

            // configure which metadata gets inherited from parent
            Metadata metadata = metadataTransfer.getMetaForOutlink(target, url, parentMetadata);
            metadata.setValue(isSitemapKey, "true");

            Outlink ol = new Outlink(target);
            ol.setMetadata(metadata);
            links.add(ol);
            LOG.debug("{} : [sitemap] {}", url, target);
        }
    }
    // sitemap files
    else {
        SiteMap sm = (SiteMap) siteMap;
        // TODO see what we can do with the LastModified info
        Collection<SiteMapURL> sitemapURLs = sm.getSiteMapUrls();
        Iterator<SiteMapURL> iter = sitemapURLs.iterator();
        while (iter.hasNext()) {
            SiteMapURL smurl = iter.next();
            double priority = smurl.getPriority();
            // TODO handle priority in metadata

            ChangeFrequency freq = smurl.getChangeFrequency();
            // TODO convert the frequency into a numerical value and handle
            // it in metadata

            String target = smurl.getUrl().toExternalForm();

            // build an absolute URL
            try {
                target = URLUtil.resolveURL(sURL, target).toExternalForm();
            } catch (MalformedURLException e) {
                LOG.debug("MalformedURLException on {}", target);
                continue;
            }

            Date lastModified = smurl.getLastModified();
            if (lastModified != null) {
                // filter based on the published date
                if (filterHoursSinceModified != -1) {
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.add(Calendar.HOUR, -filterHoursSinceModified);
                    if (lastModified.before(rightNow.getTime())) {
                        LOG.info("{} has a modified date {} which is more than {} hours old", target,
                                lastModified.toString(), filterHoursSinceModified);
                        continue;
                    }
                }
            }

            // apply filtering to outlinks
            target = urlFilters.filter(sURL, parentMetadata, target);

            if (StringUtils.isBlank(target))
                continue;

            // configure which metadata gets inherited from parent
            Metadata metadata = metadataTransfer.getMetaForOutlink(target, url, parentMetadata);
            metadata.setValue(isSitemapKey, "false");

            Outlink ol = new Outlink(target);
            ol.setMetadata(metadata);
            links.add(ol);
            LOG.debug("{} : [sitemap] {}", url, target);
        }
    }

    return links;
}

From source file:com.application.utils.FastDatePrinter.java

/**
 * <p>Returns a list of Rules given a pattern.</p>
 *
 * @return a {@code List} of Rule objects
 * @throws IllegalArgumentException if pattern is invalid
 *///from  w  w  w  . ja  v a2 s. c  om
protected List<Rule> parsePattern() {
    final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
    final List<Rule> rules = new ArrayList<Rule>();

    final String[] ERAs = symbols.getEras();
    final String[] months = symbols.getMonths();
    final String[] shortMonths = symbols.getShortMonths();
    final String[] weekdays = symbols.getWeekdays();
    final String[] shortWeekdays = symbols.getShortWeekdays();
    final String[] AmPmStrings = symbols.getAmPmStrings();

    final int length = mPattern.length();
    final int[] indexRef = new int[1];

    for (int i = 0; i < length; i++) {
        indexRef[0] = i;
        final String token = parseToken(mPattern, indexRef);
        i = indexRef[0];

        final int tokenLen = token.length();
        if (tokenLen == 0) {
            break;
        }

        Rule rule;
        final char c = token.charAt(0);

        switch (c) {
        case 'G': // era designator (text)
            rule = new TextField(Calendar.ERA, ERAs);
            break;
        case 'y': // year (number)
            if (tokenLen == 2) {
                rule = TwoDigitYearField.INSTANCE;
            } else {
                rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
            }
            break;
        case 'M': // month in year (text and number)
            if (tokenLen >= 4) {
                rule = new TextField(Calendar.MONTH, months);
            } else if (tokenLen == 3) {
                rule = new TextField(Calendar.MONTH, shortMonths);
            } else if (tokenLen == 2) {
                rule = TwoDigitMonthField.INSTANCE;
            } else {
                rule = UnpaddedMonthField.INSTANCE;
            }
            break;
        case 'd': // day in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
            break;
        case 'h': // hour in am/pm (number, 1..12)
            rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
            break;
        case 'H': // hour in day (number, 0..23)
            rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
            break;
        case 'm': // minute in hour (number)
            rule = selectNumberRule(Calendar.MINUTE, tokenLen);
            break;
        case 's': // second in minute (number)
            rule = selectNumberRule(Calendar.SECOND, tokenLen);
            break;
        case 'S': // millisecond (number)
            rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
            break;
        case 'E': // day in week (text)
            rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
            break;
        case 'D': // day in year (number)
            rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
            break;
        case 'F': // day of week in month (number)
            rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
            break;
        case 'w': // week in year (number)
            rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
            break;
        case 'W': // week in month (number)
            rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
            break;
        case 'a': // am/pm marker (text)
            rule = new TextField(Calendar.AM_PM, AmPmStrings);
            break;
        case 'k': // hour in day (1..24)
            rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
            break;
        case 'K': // hour in am/pm (0..11)
            rule = selectNumberRule(Calendar.HOUR, tokenLen);
            break;
        case 'z': // time zone (text)
            if (tokenLen >= 4) {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
            } else {
                rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
            }
            break;
        case 'Z': // time zone (value)
            if (tokenLen == 1) {
                rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
            } else {
                rule = TimeZoneNumberRule.INSTANCE_COLON;
            }
            break;
        case '\'': // literal text
            final String sub = token.substring(1);
            if (sub.length() == 1) {
                rule = new CharacterLiteral(sub.charAt(0));
            } else {
                rule = new StringLiteral(sub);
            }
            break;
        default:
            throw new IllegalArgumentException("Illegal pattern component: " + token);
        }

        rules.add(rule);
    }

    return rules;
}

From source file:me.mast3rplan.phantombot.cache.FollowersCache.java

private void updateCache(int newCount) throws Exception {
    Map<String, JSONObject> newCache = Maps.newHashMap();

    final List<JSONObject> responses = Lists.newArrayList();
    List<Thread> threads = Lists.newArrayList();

    hasFail = false;//from w w  w  .jav  a  2s  .  com

    Calendar c = Calendar.getInstance();

    c.add(Calendar.HOUR, 1);

    nextFull = c.getTime();

    for (int i = 0; i < Math.ceil(newCount / 100.0); i++) {
        final int offset = i * 100;
        Thread thread = new Thread() {
            @Override
            public void run() {
                JSONObject j = TwitchAPIv3.instance().GetChannelFollows(channel, 100, offset, true);

                if (j.getBoolean("_success")) {
                    if (j.getInt("_http") == 200) {
                        responses.add(j);

                    } else {
                        try {
                            throw new Exception("[HTTPErrorException] HTTP " + j.getInt("status") + " "
                                    + j.getString("error") + ". req=" + j.getString("_type") + " "
                                    + j.getString("_url") + " " + j.getString("_post") + "   "
                                    + (j.has("message") && !j.isNull("message")
                                            ? "message=" + j.getString("message")
                                            : "content=" + j.getString("_content")));
                        } catch (Exception e) {
                            com.gmt2001.Console.out
                                    .println("FollowersCache.updateCache>>Failed to update followers: "
                                            + e.getMessage());
                            com.gmt2001.Console.err.logStackTrace(e);
                        }
                    }
                } else {
                    try {
                        throw new Exception(
                                "[" + j.getString("_exception") + "] " + j.getString("_exceptionMessage"));
                    } catch (Exception e) {
                        if ((e.getMessage().startsWith("[SocketTimeoutException]")
                                || e.getMessage().startsWith("[IOException]")) && !hasFail) {
                            hasFail = true;

                            Calendar c = Calendar.getInstance();

                            if (lastFail.after(new Date())) {
                                numfail++;
                            } else {
                                numfail = 1;
                            }

                            c.add(Calendar.MINUTE, 1);

                            lastFail = c.getTime();

                            if (numfail >= 5) {
                                timeoutExpire = c.getTime();
                            }
                        }

                        com.gmt2001.Console.out.println(
                                "FollowersCache.updateCache>>Failed to update followers: " + e.getMessage());
                        com.gmt2001.Console.err.logStackTrace(e);
                    }
                }
            }
        };
        threads.add(thread);
        thread.start();
    }

    for (Thread thread : threads) {
        thread.join();
    }

    for (JSONObject response : responses) {
        JSONArray followers = response.getJSONArray("follows");

        if (followers.length() == 0) {
            break;
        }

        for (int j = 0; j < followers.length(); j++) {
            JSONObject follower = followers.getJSONObject(j);
            newCache.put(follower.getJSONObject("user").getString("name"), follower);
        }
    }

    List<String> followers = Lists.newArrayList();
    List<String> unfollowers = Lists.newArrayList();

    for (String key : newCache.keySet()) {
        if (cache == null || !cache.containsKey(key)) {
            followers.add(key);
        }
    }

    if (cache != null) {
        for (String key : cache.keySet()) {
            if (!newCache.containsKey(key)) {
                unfollowers.add(key);
            }
        }
    }

    this.cache = newCache;
    this.count = newCache.size();

    for (String follower : followers) {
        EventBus.instance()
                .post(new TwitchFollowEvent(follower, PhantomBot.instance().getChannel("#" + this.channel)));
    }

    for (String follower : unfollowers) {
        EventBus.instance()
                .post(new TwitchUnfollowEvent(follower, PhantomBot.instance().getChannel("#" + this.channel)));
    }

    if (firstUpdate) {
        firstUpdate = false;
        EventBus.instance()
                .post(new TwitchFollowsInitializedEvent(PhantomBot.instance().getChannel("#" + this.channel)));
    }
}

From source file:com.spvp.dal.MySqlDatabase.java

private void osvjeziHistorijuPrognozaZaGrad(Grad g, WebService ws) {

    try (Connection conn = getConnection()) {

        PreparedStatement ps = conn.prepareStatement("SELECT hp.datum dat "
                + "FROM historija_prognoze hp, gradovi_prognoze gp "
                + "WHERE hp.id = gp.prognoza_id AND gp.grad_id = ? " + "ORDER BY hp.datum DESC " + "LIMIT 1");

        ps.setInt(1, g.getIdGrada());// www.j a  v  a  2s  . c o m

        ResultSet rs = ps.executeQuery();

        if (rs.next()) {

            Calendar cal = Calendar.getInstance();
            cal.setTime(rs.getDate("dat"));
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.HOUR, 0);

            //System.out.println("Zadnji datum u bazi je bio: " + cal.getTime().toString());

            Calendar tempDate = Calendar.getInstance();
            tempDate.set(Calendar.MILLISECOND, 0);
            tempDate.set(Calendar.SECOND, 0);
            tempDate.set(Calendar.MINUTE, 0);
            tempDate.set(Calendar.HOUR, 0);

            //System.out.println("Danasnji datum je: " + tempDate.getTime().toString());

            long diff = tempDate.getTime().getTime() - cal.getTime().getTime();
            long brDana = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);

            //System.out.println("Razlika u danima je: " + brDana);

            if (brDana == 0)
                return;

            //System.out.println("Osvjezavanje zadnjeg dana u bazi...");

            this.osvjeziZadnjuPrognozuZaGrad(g, ws);

            //System.out.println("Ucitavanje novih prognoza...");

            Location l = new Location(false);
            l.setCity(g.getImeGrada());
            l.setCountry("Bosnia and Herzegovina");
            l.setCountryCode("ba");
            l.setLatitude(g.getLatitude());
            l.setLongitude(g.getLongitude());
            l.setStatus(Boolean.TRUE);

            this.ucitajPrognozeUBazu(ws.getHistorijskePodatkeByLocation(l, (int) brDana));

        } else { // Ne postoji ni jedan unos prognoze za dati grad

            //System.out.println("Zadnji datum u bazi je bio: " + rs.getDate("dat").toString());

            Location l = new Location(true);
            l.setCity(g.getImeGrada());
            l.setCountryCode("ba");
            l.setLatitude(g.getLatitude());
            l.setLongitude(g.getLongitude());
            l.setCountry("Bosnia and Herzegovina");

            this.ucitajPrognozeUBazu(ws.getHistorijskePodatkeByLocation(l, 15));

        }

    } catch (SQLException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.appeligo.alerts.KeywordAlertThread.java

private void checkAgainstEpg() throws IOException {

    final SearchResults searchResults = new SearchResults(alertManager.getLuceneIndex(), null, 10, null);
    searchResults.setSearchType(SearchType.FUTURE);
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -20); // Allowing for an abnormally long 4 hour EPG index update should be safe enough
    Date yesterday = cal.getTime();
    searchResults.setModifiedSince(yesterday);
    final IndexSearcher searcher = searchResults.newIndexSearcher();
    try {//from  w w  w .j a va  2 s.c  om
        boolean maxExceeded = executeKeywordSearch(new SearchExecutor() {

            Query luceneQuery;

            public Hits search(String lineupId, String normalizedQuery) throws ParseException, IOException {
                searchResults.setQuery(proximitize(normalizedQuery));
                searchResults.setLineup(lineupId);
                luceneQuery = searchResults.generateLuceneQuery(searcher);
                //Required to use the highlighter
                luceneQuery = searcher.rewrite(luceneQuery);
                return searcher.search(luceneQuery);
            }

            public Query getLuceneQuery() {
                return luceneQuery;
            }
        }, "keyword_alert_epg", false);
        if (maxExceeded) {
            log.fatal("Reached max consecutive exceptions for KeywordAlertThread. Exiting thread immediately.");
            return;
        }
    } finally {
        searcher.close();
    }
    if (log.isDebugEnabled())
        log.debug("KeywordAlertThread done with check of KeywordAlerts against EPG data");
}

From source file:com.rockagen.commons.util.CommUtil.java

/**
 * Return the next day's date and time 00:00:00 start date
 *
 * @param date Date/*from   w w w.  j  a va2 s  .c om*/
 * @return next day begin
 */
public static Date nextDayBegin(Date date) {
    Calendar cal = getCalendar(date);
    cal.add(Calendar.DATE, 1); // next day's am O0:00:00
    cal.set(Calendar.AM_PM, Calendar.AM);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    return cal.getTime();
}