Example usage for org.joda.time DateTime minus

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

Introduction

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

Prototype

public DateTime minus(ReadablePeriod period) 

Source Link

Document

Returns a copy of this datetime with the specified period taken away.

Usage

From source file:be.fedict.trust.ocsp.OcspTrustLinker.java

License:Open Source License

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    URI ocspUri = getOcspUri(childCertificate);
    if (null == ocspUri) {
        return TrustLinkerResult.UNDECIDED;
    }//from   w  ww  .  ja v a  2 s .com
    LOG.debug("OCSP URI: " + ocspUri);

    OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate,
            validationDate);
    if (null == ocspResp) {
        LOG.debug("OCSP response not found");
        return TrustLinkerResult.UNDECIDED;
    }

    int ocspRespStatus = ocspResp.getStatus();
    if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) {
        LOG.debug("OCSP response status: " + ocspRespStatus);
        return TrustLinkerResult.UNDECIDED;
    }

    Object responseObject = ocspResp.getResponseObject();
    BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject;

    X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts();
    for (X509CertificateHolder responseCertificate : responseCertificates) {
        LOG.debug("OCSP response cert: " + responseCertificate.getSubject());
        LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer());
    }

    algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate);

    if (0 == responseCertificates.length) {
        /*
         * This means that the OCSP response has been signed by the issuing
         * CA itself.
         */
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey());
        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
    } else {
        /*
         * We're dealing with a dedicated authorized OCSP Responder
         * certificate, or of course with a CA that issues the OCSP
         * Responses itself.
         */

        X509CertificateHolder ocspResponderCertificate = responseCertificates[0];
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate);

        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP Responser response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
        if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) {
            // check certificate signature algorithm
            algorithmPolicy.checkSignatureAlgorithm(
                    ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate);

            X509Certificate issuingCaCertificate;
            if (responseCertificates.length < 2) {
                // so the OCSP certificate chain only contains a single
                // entry
                LOG.debug("OCSP responder complete certificate chain missing");
                /*
                 * Here we assume that the OCSP Responder is directly signed
                 * by the CA.
                 */
                issuingCaCertificate = certificate;
            } else {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                issuingCaCertificate = (X509Certificate) certificateFactory
                        .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded()));
                /*
                 * Is next check really required?
                 */
                if (false == certificate.equals(issuingCaCertificate)) {
                    LOG.debug("OCSP responder certificate not issued by CA");
                    return TrustLinkerResult.UNDECIDED;
                }
            }
            // check certificate signature
            algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate);

            PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker();
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory
                    .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded()));
            LOG.debug("OCSP Responder public key fingerprint: "
                    + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded()));
            publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate,
                    validationDate, revocationData, algorithmPolicy);
            if (null == x509OcspResponderCertificate
                    .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) {
                LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck");
                /*
                 * TODO: perform CRL validation on the OCSP Responder
                 * certificate. On the other hand, do we really want to
                 * check the checker?
                 */
                return TrustLinkerResult.UNDECIDED;
            }
            List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage();
            if (null == extendedKeyUsage) {
                LOG.debug("OCSP Responder certificate has no extended key usage extension");
                return TrustLinkerResult.UNDECIDED;
            }
            if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage");
                return TrustLinkerResult.UNDECIDED;
            }
        } else {
            LOG.debug("OCSP Responder certificate equals the CA certificate");
            // and the CA certificate is already trusted at this point
        }
    }

    DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
    CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1),
            new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber());

    SingleResp[] singleResps = basicOCSPResp.getResponses();
    for (SingleResp singleResp : singleResps) {
        CertificateID responseCertificateId = singleResp.getCertID();
        if (false == certificateId.equals(responseCertificateId)) {
            continue;
        }
        DateTime thisUpdate = new DateTime(singleResp.getThisUpdate());
        DateTime nextUpdate;
        if (null != singleResp.getNextUpdate()) {
            nextUpdate = new DateTime(singleResp.getNextUpdate());
        } else {
            LOG.debug("no OCSP nextUpdate");
            nextUpdate = thisUpdate;
        }
        LOG.debug("OCSP thisUpdate: " + thisUpdate);
        LOG.debug("(OCSP) nextUpdate: " + nextUpdate);
        DateTime beginValidity = thisUpdate.minus(this.freshnessInterval);
        DateTime endValidity = nextUpdate.plus(this.freshnessInterval);
        DateTime validationDateTime = new DateTime(validationDate);
        if (validationDateTime.isBefore(beginValidity)) {
            LOG.warn("OCSP response not yet valid");
            continue;
        }
        if (validationDateTime.isAfter(endValidity)) {
            LOG.warn("OCSP response expired");
            continue;
        }
        if (null == singleResp.getCertStatus()) {
            LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal());
            addRevocationData(revocationData, ocspResp, ocspUri);
            return TrustLinkerResult.TRUSTED;
        } else {
            LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName());
            if (singleResp.getCertStatus() instanceof RevokedStatus) {
                LOG.debug("OCSP status revoked");
            }
            addRevocationData(revocationData, ocspResp, ocspUri);
            throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
                    "certificate revoked by OCSP");
        }
    }

    LOG.debug("no matching OCSP response entry");
    return TrustLinkerResult.UNDECIDED;
}

From source file:br.com.hyperclass.parking.domain.parking.ParkingTimeValueCalculatorService.java

License:Open Source License

public double calculateParkingTime(final DateTime initialTime, final DateTime finalTime,
        final double valueOfTypeOfVehicle) throws ParkingException {
    final DateTime parkingTime = finalTime.minus(initialTime.getMillis());
    if (checkParkingTime(parkingTime)) {
        return calculate(valueOfTypeOfVehicle);
    }/* www . j a v a2  s. c om*/
    if (next == null) {
        throw new FailedToPerformTheCalculationException();
    }
    return next.calculateParkingTime(initialTime, finalTime, valueOfTypeOfVehicle);
}

From source file:colossal.pipe.BaseOptions.java

License:Apache License

public Interval getInterval() {
    if (time != null) {
        String[] parts = time.split("/");
        if (parts.length != 2) {
            System.err.println("Can't parse time: use a format like 2007-03-01T13:00:00Z/2007-03-01T14:00:00Z");
        } else {//from www .j  av  a 2  s. c om
            DateTime s = parseDateTime(parts[0]);
            DateTime e = parseDateTime(parts[1]);
            return new Interval(s, e);
        }
    } else if (start != null) {
        DateTime s = parseDateTime(start);
        if (end != null) {
            DateTime e = parseDateTime(end);
            return new Interval(s, e);
        } else if (duration != null) {
            Period p = parseDuration();
            return new Interval(s, p);
        }
    } else if (end != null && duration != null) {
        DateTime e = parseDateTime(end);
        Period p = parseDuration();
        return new Interval(e.minus(p), p);
    }
    return null;
}

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   w  w  w. j  av a2  s . c  o m
    }

    // 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.alfaariss.oa.util.saml2.SAML2ConditionsWindow.java

License:Open Source License

/**
 * Verifies if the current time is within the supplied time window.
 * <br>/*w w  w .  j  av a2  s  .co  m*/
 * The time window is extended with configured offsets.
 * 
 * @param dtNB Not Before condition or NULL if not available.
 * @param dtNOA Not On Or After condition or NULL if not available.
 * @return TRUE if the current datetime is within the window.
 */
public boolean canAccept(DateTime dtNB, DateTime dtNOA) {
    DateTime dtNow = new DateTime();

    if (dtNB != null) {
        DateTime dtNotBefore = dtNB.minus(_lBeforeOffset);
        if (dtNow.getMillis() < dtNotBefore.getMillis()) {
            StringBuffer sbDebug = new StringBuffer("Condition time stamp(s) incorrect; Current time (");
            sbDebug.append(dtNow);
            sbDebug.append(") is before the Not Before time: ");
            sbDebug.append(dtNB);
            _logger.debug(sbDebug.toString());
            return false;
        }
    }

    if (dtNOA != null) {
        DateTime dtNotOnOrAfter = dtNOA.plus(_lAfterOffset);
        if (dtNow.getMillis() >= dtNotOnOrAfter.getMillis()) {
            StringBuffer sbDebug = new StringBuffer("Condition time stamp(s) incorrect; Current time (");
            sbDebug.append(dtNow);
            sbDebug.append(") is on or after the Not On Or After time: ");
            sbDebug.append(dtNOA);
            _logger.debug(sbDebug.toString());
            return false;
        }
    }

    return true;
}

From source file:com.alliander.osgp.adapter.protocol.iec61850.infra.networking.services.Iec61850DeviceConnectionService.java

License:Open Source License

public synchronized void connect(final String ipAddress, final String deviceIdentification, final IED ied,
        final LogicalDevice logicalDevice) throws ConnectionFailureException {
    LOGGER.info("Trying to find connection in cache for deviceIdentification: {}", deviceIdentification);

    if (this.testIfConnectionIsCachedAndAlive(deviceIdentification, ied, logicalDevice)) {
        return;//  w ww. j ava 2  s  .c  om
    }
    final InetAddress inetAddress = this.convertIpAddress(ipAddress);
    if (inetAddress == null) {
        return;
    }
    // Connect to obtain ClientAssociation and ServerModel.
    LOGGER.info("Trying to connect to deviceIdentification: {} at IP address {} using response time-out: {}",
            deviceIdentification, ipAddress, this.responseTimeout);
    final DateTime startTime = DateTime.now();

    // Create instance of appropriate event listener.
    Iec61850ClientBaseEventListener eventListener = null;
    try {
        eventListener = Iec61850ClientEventListenerFactory.getInstance().getEventListener(ied,
                deviceIdentification, this.deviceManagementService);
    } catch (final ProtocolAdapterException e) {
        LOGGER.error(
                "ProtocolAdapterException: no Iec61850ClientBaseEventListener instance could be contructed, continue without event listener for deviceIdentification: "
                        + deviceIdentification,
                e);
    }

    // For now, the port numbers are defined in the property file. If in
    // the future a database is added to this component, the port
    // numbers for particular devices should be saved using the
    // database.
    int port = 102;
    if (IED.FLEX_OVL.equals(ied)) {
        port = this.iec61850SsldPortServer;
    } else if (IED.ZOWN_RTU.equals(ied)) {
        port = this.iec61850RtuPortServer;
    }

    // Try to connect and receive the ClientAssociation.
    final Iec61850ClientAssociation iec61850ClientAssociation = this.iec61850Client
            .connect(deviceIdentification, inetAddress, eventListener, port);
    final ClientAssociation clientAssociation = iec61850ClientAssociation.getClientAssociation();
    // Set response time-out.
    clientAssociation.setResponseTimeout(this.responseTimeout);
    // Read the ServerModel, either from the device or from a SCL file.
    ServerModel serverModel;
    try {
        serverModel = this.readServerModel(clientAssociation, deviceIdentification);
    } catch (final ProtocolAdapterException e) {
        LOGGER.error("ProtocolAdapterException: unable to read ServerModel for deviceIdentification "
                + deviceIdentification, e);
        throw new ConnectionFailureException(e.getMessage(), e);
    }

    // Cache the connection.
    this.cacheIec61850Connection(deviceIdentification,
            new Iec61850Connection(iec61850ClientAssociation, serverModel));

    final DateTime endTime = DateTime.now();
    LOGGER.info(
            "Connected to device: {}, fetched server model. Start time: {}, end time: {}, total time in milliseconds: {}",
            deviceIdentification, startTime, endTime, endTime.minus(startTime.getMillis()).getMillis());
}

From source file:com.almende.eve.scheduling.SyncScheduler.java

License:Apache License

@Override
public String schedule(final String id, final Object msg, final DateTime due) {
    final String uuid = id != null ? id : new UUID().toString();
    getClock().requestTrigger(uuid, due.minus(offset), new Runnable() {

        @Override// w w w. j a v  a  2  s. co  m
        public void run() {
            handleTrigger(msg, id);
        }

    });
    return uuid;
}

From source file:com.arpnetworking.metrics.common.tailer.FilePositionStore.java

License:Apache License

/**
 * {@inheritDoc}/* w ww. j a va  2s .  co  m*/
 */
@Override
public void setPosition(final String identifier, final long position) {
    final Descriptor descriptor = _state.putIfAbsent(identifier,
            new Descriptor.Builder().setPosition(position).build());

    final DateTime now = DateTime.now();
    boolean requiresFlush = now.minus(_flushInterval).isAfter(_lastFlush);
    if (descriptor != null) {
        descriptor.update(position, now);
        requiresFlush = requiresFlush || descriptor.getDelta() > _flushThreshold;
    }
    if (requiresFlush) {
        flush();
    }
}

From source file:com.arpnetworking.metrics.common.tailer.FilePositionStore.java

License:Apache License

private void flush() {
    // Age out old state
    final DateTime now = DateTime.now();
    final DateTime oldest = now.minus(_retention);
    final long sizeBefore = _state.size();
    final Iterator<Map.Entry<String, Descriptor>> iterator = _state.entrySet().iterator();
    while (iterator.hasNext()) {
        final Map.Entry<String, Descriptor> entry = iterator.next();
        if (!oldest.isBefore(entry.getValue().getLastUpdated())) {
            // Remove old descriptors
            iterator.remove();/*from ww  w  .ja  v a2  s.  co  m*/
        } else {
            // Mark retained descriptors as flushed
            entry.getValue().flush();
        }
    }
    final long sizeAfter = _state.size();
    if (sizeBefore != sizeAfter) {
        LOGGER.debug().setMessage("Removed old entries from file position store")
                .addData("sizeBefore", sizeBefore).addData("sizeAfter", sizeAfter).log();
    }

    // Persist the state to disk
    try {
        final Path temporaryFile = Paths.get(_file.toAbsolutePath().toString() + ".tmp");
        OBJECT_MAPPER.writeValue(temporaryFile.toFile(), _state);
        Files.move(temporaryFile, _file, StandardCopyOption.REPLACE_EXISTING);

        LOGGER.debug().setMessage("Persisted file position state to disk").addData("size", _state.size())
                .addData("file", _file).log();
    } catch (final IOException ioe) {
        throw Throwables.propagate(ioe);
    } finally {
        _lastFlush = now;
    }
}

From source file:com.arpnetworking.tsdcore.tailer.FilePositionStore.java

License:Apache License

/**
 * {@inheritDoc}//  ww w  .  jav  a 2 s  . co m
 */
@Override
public void setPosition(final String identifier, final long position) {
    final Descriptor descriptor = _state.putIfAbsent(identifier,
            new Descriptor.Builder().setPosition(Long.valueOf(position)).build());

    final DateTime now = DateTime.now();
    boolean requiresFlush = now.minus(_flushInterval).isAfter(_lastFlush);
    if (descriptor != null) {
        descriptor.update(position, now);
        requiresFlush = requiresFlush || descriptor.getDelta() > _flushThreshold;
    }
    if (requiresFlush) {
        flush();
    }
}