Example usage for org.joda.time Duration standardDays

List of usage examples for org.joda.time Duration standardDays

Introduction

In this page you can find the example usage for org.joda.time Duration standardDays.

Prototype

public static Duration standardDays(long days) 

Source Link

Document

Create a duration with the specified number of days assuming that there are the standard number of milliseconds in a day.

Usage

From source file:com.microsoft.azure.management.graphrbac.samples.ManageServicePrincipal.java

License:Open Source License

private static ServicePrincipal createServicePrincipalWithRoleForApplicationAndExportToFile(
        Azure.Authenticated authenticated, ActiveDirectoryApplication activeDirectoryApplication,
        BuiltInRole role, String subscriptionId, String authFilePath) throws Exception {

    String name = SdkContext.randomResourceName("sp-sample", 20);
    //create a self-sighed certificate
    String domainName = name + ".com";
    String certPassword = "StrongPass!12";
    Certificate certificate = Certificate.createSelfSigned(domainName, certPassword);

    // create  a Service Principal and assign it to a subscription with the role Contributor
    return authenticated.servicePrincipals().define("name").withExistingApplication(activeDirectoryApplication)
            // password credentials definition
            .definePasswordCredential("ServicePrincipalAzureSample").withPasswordValue("StrongPass!12").attach()
            // certificate credentials definition
            .defineCertificateCredential("spcert").withAsymmetricX509Certificate()
            .withPublicKey(Files.readAllBytes(Paths.get(certificate.getCerPath())))
            .withDuration(Duration.standardDays(7))
            // export the credentials to the file
            .withAuthFileToExport(new FileOutputStream(authFilePath))
            .withPrivateKeyFile(certificate.getPfxPath()).withPrivateKeyPassword(certPassword).attach()
            .withNewRoleInSubscription(role, subscriptionId).create();
}

From source file:com.microsoft.azure.management.graphrbac.samples.ManageServicePrincipal.java

License:Open Source License

private static void manageApplication(Azure.Authenticated authenticated,
        ActiveDirectoryApplication activeDirectoryApplication) {
    activeDirectoryApplication.update()/*from  w ww  .j  av a 2  s.  co  m*/
            // add another password credentials
            .definePasswordCredential("password-1").withPasswordValue("P@ssw0rd-1")
            .withDuration(Duration.standardDays(700)).attach()
            // add a reply url
            .withReplyUrl("http://localhost:8080").apply();
}

From source file:com.microsoft.azure.management.graphrbac.samples.ManageServicePrincipalCredentials.java

License:Open Source License

/**
 * Main function which runs the actual sample.
 *
 * @param authenticated instance of Authenticated
 * @param defaultSubscription default subscription id
 * @param environment the environment the sample is running in
 * @return true if sample runs successfully
 *//*from ww  w  . j a  v a 2 s .  c o  m*/
public static boolean runSample(Azure.Authenticated authenticated, String defaultSubscription,
        AzureEnvironment environment) {
    final String spName = Utils.createRandomName("sp");
    final String appName = SdkContext.randomResourceName("app", 20);
    final String appUrl = "https://" + appName;
    final String passwordName1 = SdkContext.randomResourceName("password", 20);
    final String password1 = "P@ssw0rd";
    final String passwordName2 = SdkContext.randomResourceName("password", 20);
    final String password2 = "StrongP@ss!12";
    final String certName1 = SdkContext.randomResourceName("cert", 20);
    final String raName = SdkContext.randomUuid();
    String applicationId = "";
    try {
        // ============================================================
        // Create application

        System.out.println("Creating an Active Directory application " + appName + "...");

        ActiveDirectoryApplication application = authenticated.activeDirectoryApplications().define(appName)
                .withSignOnUrl(appUrl).definePasswordCredential(passwordName1).withPasswordValue(password1)
                .attach().definePasswordCredential(passwordName2).withPasswordValue(password2).attach()
                .defineCertificateCredential(certName1).withAsymmetricX509Certificate()
                .withPublicKey(ByteStreams.toByteArray(
                        ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.cer")))
                .withDuration(Duration.standardDays(1)).attach().create();

        System.out.println("Created Active Directory application " + appName + ".");
        Utils.print(application);

        applicationId = application.id();

        // ============================================================
        // Create service principal

        System.out.println("Creating an Active Directory service principal " + spName + "...");

        ServicePrincipal servicePrincipal = authenticated.servicePrincipals().define(spName)
                .withExistingApplication(application).create();

        System.out.println("Created service principal " + spName + ".");
        Utils.print(servicePrincipal);

        // ============================================================
        // Create role assignment

        System.out
                .println("Creating a Contributor role assignment " + raName + " for the service principal...");

        Thread.sleep(15000);

        RoleAssignment roleAssignment = authenticated.roleAssignments().define(raName)
                .forServicePrincipal(servicePrincipal).withBuiltInRole(BuiltInRole.CONTRIBUTOR)
                .withSubscriptionScope(defaultSubscription).create();

        System.out.println("Created role assignment " + raName + ".");
        Utils.print(roleAssignment);

        // ============================================================
        // Verify the credentials are valid

        System.out.println("Verifying password credential " + passwordName1 + " is valid...");

        ApplicationTokenCredentials testCredential = new ApplicationTokenCredentials(
                servicePrincipal.applicationId(), authenticated.tenantId(), password1, environment);
        try {
            Azure.authenticate(testCredential).withDefaultSubscription();

            System.out.println("Verified " + passwordName1 + " is valid.");
        } catch (Exception e) {
            System.out.println("Failed to verify " + passwordName1 + " is valid.");
        }

        System.out.println("Verifying password credential " + passwordName2 + " is valid...");

        testCredential = new ApplicationTokenCredentials(servicePrincipal.applicationId(),
                authenticated.tenantId(), password2, environment);
        try {
            Azure.authenticate(testCredential).withDefaultSubscription();

            System.out.println("Verified " + passwordName2 + " is valid.");
        } catch (Exception e) {
            System.out.println("Failed to verify " + passwordName2 + " is valid.");
        }

        System.out.println("Verifying certificate credential " + certName1 + " is valid...");

        testCredential = new ApplicationTokenCredentials(servicePrincipal.applicationId(),
                authenticated.tenantId(),
                ByteStreams.toByteArray(
                        ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.pfx")),
                "Abc123", environment);
        try {
            Azure.authenticate(testCredential).withDefaultSubscription();

            System.out.println("Verified " + certName1 + " is valid.");
        } catch (Exception e) {
            System.out.println("Failed to verify " + certName1 + " is valid.");
        }

        // ============================================================
        // Revoke access of the 1st password credential
        System.out.println("Revoking access for password credential " + passwordName1 + "...");

        application.update().withoutCredential(passwordName1).apply();

        Thread.sleep(15000);

        System.out.println("Credential revoked.");

        // ============================================================
        // Verify the revoked password credential is no longer valid

        System.out.println("Verifying password credential " + passwordName1 + " is revoked...");

        testCredential = new ApplicationTokenCredentials(servicePrincipal.applicationId(),
                authenticated.tenantId(), password1, environment);
        try {
            Azure.authenticate(testCredential).withDefaultSubscription();

            System.out.println("Failed to verify " + passwordName1 + " is revoked.");
        } catch (Exception e) {
            System.out.println("Verified " + passwordName1 + " is revoked.");
        }

        // ============================================================
        // Revoke the role assignment

        System.out.println("Revoking role assignment " + raName + "...");

        authenticated.roleAssignments().deleteById(roleAssignment.id());

        Thread.sleep(5000);

        // ============================================================
        // Verify the revoked password credential is no longer valid

        System.out.println(
                "Verifying password credential " + passwordName2 + " has no access to subscription...");

        testCredential = new ApplicationTokenCredentials(servicePrincipal.applicationId(),
                authenticated.tenantId(), password2, environment);
        try {
            Azure.authenticate(testCredential).withDefaultSubscription().resourceGroups().list();

            System.out.println("Failed to verify " + passwordName2 + " has no access to subscription.");
        } catch (Exception e) {
            System.out.println("Verified " + passwordName2 + " has no access to subscription.");
        }

        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting application: " + appName);
            authenticated.activeDirectoryApplications().deleteById(applicationId);
            System.out.println("Deleted application: " + appName);
        } catch (Exception e) {
            System.out.println("Did not create applications in Azure. No clean up is necessary");
        }
    }
    return false;
}

From source file:com.mirth.connect.server.util.LoginRequirementsChecker.java

License:Open Source License

private Duration getDurationRemainingFromDays(long passwordTime, long currentTime, int durationDays) {
    Duration expirationDuration = Duration.standardDays(durationDays);
    Duration passwordDuration = new Duration(passwordTime, currentTime);

    return expirationDuration.minus(passwordDuration);
}

From source file:com.mirth.connect.server.util.PasswordRequirementsChecker.java

License:Open Source License

private String checkReusePeriod(List<Credentials> previousCredentials, String plainPassword, int reusePeriod) {
    // Return without checking if the reuse policies are off
    if (reusePeriod == 0) {
        return null;
    }// ww  w.j  av a2  s. co m

    UserController userController = ControllerFactory.getFactory().createUserController();

    // Let -1 mean the duration is infinite
    Duration reusePeriodDuration = null;
    if (reusePeriod != -1) {
        reusePeriodDuration = Duration.standardDays(reusePeriod);
    }

    for (Credentials credentials : previousCredentials) {
        boolean checkPassword = false;
        if (reusePeriodDuration == null) {
            checkPassword = true;
        } else {
            checkPassword = reusePeriodDuration.isLongerThan(
                    new Duration(credentials.getPasswordDate().getTimeInMillis(), System.currentTimeMillis()));
        }

        if (checkPassword && userController.checkPassword(plainPassword, credentials.getPassword())) {
            if (reusePeriod == -1) {
                return "You cannot reuse the same password.";
            }
            return "You cannot reuse the same password within " + reusePeriod + " days.";
        }
    }

    return null;
}

From source file:com.mirth.connect.server.util.PasswordRequirementsChecker.java

License:Open Source License

public Calendar getLastExpirationDate(PasswordRequirements passwordRequirements) {
    DateTime dateTime = new DateTime();

    // Must keep all passwords if reuse period is -1 (infinite) or reuse limit is set
    if ((passwordRequirements.getReusePeriod() == -1) || passwordRequirements.getReuseLimit() != 0) {
        return null;
    }/*w w w.  jav  a2 s  .  co  m*/

    if (passwordRequirements.getReusePeriod() == 0) {
        return Calendar.getInstance();
    }

    return dateTime.minus(Duration.standardDays(passwordRequirements.getReusePeriod()))
            .toCalendar(Locale.getDefault());
}

From source file:com.peertopark.java.dates.Dates.java

License:Apache License

/**
 * Get seconds fromDays//from w w w.j a  v  a2s.c o m
 *
 * @param days
 * @return long
 */
public static long getSecondsFromDays(long days) {
    return Duration.standardDays(days).getStandardSeconds();
}

From source file:com.robwilliamson.healthyesther.reminder.TimingModel.java

License:Open Source License

private RangeSet allowedTimes() {
    DateTime yesterday = mEnvironment.getNow().minus(Duration.standardDays(1));
    return mAllowedNotificationTimes.startingFrom(yesterday.getYear(), yesterday.getMonthOfYear(),
            yesterday.getDayOfMonth());//from www .j a  v a2s  . c  om
}

From source file:com.robwilliamson.healthyesther.util.time.Range.java

License:Open Source License

public Range startingTomorrow() {
    return startingFrom(from.plus(Duration.standardDays(1)));
}

From source file:com.robwilliamson.healthyesther.util.time.Range.java

License:Open Source License

public Range startingYesterday() {
    return startingFrom(from.minus(Duration.standardDays(1)));
}