Example usage for org.joda.time DateTime plusYears

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

Introduction

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

Prototype

public DateTime plusYears(int years) 

Source Link

Document

Returns a copy of this datetime plus the specified number of years.

Usage

From source file:net.link.util.test.pkix.PkiTestUtils.java

License:Open Source License

public static X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String dn)
        throws IllegalStateException, IOException, CertificateException, OperatorCreationException {

    DateTime now = new DateTime();
    DateTime future = now.plusYears(10);
    return generateSelfSignedCertificate(keyPair, dn, now, future, null, true, true, false);
}

From source file:net.ripe.rpki.commons.provisioning.ProvisioningObjectMother.java

License:BSD License

private static X509ResourceCertificate generateX509() {
    X509ResourceCertificateBuilder builder = new X509ResourceCertificateBuilder();

    builder.withSubjectDN(new X500Principal("CN=zz.subject")).withIssuerDN(new X500Principal("CN=zz.issuer"));
    builder.withSerial(BigInteger.ONE);
    builder.withPublicKey(TEST_KEY_PAIR.getPublic());
    builder.withSigningKeyPair(SECOND_TEST_KEY_PAIR);
    DateTime now = new DateTime(2011, 3, 1, 0, 0, 0, 0);
    builder.withValidityPeriod(new ValidityPeriod(now, now.plusYears(5)));
    builder.withResources(IpResourceSet.ALL_PRIVATE_USE_RESOURCES);
    return builder.build();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.pedagogicalCouncil.ViewTutorshipDA.java

License:Open Source License

/**
 * Aux method to create Partials/*from w  w w.ja  v a 2  s . co  m*/
 * 
 * @return
 */
private Partial createPartialForEndDate() {
    DateTime today = new DateTime();
    return new Partial(today.plusYears(2).toLocalDate());
}

From source file:net.tourbook.chart.ChartComponents.java

License:Open Source License

private void createHistoryUnits(final int firstYear, int lastYear) {

    /*/*from   w w w .  j a  v a 2  s . c o  m*/
     * add an additional year because at the year end, a history chart displays also the next
     * year which caused an outOfBound exception when testing this app at 28.12.2012
     */
    lastYear += 1;

    final int numberOfYears = lastYear - firstYear + 1;

    _historyYears = new int[numberOfYears];
    _historyMonths = new int[numberOfYears][12];
    _historyDOY = new int[numberOfYears];

    int yearIndex = 0;

    DateTime currentYear = new DateTime().withDate(firstYear - 1, 1, 1);

    for (int currentYearNo = firstYear; currentYearNo <= lastYear; currentYearNo++) {

        currentYear = currentYear.plusYears(1);

        _historyYears[yearIndex] = currentYearNo;

        int yearDOY = 0;

        // get number of days for each month
        for (int monthIndex = 0; monthIndex < 12; monthIndex++) {

            final int monthDays = currentYear.withMonthOfYear(monthIndex + 1).dayOfMonth().getMaximumValue();

            _historyMonths[yearIndex][monthIndex] = monthDays;

            yearDOY += monthDays;
        }

        _historyDOY[yearIndex] = yearDOY;

        yearIndex++;
    }
}

From source file:org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.date.BeamSqlDatetimePlusExpression.java

License:Apache License

private DateTime addInterval(DateTime dateTime, SqlTypeName intervalType, int numberOfIntervals) {
    switch (intervalType) {
    case INTERVAL_SECOND:
        return dateTime.plusSeconds(numberOfIntervals);
    case INTERVAL_MINUTE:
        return dateTime.plusMinutes(numberOfIntervals);
    case INTERVAL_HOUR:
        return dateTime.plusHours(numberOfIntervals);
    case INTERVAL_DAY:
        return dateTime.plusDays(numberOfIntervals);
    case INTERVAL_MONTH:
        return dateTime.plusMonths(numberOfIntervals);
    case INTERVAL_YEAR:
        return dateTime.plusYears(numberOfIntervals);
    default://w w w.jav  a 2s. c om
        throw new IllegalArgumentException("Adding " + intervalType.getName() + " to date is not supported");
    }
}

From source file:org.apache.cloudstack.saml.SAMLUtils.java

License:Apache License

public static X509Certificate generateRandomX509Certificate(KeyPair keyPair) throws NoSuchAlgorithmException,
        NoSuchProviderException, CertificateEncodingException, SignatureException, InvalidKeyException {
    DateTime now = DateTime.now(DateTimeZone.UTC);
    X500Principal dnName = new X500Principal("CN=ApacheCloudStack");
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setSubjectDN(dnName);/*from w ww  .j a  va2s  .  co  m*/
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(now.minusDays(1).toDate());
    certGen.setNotAfter(now.plusYears(3).toDate());
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    return certGen.generate(keyPair.getPrivate(), "BC");
}

From source file:org.apache.cloudstack.utils.security.CertUtils.java

License:Apache License

public static X509Certificate generateV1Certificate(final KeyPair keyPair, final String subject,
        final String issuer, final int validityYears, final String signatureAlgorithm)
        throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        InvalidKeyException, OperatorCreationException {
    final DateTime now = DateTime.now(DateTimeZone.UTC);
    final X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(new X500Name(issuer),
            generateRandomBigInt(), now.minusDays(1).toDate(), now.plusYears(validityYears).toDate(),
            new X500Name(subject), keyPair.getPublic());
    final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC")
            .build(keyPair.getPrivate());
    final X509CertificateHolder certHolder = certBuilder.build(signer);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
}

From source file:org.apache.drill.cv.exec.server.rest.CvDrillWebServer.java

License:Apache License

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified
 * keystore/truststore settings they will be used else a self-signed certificate is generated and
 * used.//from ww w  .jav a2s  .  c  o m
 *
 * @return Initialized {@link ServerConnector} for HTTPS connectios.
 * @throws Exception
 */
private ServerConnector createHttpsConnector() throws Exception {
    CvDrillWebServer.logger.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH)
            && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) {
        CvDrillWebServer.logger.info("Using configured SSL settings for web server");
        sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
        sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));

        // TrustStore and TrustStore password are optional
        if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
            sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
            if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
                sslContextFactory
                        .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
            }
        }
    } else {
        CvDrillWebServer.logger.info("Using generated self-signed SSL settings for web server");
        final SecureRandom random = new SecureRandom();

        // Generate a private-public key pair
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024, random);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();

        final DateTime now = DateTime.now();

        // Create builder for certificate attributes
        final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
                .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
                .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
                .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());

        final Date notBefore = now.minusMinutes(1).toDate();
        final Date notAfter = now.plusYears(5).toDate();
        final BigInteger serialNumber = new BigInteger(128, random);

        // Create a certificate valid for 5years from now.
        final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
                serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

        // Sign the certificate using the private key
        final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .build(keyPair.getPrivate());
        final X509Certificate certificate = new JcaX509CertificateConverter()
                .getCertificate(certificateBuilder.build(contentSigner));

        // Check the validity
        certificate.checkValidity(now.toDate());

        // Make sure the certificate is self-signed.
        certificate.verify(certificate.getPublicKey());

        // Generate a random password for keystore protection
        final String keyStorePasswd = RandomStringUtils.random(20);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);
        keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        sslContextFactory.setKeyStore(keyStore);
        sslContextFactory.setKeyStorePassword(keyStorePasswd);
    }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(getWebserverPort());

    return sslConnector;
}

From source file:org.apache.drill.exec.server.rest.WebServer.java

License:Apache License

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings
 * they will be used else a self-signed certificate is generated and used.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connectios.
 * @throws Exception//from  w  ww .j a  va 2s .  c  o  m
 */
private ServerConnector createHttpsConnector() throws Exception {
    logger.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH)
            && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) {
        logger.info("Using configured SSL settings for web server");
        sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
        sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));

        // TrustStore and TrustStore password are optional
        if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
            sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
            if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
                sslContextFactory
                        .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
            }
        }
    } else {
        logger.info("Using generated self-signed SSL settings for web server");
        final SecureRandom random = new SecureRandom();

        // Generate a private-public key pair
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024, random);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();

        final DateTime now = DateTime.now();

        // Create builder for certificate attributes
        final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
                .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
                .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
                .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());

        final Date notBefore = now.minusMinutes(1).toDate();
        final Date notAfter = now.plusYears(5).toDate();
        final BigInteger serialNumber = new BigInteger(128, random);

        // Create a certificate valid for 5years from now.
        final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
                serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

        // Sign the certificate using the private key
        final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .build(keyPair.getPrivate());
        final X509Certificate certificate = new JcaX509CertificateConverter()
                .getCertificate(certificateBuilder.build(contentSigner));

        // Check the validity
        certificate.checkValidity(now.toDate());

        // Make sure the certificate is self-signed.
        certificate.verify(certificate.getPublicKey());

        // Generate a random password for keystore protection
        final String keyStorePasswd = RandomStringUtils.random(20);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);
        keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        sslContextFactory.setKeyStore(keyStore);
        sslContextFactory.setKeyStorePassword(keyStorePasswd);
    }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT));

    return sslConnector;
}

From source file:org.apache.drill.yarn.appMaster.http.WebServer.java

License:Apache License

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has
 * specified keystore/truststore settings they will be used else a self-signed
 * certificate is generated and used./*from  ww  w . j a v a  2  s .com*/
 * <p>
 * This is a shameless copy of
 * {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}.
 * The two should be merged at some point. The primary issue is that the Drill
 * version is tightly coupled to Drillbit configuration.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connections.
 * @throws Exception
 */

private ServerConnector createHttpsConnector(Config config) throws Exception {
    LOG.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    // if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) &&
    // !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)))
    // {
    // LOG.info("Using configured SSL settings for web server");
    // sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
    // sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));
    //
    // // TrustStore and TrustStore password are optional
    // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
    // sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
    // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
    // sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
    // }
    // }
    // } else {
    LOG.info("Using generated self-signed SSL settings for web server");
    final SecureRandom random = new SecureRandom();

    // Generate a private-public key pair
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, random);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final DateTime now = DateTime.now();

    // Create builder for certificate attributes
    final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
            .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
            .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, "Drill AM");

    final Date notBefore = now.minusMinutes(1).toDate();
    final Date notAfter = now.plusYears(5).toDate();
    final BigInteger serialNumber = new BigInteger(128, random);

    // Create a certificate valid for 5years from now.
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
            serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

    // Sign the certificate using the private key
    final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .build(keyPair.getPrivate());
    final X509Certificate certificate = new JcaX509CertificateConverter()
            .getCertificate(certificateBuilder.build(contentSigner));

    // Check the validity
    certificate.checkValidity(now.toDate());

    // Make sure the certificate is self-signed.
    certificate.verify(certificate.getPublicKey());

    // Generate a random password for keystore protection
    final String keyStorePasswd = RandomStringUtils.random(20);
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
            new java.security.cert.Certificate[] { certificate });

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePasswd);
    // }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(jettyServer,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT));

    return sslConnector;
}