Example usage for org.joda.time DateTime getMillis

List of usage examples for org.joda.time DateTime getMillis

Introduction

In this page you can find the example usage for org.joda.time DateTime getMillis.

Prototype

public long getMillis() 

Source Link

Document

Gets the milliseconds of the datetime instant from the Java epoch of 1970-01-01T00:00:00Z.

Usage

From source file:com.act.lcms.v2.fullindex.Searcher.java

License:Open Source License

/**
 * Searches an LCMS index for all (time, m/z, intensity) triples within some time and m/z ranges.
 *
 * Note that this method is very much a first-draft/WIP.  There are many opportunities for optimization and
 * improvement here, but this works as an initial attempt.  This method is littered with TODOs, which once TODone
 * should make this a near optimal method of searching through LCMS readings.
 *
 * @param mzRange The range of m/z values for which to search.
 * @param timeRange The time range for which to search.
 * @return A list of (time, m/z, intensity) triples that fall within the specified ranges.
 * @throws RocksDBException//  www .  ja va  2s.co m
 * @throws ClassNotFoundException
 * @throws IOException
 */
public List<TMzI> searchIndexInRange(Pair<Double, Double> mzRange, Pair<Double, Double> timeRange)
        throws RocksDBException, ClassNotFoundException, IOException {
    // TODO: gracefully handle the case when only range is specified.
    // TODO: consider producing some sort of query plan structure that can be used for optimization/explanation.

    DateTime start = DateTime.now();
    /* Demote the time range to floats, as we know that that's how we stored times in the DB.  This tight coupling would
     * normally be a bad thing, but given that this class is joined at the hip with Builder necessarily, it
     * doesn't seem like a terrible thing at the moment. */
    Pair<Float, Float> tRangeF = // My kingdom for a functor!
            Pair.of(timeRange.getLeft().floatValue(), timeRange.getRight().floatValue());

    LOGGER.info("Running search for %.6f <= t <= %.6f, %.6f <= m/z <= %.6f", tRangeF.getLeft(),
            tRangeF.getRight(), mzRange.getLeft(), mzRange.getRight());

    // TODO: short circuit these filters.  The first failure after success => no more possible hits.
    List<Float> timesInRange = timepointsInRange(tRangeF);

    byte[][] timeIndexBytes = extractValueBytes(ColumnFamilies.TIMEPOINT_TO_TRIPLES, timesInRange, Float.BYTES,
            ByteBuffer::putFloat);
    // TODO: bail if all the timeIndexBytes lengths are zero.

    List<MZWindow> mzWindowsInRange = mzWindowsInRange(mzRange);

    byte[][] mzIndexBytes = extractValueBytes(ColumnFamilies.WINDOW_ID_TO_TRIPLES, mzWindowsInRange,
            Integer.BYTES, (buff, mz) -> buff.putInt(mz.getIndex()));
    // TODO: bail if all the mzIndexBytes are zero.

    /* TODO: if the number of entries in one range is significantly smaller than the other (like an order of magnitude
     * or more, skip extraction of the other set of ids and just filter at the end.  This will be especially helpful
     * when the number of ids in the m/z domain is small, as each time point will probably have >10k ids. */

    LOGGER.info("Found/loaded %d matching time ranges, %d matching m/z ranges", timesInRange.size(),
            mzWindowsInRange.size());

    // TODO: there is no need to union the time indices since they are necessarily distinct.  Just concatenate instead.
    Set<Long> unionTimeIds = unionIdBuffers(timeIndexBytes);
    Set<Long> unionMzIds = unionIdBuffers(mzIndexBytes);
    // TODO: handle the case where one of the sets is empty specially.  Either keep all in the other set or drop all.
    // TODO: we might be able to do this faster by intersecting two sorted lists.
    Set<Long> intersectionIds = new HashSet<>(unionTimeIds);
    /* TODO: this is effectively a hash join, which isn't optimal for sets of wildly different cardinalities.
     * Consider using sort-merge join instead, which will reduce the object overhead (by a lot) and allow us to pass
     * over the union of the ids from each range just once when joining them.  Additionally, just skip this whole step
     * and filter at the end if one of the set's sizes is less than 1k or so and the other is large. */
    intersectionIds.retainAll(unionMzIds);
    LOGGER.info("Id intersection results: t = %d, mz = %d, t ^ mz = %d", unionTimeIds.size(), unionMzIds.size(),
            intersectionIds.size());

    List<Long> idsToFetch = new ArrayList<>(intersectionIds);
    Collections.sort(idsToFetch); // Sort ids so we retrieve them in an order that exploits index locality.

    LOGGER.info("Collecting TMzI triples");
    // Collect all the triples for the ids we extracted.
    // TODO: don't manifest all the bytes: just create a stream of results from the cursor to reduce memory overhead.
    List<TMzI> results = new ArrayList<>(idsToFetch.size());
    byte[][] resultBytes = extractValueBytes(ColumnFamilies.ID_TO_TRIPLE, idsToFetch, Long.BYTES,
            ByteBuffer::putLong);
    for (byte[] tmziBytes : resultBytes) {
        results.add(TMzI.readNextFromByteBuffer(ByteBuffer.wrap(tmziBytes)));
    }

    // TODO: do this filtering inline with the extraction.  We shouldn't have to load all the triples before filtering.
    LOGGER.info("Performing final filtering");
    int preFilterTMzICount = results.size();
    results = results.stream()
            .filter(tmzi -> tmzi.getTime() >= tRangeF.getLeft() && tmzi.getTime() <= tRangeF.getRight()
                    && tmzi.getMz() >= mzRange.getLeft() && tmzi.getMz() <= mzRange.getRight())
            .collect(Collectors.toList());
    LOGGER.info("Precise filtering results: %d -> %d", preFilterTMzICount, results.size());

    DateTime end = DateTime.now();
    LOGGER.info("Search completed in %dms", end.getMillis() - start.getMillis());

    // TODO: return a stream instead that can load the triples lazily.
    return results;
}

From source file:com.addthis.hydra.data.query.op.OpDateFormat.java

License:Apache License

@Override
public Bundle rowOp(Bundle row) {
    BundleColumnBinder binder = getSourceColumnBinder(row);
    // concatenate columns
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < incols.length; i++) {
        String s = ValueUtil.asNativeString(binder.getColumn(row, incols[i]));
        if (s != null) {
            buf.append(s);//w ww. j  a  v  a 2 s  .  co  m
        }
    }
    // convert input
    String sbuf = buf.toString();
    DateTime dt = null;
    if (fromMillis > 0) {
        dt = new DateTime(Integer.parseInt(sbuf, fromMillis));
    } else {
        dt = inFormat.parseDateTime(sbuf);
    }
    // convert and output
    ValueObject out = null;
    if (toMillis > 0) {
        out = ValueFactory.create(dt.getMillis());
    } else {
        out = ValueFactory.create(outFormat.print(dt));
    }
    if (outcol >= row.getCount()) {
        binder.appendColumn(row, out);
    } else {
        binder.setColumn(row, outcol, out);
    }
    return row;
}

From source file:com.addthis.hydra.kafka.consumer.FetchTask.java

License:Apache License

private static void consume(AtomicBoolean running, String topic, PartitionMetadata partition,
        PageDB<SimpleMark> markDb, DateTime startTime, LinkedBlockingQueue<MessageWrapper> messageQueue,
        ConcurrentMap<String, Long> sourceOffsets) {
    SimpleConsumer consumer = null;/*from   w ww. ja v a 2 s  .co  m*/
    try {
        if (!running.get()) {
            return;
        }
        // initialize consumer and offsets
        int partitionId = partition.partitionId();
        Broker broker = partition.leader();
        consumer = new SimpleConsumer(broker.host(), broker.port(), timeout, fetchSize,
                "kafka-source-consumer");
        String sourceIdentifier = topic + "-" + partitionId;
        final long endOffset = ConsumerUtils.latestOffsetAvailable(consumer, topic, partitionId,
                offsetAttempts);
        final SimpleMark previousMark = markDb.get(new DBKey(0, sourceIdentifier));
        long startOffset = -1;
        if (previousMark != null) {
            startOffset = previousMark.getIndex();
        } else if (startTime != null) {
            startOffset = ConsumerUtils.getOffsetBefore(consumer, topic, partitionId, startTime.getMillis(),
                    offsetAttempts);
            log.info("no previous mark for host: {}, partition: {}, starting from offset: {}, closest to: {}",
                    consumer.host(), partitionId, startOffset, startTime);
        }
        if (startOffset == -1) {
            log.info(
                    "no previous mark for host: {}:{}, topic: {}, partition: {}, no offsets available for "
                            + "startTime: {}, starting from earliest",
                    consumer.host(), consumer.port(), topic, partitionId, startTime);
            startOffset = ConsumerUtils.earliestOffsetAvailable(consumer, topic, partitionId, offsetAttempts);
        } else if (startOffset > endOffset) {
            log.warn(
                    "initial offset for: {}:{}, topic: {}, partition: {} is beyond latest, {} > {}; kafka data "
                            + "was either wiped (resetting offsets) or corrupted - skipping "
                            + "ahead to offset {} to recover consuming from latest",
                    consumer.host(), consumer.port(), topic, partitionId, startOffset, endOffset, endOffset);
            startOffset = endOffset;
            // Offsets are normally updated when the bundles are consumed from source.next() - since we wont
            // be fetching any bundles to be consumed, we need to update offset map (that gets persisted to marks)
            // here. The sourceOffsets map probably *should not* be modified anywhere else outside of next().
            sourceOffsets.put(sourceIdentifier, startOffset);
        }
        log.info(
                "started consuming topic: {}, partition: {}, from broker: {}:{}, at offset: {}, until offset: {}",
                topic, partitionId, consumer.host(), consumer.port(), startOffset, endOffset);
        // fetch from broker, add to queue (decoder threads will process queue in parallel)
        long offset = startOffset;
        while (running.get() && (offset < endOffset)) {
            FetchRequest request = new FetchRequestBuilder().addFetch(topic, partitionId, offset, fetchSize)
                    .build();
            FetchResponse response = consumer.fetch(request);
            short errorCode = response.errorCode(topic, partitionId);
            ByteBufferMessageSet messageSet = null;
            if (errorCode == ErrorMapping.NoError()) {
                messageSet = response.messageSet(topic, partitionId);
                // clamp out-of-range offsets
            } else if (errorCode == ErrorMapping.OffsetOutOfRangeCode()) {
                long earliestOffset = ConsumerUtils.earliestOffsetAvailable(consumer, topic, partitionId,
                        offsetAttempts);
                if (offset < earliestOffset) {
                    log.error(
                            "forwarding invalid early offset: {}:{}, topic: {}, partition: {}, "
                                    + "from offset: {}, to: {}",
                            consumer.host(), consumer.port(), topic, partition, offset, earliestOffset);
                    offset = earliestOffset;
                    // offset exceptions should only be thrown when offset < earliest, so this case shouldnt ever happen
                } else {
                    long latestOffset = ConsumerUtils.latestOffsetAvailable(consumer, topic, partitionId,
                            offsetAttempts);
                    log.error(
                            "rewinding invalid future offset: {}:{}, topic: {}, partition: {}, "
                                    + "from offset: {}, to: {}",
                            consumer.host(), consumer.port(), topic, partition, offset, latestOffset);
                    offset = latestOffset;
                }
                // partition was moved/rebalanced in background, so this consumer's host no longer has data
            } else if (errorCode == ErrorMapping.NotLeaderForPartitionCode()
                    || errorCode == ErrorMapping.UnknownTopicOrPartitionCode()) {
                Broker newLeader = ConsumerUtils.getNewLeader(consumer, topic, partitionId);
                log.warn(
                        "current partition was moved off of current host while consuming, reconnecting to new "
                                + "leader; topic: {}-{}, old: {}:{}, new leader: {}:{}",
                        topic, partitionId, consumer.host(), consumer.port(), newLeader.host(),
                        newLeader.port());
                consumer.close();
                consumer = new SimpleConsumer(newLeader.host(), newLeader.port(), timeout, fetchSize,
                        "kafka-source-consumer");
                // any other error
            } else if (errorCode != ErrorMapping.NoError()) {
                log.error("failed to consume from broker: {}:{}, topic: {}, partition: {}, offset: {}",
                        consumer.host(), consumer.port(), topic, partitionId, offset);
                throw new RuntimeException(ErrorMapping.exceptionFor(errorCode));
            }

            if (messageSet != null) {
                for (MessageAndOffset messageAndOffset : messageSet) {
                    // Fetch requests sometimes return bundles that come before the requested offset (presumably
                    // due to batching).  Ignore those early bundles until reaching the desired offset.
                    if (messageAndOffset.offset() >= startOffset) {
                        putWhileRunning(messageQueue, new MessageWrapper(messageAndOffset, consumer.host(),
                                topic, partitionId, sourceIdentifier), running);
                    }
                    offset = messageAndOffset.nextOffset();
                }
            }
        }
        log.info("finished consuming topic: {}, partition: {}, from broker: {}:{}, at offset: {}", topic,
                partitionId, consumer.host(), consumer.port(), offset);
    } catch (BenignKafkaException ignored) {
    } catch (Exception e) {
        log.error("kafka consume thread failed: ", e);
    } finally {
        putWhileRunning(messageQueue, MessageWrapper.messageQueueEndMarker, running);
        if (consumer != null) {
            consumer.close();
        }
    }
}

From source file:com.agenmate.lollipop.addedit.AddEditFragment.java

License:Apache License

private long getDueDate() {
    if (timePickerLayout.getDueDateStatus() == TimePickerLayout.NO_DUE_DATE)
        return 0;
    else {/*from w w w . j av a  2s.co  m*/
        long time = timePickerLayout.getTimeFromPicker().getMillis() * 1000;
        DateTime now = new DateTime().withSecondOfMinute(0).withMillisOfSecond(0).plusMinutes(1);
        if (now.getMillis() * 1000 < time)
            return time;
        else {
            // TODO turn off alarm
            return -1;
        }
    }
}

From source file:com.aionemu.gameserver.dataholders.InstanceCooltimeData.java

License:Open Source License

public long getInstanceEntranceCooltime(Player player, int worldId) {
    int instanceCooldownRate = InstanceService.getInstanceRate(player, worldId);
    long instanceCoolTime = 0;
    InstanceCooltime clt = getInstanceCooltimeByWorldId(worldId);
    if (clt != null) {
        instanceCoolTime = clt.getEntCoolTime();
        if (clt.getCoolTimeType().isDaily()) {
            DateTime now = DateTime.now();
            DateTime repeatDate = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(),
                    (int) (instanceCoolTime / 100), 0, 0);
            if (now.isAfter(repeatDate)) {
                repeatDate = repeatDate.plusHours(24);
                instanceCoolTime = repeatDate.getMillis();
            } else {
                instanceCoolTime = repeatDate.getMillis();
            }// w  ww .jav a  2  s  .co  m
        } else if (clt.getCoolTimeType().isWeekly()) {
            String[] days = clt.getTypeValue().split(",");
            instanceCoolTime = getUpdateHours(days, (int) (instanceCoolTime / 100));
        } else {
            instanceCoolTime = System.currentTimeMillis() + (instanceCoolTime * 60 * 1000);
        }
    }
    if (instanceCooldownRate != 1) {
        instanceCoolTime = System.currentTimeMillis()
                + ((instanceCoolTime - System.currentTimeMillis()) / instanceCooldownRate);
    }
    return instanceCoolTime;
}

From source file:com.aionemu.gameserver.dataholders.InstanceCooltimeData.java

License:Open Source License

private long getUpdateHours(String[] days, int hour) {
    DateTime now = DateTime.now();//  w  ww.  j  a  v  a2 s. c o m
    DateTime repeatDate = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), hour, 0, 0);
    int curentDay = now.getDayOfWeek();
    for (String name : days) {
        int day = getDay(name);
        if (day < curentDay) {
            continue;
        }
        if (day == curentDay) {
            if (now.isBefore(repeatDate)) {
                return repeatDate.getMillis();
            }
        } else {
            repeatDate = repeatDate.plusDays(day - curentDay);
            return repeatDate.getMillis();
        }
    }
    return repeatDate.plusDays((7 - curentDay) + getDay(days[0])).getMillis();
}

From source file:com.aionemu.gameserver.model.gameobjects.UseableItemObject.java

License:Open Source License

@Override
public void onUse(final Player player) {
    if (!usingPlayer.compareAndSet(null, player)) {
        // The same player is using, return. It might be double-click
        if (usingPlayer.compareAndSet(player, player)) {
            return;
        }/*w  ww.jav  a 2 s .  c om*/
        PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_OCCUPIED_BY_OTHER);
        return;
    }

    boolean isOwner = getOwnerHouse().getOwnerId() == player.getObjectId();
    if (getObjectTemplate().isOwnerOnly() && !isOwner) {
        warnAndRelease(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_IS_ONLY_FOR_OWNER_VALID);
        return;
    }

    boolean cdExpired = player.getHouseObjectCooldownList().isCanUseObject(getObjectId());
    if (!cdExpired) {
        if (getObjectTemplate().getCd() != null && getObjectTemplate().getCd() != 0) {
            warnAndRelease(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_CANNOT_USE_FLOWERPOT_COOLTIME);
            return;
        }
        if (getObjectTemplate().isOwnerOnly() && isOwner) {
            warnAndRelease(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_CANT_USE_PER_DAY);
            return;
        }
    }

    final UseItemAction action = getObjectTemplate().getAction();
    if (action == null) {
        // Some objects do not have actions; they are test items now
        warnAndRelease(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_ALL_CANT_USE);
        return;
    }

    if (getObjectTemplate().getPlacementLimit() == LimitType.COOKING) {
        // Check if player already has an item
        if (player.getInventory().getItemCountByItemId(action.getRewardId()) > 0) {
            int nameId = DataManager.ITEM_DATA.getItemTemplate(action.getRewardId()).getNameId();
            SM_SYSTEM_MESSAGE msg = SM_SYSTEM_MESSAGE.STR_MSG_CANNOT_USE_ALREADY_HAVE_REWARD_ITEM(nameId,
                    getObjectTemplate().getNameId());
            warnAndRelease(player, msg);
            return;
        }
    }

    final Integer useCount = getObjectTemplate().getUseCount();
    int currentUseCount = 0;

    if (useCount != null) {
        // Counter is for both, but could be made custom from configs
        currentUseCount = getOwnerUsedCount() + getVisitorUsedCount();
        if (currentUseCount >= useCount && !isOwner || currentUseCount > useCount && isOwner) {
            // if expiration is set then final reward has to be given for owner only
            // due to inventory full. If inventory was not full, the object had to be despawned, so
            // we wouldn't reach this check.
            if (!mustGiveLastReward || !isOwner) {
                warnAndRelease(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_ACHIEVE_USE_COUNT);
                return;
            }
        }
    }

    final Integer requiredItem = getObjectTemplate().getRequiredItem();

    if (mustGiveLastReward && !isOwner) {
        // Expired, waiting owner
        int descId = DataManager.ITEM_DATA.getItemTemplate(requiredItem).getNameId();
        warnAndRelease(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_DELETE_EXPIRE_TIME(descId));
        return;
    } else if (requiredItem != null) {
        int checkType = action.getCheckType();
        if (checkType == 1) { // equip item needed
            List<Item> items = player.getEquipment().getEquippedItemsByItemId(requiredItem);
            if (items.size() == 0) {
                int descId = DataManager.ITEM_DATA.getItemTemplate(requiredItem).getNameId();
                warnAndRelease(player,
                        SM_SYSTEM_MESSAGE.STR_MSG_CANT_USE_HOUSE_OBJECT_ITEM_EQUIP(new DescriptionId(descId)));
                return;
            }
        } else if (player.getInventory().getItemCountByItemId(requiredItem) < action.getRemoveCount()) {
            int descId = DataManager.ITEM_DATA.getItemTemplate(requiredItem).getNameId();
            warnAndRelease(player,
                    SM_SYSTEM_MESSAGE.STR_MSG_CANT_USE_HOUSE_OBJECT_ITEM_CHECK(new DescriptionId(descId)));
            return;
        }
    }

    if (player.getInventory().isFull()) {
        warnAndRelease(player, SM_SYSTEM_MESSAGE.STR_WAREHOUSE_TOO_MANY_ITEMS_INVENTORY);
        return;
    }

    final int delay = getObjectTemplate().getDelay();
    final int ownerId = getOwnerHouse().getOwnerId();
    final int usedCount = useCount == null ? 0 : currentUseCount + 1;
    final ItemUseObserver observer = new ItemUseObserver() {
        @Override
        public void abort() {
            PacketSendUtility.sendPacket(player, new SM_USE_OBJECT(player.getObjectId(), getObjectId(), 0, 9));
            player.getObserveController().removeObserver(this);
            warnAndRelease(player, null);
        }

        @Override
        public void itemused(Item item) {
            abort();
        }
    };

    player.getObserveController().attach(observer);
    PacketSendUtility.sendPacket(player,
            SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_USE(getObjectTemplate().getNameId()));
    PacketSendUtility.sendPacket(player, new SM_USE_OBJECT(player.getObjectId(), getObjectId(), delay, 8));
    player.getController().addTask(TaskId.HOUSE_OBJECT_USE,
            ThreadPoolManager.getInstance().schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        PacketSendUtility.sendPacket(player,
                                new SM_USE_OBJECT(player.getObjectId(), getObjectId(), 0, 9));
                        if (action.getRemoveCount() != null && action.getRemoveCount() != 0) {
                            player.getInventory().decreaseByItemId(requiredItem, action.getRemoveCount());
                        }

                        UseableItemObject myself = UseableItemObject.this;
                        int rewardId = 0;
                        boolean delete = false;

                        if (useCount != null) {
                            if (action.getFinalRewardId() != null && useCount + 1 == usedCount) {
                                // visitors do not get final rewards
                                rewardId = action.getFinalRewardId();
                                ItemService.addItem(player, rewardId, 1);
                                delete = true;
                            } else if (action.getRewardId() != null) {
                                rewardId = action.getRewardId();
                                ItemService.addItem(player, rewardId, 1);
                                if (useCount == usedCount) {
                                    PacketSendUtility.sendPacket(player,
                                            SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_FLOWERPOT_GOAL(
                                                    myself.getObjectTemplate().getNameId()));
                                    if (action.getFinalRewardId() == null) {
                                        delete = true;
                                    } else {
                                        myself.setMustGiveLastReward(true);
                                        myself.setExpireTime((int) (System.currentTimeMillis() / 1000));
                                        myself.setPersistentState(PersistentState.UPDATE_REQUIRED);
                                    }
                                }
                            }
                        } else if (action.getRewardId() != null) {
                            rewardId = action.getRewardId();
                            ItemService.addItem(player, rewardId, 1);
                        }
                        if (usedCount > 0) {
                            if (!delete) {
                                if (player.getObjectId() == ownerId) {
                                    myself.incrementOwnerUsedCount();
                                } else {
                                    myself.incrementVisitorUsedCount();
                                }
                            }
                            PacketSendUtility.broadcastPacket(player,
                                    new SM_OBJECT_USE_UPDATE(player.getObjectId(), ownerId, usedCount, myself),
                                    true);
                        }
                        if (rewardId > 0) {
                            int rewardNameId = DataManager.ITEM_DATA.getItemTemplate(rewardId).getNameId();
                            PacketSendUtility.sendPacket(player,
                                    SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_REWARD_ITEM(
                                            myself.getObjectTemplate().getNameId(), rewardNameId));
                        }
                        if (delete) {
                            selfDestroy(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_DELETE_USE_COUNT_FINAL(
                                    getObjectTemplate().getNameId()));
                        } else {
                            Integer cd = myself.getObjectTemplate().getCd();
                            DateTime repeatDate;
                            if (cd == null || cd == 0) {
                                // use once per day
                                DateTime tomorrow = DateTime.now().plusDays(1);
                                repeatDate = new DateTime(tomorrow.getYear(), tomorrow.getMonthOfYear(),
                                        tomorrow.getDayOfMonth(), 0, 0, 0);
                                cd = (int) (repeatDate.getMillis() - DateTime.now().getMillis()) / 1000;
                            }
                            player.getHouseObjectCooldownList().addHouseObjectCooldown(myself.getObjectId(),
                                    cd);
                        }
                    } finally {
                        player.getObserveController().removeObserver(observer);
                        warnAndRelease(player, null);
                    }
                }
            }, delay));
}

From source file:com.aionemu.gameserver.model.house.MaintenanceTask.java

License:Open Source License

@Override
protected void executeTask() {
    if (!HousingConfig.ENABLE_HOUSE_PAY) {
        return;/*from  ww  w .  j a v a  2 s  . c  om*/
    }

    // Get times based on configuration values
    DateTime now = new DateTime();
    DateTime previousRun = now.minus(getPeriod()); // usually week ago
    DateTime beforePreviousRun = previousRun.minus(getPeriod()); // usually two weeks ago

    for (House house : maintainedHouses) {
        if (house.isFeePaid()) {
            continue; // player already paid, don't check
        }
        long payTime = house.getNextPay().getTime();
        long impoundTime = 0;
        int warnCount = 0;

        PlayerCommonData pcd = null;
        Player player = World.getInstance().findPlayer(house.getOwnerId());
        if (player == null) {
            pcd = DAOManager.getDAO(PlayerDAO.class).loadPlayerCommonData(house.getOwnerId());
        } else {
            pcd = player.getCommonData();
        }

        if (pcd == null) {
            // player doesn't exist already for some reasons
            log.warn("House " + house.getAddress().getId()
                    + " had player assigned but no player exists. Auctioned.");
            putHouseToAuction(house, null);
            continue;
        }

        if (payTime <= beforePreviousRun.getMillis()) {
            DateTime plusDay = beforePreviousRun.minusDays(1);
            if (payTime <= plusDay.getMillis()) {
                // player didn't pay after the second warning and one day passed
                impoundTime = now.getMillis();
                warnCount = 3;
                putHouseToAuction(house, pcd);
            } else {
                impoundTime = now.plusDays(1).getMillis();
                warnCount = 2;
            }
        } else if (payTime <= previousRun.getMillis()) {
            // player did't pay 1 period
            impoundTime = now.plus(getPeriod()).plusDays(1).getMillis();
            warnCount = 1;
        } else {
            continue; // should not happen
        }

        if (pcd.isOnline()) {
            if (warnCount == 3) {
                PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_SEQUESTRATE);
            } else {
                PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OVERDUE);
            }
        }
        MailFormatter.sendHouseMaintenanceMail(house, warnCount, impoundTime);
    }
}

From source file:com.aionemu.gameserver.services.LoginEventService.java

License:Open Source License

private static Timestamp autoAddTimeColumn() {
    DateTime now = DateTime.now();/* w ww  .j  ava  2  s  . co m*/
    DateTime repeatDate = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 9, 0, 0);
    if (now.isAfter(repeatDate)) {
        repeatDate = repeatDate.plusHours(24);
    }
    return new Timestamp(repeatDate.getMillis());
}

From source file:com.aionemu.gameserver.services.LoginEventService.java

License:Open Source License

private static Timestamp countNextRepeatTime() {
    DateTime now = DateTime.now();/*from  ww  w  .j ava  2s .  co m*/
    DateTime repeatDate = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 9, 0, 0);
    if (now.isAfter(repeatDate)) {
        repeatDate = repeatDate.plusHours(24);
    }
    return new Timestamp(repeatDate.getMillis());
}