Example usage for org.joda.time DateTime parse

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

Introduction

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

Prototype

public static DateTime parse(String str, DateTimeFormatter formatter) 

Source Link

Document

Parses a DateTime from the specified string using a formatter.

Usage

From source file:org.apigw.authserver.svc.impl.ResidentServicesImpl.java

License:Open Source License

private boolean isOverAgeLimit(String childIdNumber) {
    final String dateOfBirthString = childIdNumber.substring(0, 8);
    final DateTime dateOfBirth = DateTime.parse(dateOfBirthString, ISODateTimeFormat.basicDate());

    return yearsBetween(dateOfBirth, now()).isGreaterThan(years(legalGuradianAgeLimit));
}

From source file:org.apigw.authserver.svc.impl.TokenServicesImpl.java

License:Open Source License

/**
 * @param residentIdentificationNumber in format yyyyMMddnnnn- for example 199212319876
 * @param validitySeconds - for example 43200  (60 * 60 * 12) - 12 hours in the future
 * @return//  w ww . j  a  v a 2  s .  c o  m
 */
protected Date generateExpirationTime(String residentIdentificationNumber, long validitySeconds) {
    if (residentIdentificationNumber == null || residentIdentificationNumber.length() < 8) {
        throw new IllegalArgumentException(
                "Invalid residentIdentificationNumber " + residentIdentificationNumber);
    }
    long validityMilliseconds = validitySeconds * 1000L;
    final String birthdayString = residentIdentificationNumber.substring(0, 8);
    final DateTime birthDate = DateTime.parse(birthdayString, ISODateTimeFormat.basicDate());
    Period period = new Period(birthDate, new DateTime(), PeriodType.yearMonthDay());
    DateTime birthDatePlusLegalGuardianAgeLimit = birthDate.plusYears(legalGuardianAgeLimit);
    DateTime residentAdultDate = birthDate.plusYears(adultAge);
    DateTime expiration = new DateTime().withTimeAtStartOfDay(); //defaulting to midnight of today (token will be immediately invalid)
    if (validitySeconds > 0) {
        // Standard expiration
        final DateTime standardExpiration = new DateTime().plus(validityMilliseconds);
        if (birthDatePlusLegalGuardianAgeLimit.isAfter(now().plus(validityMilliseconds))) { // resident will hit the legal guardian age after max token validity
            expiration = standardExpiration;
        } else if (residentAdultDate.isBeforeNow()) { // resident is considered adult
            expiration = standardExpiration;
        } else if (birthDatePlusLegalGuardianAgeLimit.isAfterNow()) { //resident will hit the legal guardian age before max token validity
            expiration = birthDatePlusLegalGuardianAgeLimit;
        }
        // if we get here resident has passed legal guardian age but is not considered adult, using default
    }
    log.debug("calculated token exp time for resident who is ~ {} years, {} months and {} days old to {}",
            period.getYears(), period.getMonths(), period.getDays(), expiration);
    return expiration.toDate();
}

From source file:org.biokoframework.system.services.passwordreset.impl.EmailPasswordResetService.java

License:Open Source License

private boolean isPast(String timeStamp) {
    DateTime expiration = DateTime.parse(timeStamp, dateTimeNoMillis());
    return fCurrentTime.getCurrentTimeAsDateTime().isAfter(expiration);
}

From source file:org.cinchapi.concourse.Timestamp.java

License:Open Source License

/**
 * Parses a {@code Timestamp} from the specified string.
 * <p>//w w  w.  j  a  v  a2s.  co m
 * This uses {@link ISODateTimeFormat#dateTimeParser()}.
 * 
 * @param str the string to parse, not null
 * @return the parsed timestamp
 */
public static Timestamp parse(String str) {
    return new Timestamp(DateTime.parse(str, ISODateTimeFormat.dateTimeParser().withOffsetParsed()));
}

From source file:org.dasein.cloud.google.compute.server.DiskSupport.java

License:Apache License

public Volume toVolume(Disk disk) throws InternalException, CloudException {
    Volume volume = new Volume();
    volume.setProviderVolumeId(disk.getName());
    volume.setName(disk.getName());//w w  w .  java  2  s  . co m
    volume.setMediaLink(disk.getSelfLink());
    if (disk.getDescription() == null)
        volume.setDescription(disk.getName());
    else
        volume.setDescription(disk.getDescription());
    volume.setProviderRegionId(provider.getDataCenterServices()
            .getRegionFromZone(disk.getZone().substring(disk.getZone().lastIndexOf("/") + 1)));

    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    DateTime dt = DateTime.parse(disk.getCreationTimestamp(), fmt);
    volume.setCreationTimestamp(dt.toDate().getTime());
    volume.setProviderDataCenterId(disk.getZone().substring(disk.getZone().lastIndexOf("/") + 1));
    if (disk.getStatus().equals("DONE") || disk.getStatus().equals("READY")) {
        volume.setCurrentState(VolumeState.AVAILABLE);
    } else if (disk.getStatus().equals("FAILED")) {
        volume.setCurrentState(VolumeState.ERROR);
    } else {
        volume.setCurrentState(VolumeState.PENDING);
    }
    volume.setType(VolumeType.HDD);
    volume.setFormat(VolumeFormat.BLOCK);
    volume.setSize(new Storage<Gigabyte>(disk.getSizeGb(), Storage.GIGABYTE));
    if (disk.getSourceSnapshotId() != null && !disk.getSourceSnapshotId().equals(""))
        volume.setProviderSnapshotId(disk.getSourceSnapshotId());
    volume.setTag("contentLink", disk.getSelfLink());

    //In order to list volumes with the attached VM, VMs must be listed. Doing it for now but, ick!
    Compute gce = provider.getGoogleCompute();
    try {
        //We only care about instances in the same zone as the disk
        InstanceList list = gce.instances().list(provider.getContext().getAccountNumber(),
                disk.getZone().substring(disk.getZone().lastIndexOf("/") + 1)).execute();
        if (list.getItems() != null) {
            for (Instance instance : list.getItems()) {
                for (AttachedDisk attachedDisk : instance.getDisks()) {
                    if (attachedDisk.getSource().equals(disk.getSelfLink())) {
                        volume.setDeviceId(attachedDisk.getDeviceName());
                        volume.setProviderVirtualMachineId(instance.getName() + "_" + instance.getId());
                        break;
                    }
                }
            }
        }
    } catch (IOException ex) {
        logger.error(ex.getMessage());
        return null;
    }
    return volume;
}

From source file:org.dasein.cloud.google.compute.server.ServerSupport.java

License:Apache License

private VirtualMachine toVirtualMachine(Instance instance) throws InternalException, CloudException {
    VirtualMachine vm = new VirtualMachine();
    vm.setProviderVirtualMachineId(instance.getName() + "_" + instance.getId().toString());
    vm.setName(instance.getName());/*from   w w w  . ja  va2  s .c o  m*/
    if (instance.getDescription() != null) {
        vm.setDescription(instance.getDescription());
    } else {
        vm.setDescription(instance.getName());
    }
    vm.setProviderOwnerId(provider.getContext().getAccountNumber());

    VmState vmState = null;
    if (instance.getStatus().equalsIgnoreCase("provisioning")
            || instance.getStatus().equalsIgnoreCase("staging")) {
        if ((null != instance.getStatusMessage()) && (instance.getStatusMessage().contains("failed"))) {
            vmState = VmState.ERROR;
        } else {
            vmState = VmState.PENDING;
        }
    } else if (instance.getStatus().equalsIgnoreCase("stopping")) {
        vmState = VmState.STOPPING;
    } else if (instance.getStatus().equalsIgnoreCase("terminated")) {
        vmState = VmState.STOPPED;
    } else {
        vmState = VmState.RUNNING;
    }
    vm.setCurrentState(vmState);
    String regionId = "";
    try {
        regionId = provider.getDataCenterServices()
                .getRegionFromZone(instance.getZone().substring(instance.getZone().lastIndexOf("/") + 1));
    } catch (Exception ex) {
        logger.error("An error occurred getting the region for the instance");
        return null;
    }
    vm.setProviderRegionId(regionId);
    String zone = instance.getZone();
    zone = zone.substring(zone.lastIndexOf("/") + 1);
    vm.setProviderDataCenterId(zone);

    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    DateTime dt = DateTime.parse(instance.getCreationTimestamp(), fmt);
    vm.setCreationTimestamp(dt.toDate().getTime());

    if (instance.getDisks() != null) {
        for (AttachedDisk disk : instance.getDisks()) {
            if (disk != null && disk.getBoot() != null && disk.getBoot()) {
                String diskName = disk.getSource().substring(disk.getSource().lastIndexOf("/") + 1);
                Compute gce = provider.getGoogleCompute();
                try {
                    Disk sourceDisk = gce.disks().get(provider.getContext().getAccountNumber(), zone, diskName)
                            .execute();
                    if (sourceDisk != null && sourceDisk.getSourceImage() != null) {
                        String project = "";
                        Pattern p = Pattern.compile("/projects/(.*?)/");
                        Matcher m = p.matcher(sourceDisk.getSourceImage());
                        while (m.find()) {
                            project = m.group(1);
                            break;
                        }
                        vm.setProviderMachineImageId(project + "_" + sourceDisk.getSourceImage()
                                .substring(sourceDisk.getSourceImage().lastIndexOf("/") + 1));
                    }
                } catch (IOException ex) {
                    logger.error(ex.getMessage());
                    if (ex.getClass() == GoogleJsonResponseException.class) {
                        GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex;
                        throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(),
                                gjre.getContent(), gjre.getDetails().getMessage());
                    } else
                        throw new InternalException("IOException: " + ex.getMessage());
                }
            }
        }
    }

    String machineTypeName = instance.getMachineType()
            .substring(instance.getMachineType().lastIndexOf("/") + 1);
    vm.setProductId(machineTypeName + "+" + zone);

    ArrayList<RawAddress> publicAddresses = new ArrayList<RawAddress>();
    ArrayList<RawAddress> privateAddresses = new ArrayList<RawAddress>();
    boolean firstPass = true;
    boolean isSet = false;
    String providerAssignedIpAddressId = null;
    for (NetworkInterface nic : instance.getNetworkInterfaces()) {
        if (firstPass) {
            vm.setProviderVlanId(nic.getNetwork().substring(nic.getNetwork().lastIndexOf("/") + 1));
            firstPass = false;
        }
        if (nic.getNetworkIP() != null) {
            privateAddresses.add(new RawAddress(nic.getNetworkIP()));
        }
        if (nic.getAccessConfigs() != null && !nic.getAccessConfigs().isEmpty()) {
            for (AccessConfig accessConfig : nic.getAccessConfigs()) {
                if (accessConfig.getNatIP() != null) {
                    publicAddresses.add(new RawAddress(accessConfig.getNatIP()));
                    if (!isSet) {
                        try {
                            isSet = true;
                            providerAssignedIpAddressId = provider.getNetworkServices().getIpAddressSupport()
                                    .getIpAddressIdFromIP(accessConfig.getNatIP(), regionId);
                        } catch (InternalException ex) {
                            /*Likely to be an ephemeral IP*/
                        }
                    }
                }
            }
        }
    }

    if (instance.getMetadata() != null && instance.getMetadata().getItems() != null) {
        for (Items metadataItem : instance.getMetadata().getItems()) {
            if (metadataItem.getKey().equals("sshKeys")) {
                vm.setRootUser(metadataItem.getValue().replaceAll(":.*", ""));
            }
        }
    }

    vm.setPublicAddresses(publicAddresses.toArray(new RawAddress[publicAddresses.size()]));
    vm.setPrivateAddresses(privateAddresses.toArray(new RawAddress[privateAddresses.size()]));
    vm.setProviderAssignedIpAddressId(providerAssignedIpAddressId);

    vm.setRebootable(true);
    vm.setPersistent(true);
    vm.setIpForwardingAllowed(true);
    vm.setImagable(false);
    vm.setClonable(false);

    vm.setPlatform(Platform.guess(instance.getName()));
    vm.setArchitecture(Architecture.I64);

    vm.setTag("contentLink", instance.getSelfLink());

    return vm;
}

From source file:org.dasein.cloud.google.compute.server.SnapshotSupport.java

License:Apache License

private @Nullable Snapshot toSnapshot(com.google.api.services.compute.model.Snapshot googleSnapshot) {
    Snapshot snapshot = new Snapshot();
    snapshot.setProviderSnapshotId(googleSnapshot.getName());
    snapshot.setName(googleSnapshot.getName());
    snapshot.setDescription(googleSnapshot.getDescription());
    snapshot.setOwner(provider.getContext().getAccountNumber());
    SnapshotState state = SnapshotState.PENDING;
    if (googleSnapshot.getStatus().equals("READY"))
        state = SnapshotState.AVAILABLE;
    else if (googleSnapshot.getStatus().equals("DELETING"))
        state = SnapshotState.DELETED;/* ww w  .j  a v  a2 s  . co m*/
    snapshot.setCurrentState(state);
    //TODO: Set visible scope for snapshots
    snapshot.setSizeInGb(googleSnapshot.getDiskSizeGb().intValue());

    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    DateTime dt = DateTime.parse(googleSnapshot.getCreationTimestamp(), fmt);
    snapshot.setSnapshotTimestamp(dt.toDate().getTime());

    String sourceDisk = googleSnapshot.getSourceDisk();
    if (sourceDisk != null) {
        snapshot.setVolumeId(sourceDisk.substring(sourceDisk.lastIndexOf("/") + 1));
    }

    return snapshot;
}

From source file:org.elasticsearch.util.IndexUtils.java

License:Apache License

/**
 * ?/*w  w  w  . ja  v a2 s. c om*/
 * @param timeStr
 * @return
 */
private static long parseCreateTime(String timeStr) {
    DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    DateTime dateTime2 = DateTime.parse(timeStr, formatter);
    return dateTime2.getMillis();
}

From source file:org.entcore.feeder.timetable.udt.UDTImporter.java

License:Open Source License

public void setEndStudents(String endStudents) {
    this.endStudents = DateTime.parse(endStudents, DateTimeFormat.forPattern(DATE_FORMAT)).getMillis();
}

From source file:org.entcore.feeder.timetable.udt.UDTImporter.java

License:Open Source License

public void setStartDateStudents(String startDateStudents) {
    this.startDateStudents = DateTime.parse(startDateStudents, DateTimeFormat.forPattern(DATE_FORMAT));
    maxYearWeek = this.startDateStudents.weekOfWeekyear().withMaximumValue().weekOfWeekyear().get();
}