Example usage for org.joda.time.format ISODateTimeFormat dateTime

List of usage examples for org.joda.time.format ISODateTimeFormat dateTime

Introduction

In this page you can find the example usage for org.joda.time.format ISODateTimeFormat dateTime.

Prototype

public static DateTimeFormatter dateTime() 

Source Link

Document

Returns a formatter that combines a full date and time, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).

Usage

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());//ww  w  .j  a  va2  s.c om
    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());/* ww  w  . j  a  v a2 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;// w  w  w  . ja v a 2s . c  o  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.datanucleus.store.types.jodatime.converters.JodaDateTimeStringConverter.java

License:Open Source License

public DateTime toMemberType(String str) {
    if (str == null) {
        return null;
    }

    return ISODateTimeFormat.dateTime().parseDateTime(str);
}

From source file:org.datanucleus.store.types.jodatime.converters.JodaLocalDateTimeStringConverter.java

License:Open Source License

public LocalDateTime toMemberType(String str) {
    if (str == null) {
        return null;
    }/*from  www  . ja v a 2s.c  o m*/

    return ISODateTimeFormat.dateTime().parseLocalDateTime(str);
}

From source file:org.ddialliance.ddiftp.util.Translator.java

License:Open Source License

/**
 * Format an ISO8601 time string defined by into a Calendar<BR>
 * Defined by '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)?
 * (zzzzzz)?/*from   ww  w .  j  a  v a 2  s. c o m*/
 * 
 * @see http://www.w3.org/TR/xmlschema-2/#dateTime
 * @param time
 *            string
 * @return calendar
 * @throws DDIFtpException
 */
public static Calendar formatIso8601DateTime(String time) throws DDIFtpException {
    // yyyy-MM-dd'T'HH:mm:ss.SSSZZ full format
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    try {
        DateTime dateTime = fmt.parseDateTime(time);
        return dateTime.toCalendar(getLocale());
    } catch (IllegalArgumentException e) {
        try {
            // yyyy-MM-dd'T'HH:mm:ssZZ with out millisecond
            fmt = ISODateTimeFormat.dateTimeNoMillis();
            fmt.withLocale(getLocale());
            fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
            DateTime dateTime = fmt.parseDateTime(time);
            return dateTime.toCalendar(getLocale());
        } catch (IllegalArgumentException e1) {
            try {
                // yyyy-MM-dd'T'HH:mm:ss.SS with out time zone
                fmt = ISODateTimeFormat.dateHourMinuteSecondFraction();
                fmt.withLocale(getLocale());
                fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                DateTime dateTime = fmt.parseDateTime(time);
                return dateTime.toCalendar(getLocale());
            } catch (Exception e2) {
                try {
                    // yyyy-MM-dd'T'HH:mm:ss with out millisecond and time
                    // zone
                    fmt = ISODateTimeFormat.dateHourMinuteSecond();
                    fmt.withLocale(getLocale());
                    fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                    DateTime dateTime = fmt.parseDateTime(time);
                    return dateTime.toCalendar(getLocale());
                } catch (IllegalArgumentException e3) {
                    try {
                        fmt = ISODateTimeFormat.dateParser();
                        fmt.withLocale(getLocale());
                        fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                        DateTime dateTime = fmt.parseDateTime(time);
                        return dateTime.toCalendar(getLocale());
                    } catch (Exception e4) {
                        throw new DDIFtpException("translate.timeformat.error",
                                new Object[] { time,
                                        "'-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?" },
                                e);
                    }
                }
            }
        }
    }
}

From source file:org.ddialliance.ddiftp.util.Translator.java

License:Open Source License

/**
 * Format time in milli seconds to an ISO8601 time string<BR>
 * Defined by '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)?
 * (zzzzzz)?/*from  w  ww .  j  ava 2s. c  o  m*/
 * 
 * @see http://www.w3.org/TR/xmlschema-2/#dateTime
 * @param time
 *            in milli seconds
 * @return ISO8601 time string
 * @throws DDIFtpException
 */
public static String formatIso8601DateTime(long time) {
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    fmt.withLocale(getLocale());
    fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
    return fmt.print(time);
}

From source file:org.dspace.authority.AuthorityValue.java

License:BSD License

public List<DateTimeFormatter> getDateFormatters() {
    List<DateTimeFormatter> list = new ArrayList<DateTimeFormatter>();
    list.add(ISODateTimeFormat.dateTime());
    list.add(ISODateTimeFormat.dateTimeNoMillis());
    return list;//from w  w  w . j  a  v  a  2  s. c  om
}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.JsonDocumentWriter.java

License:Open Source License

public static JSONObject getJSON(DocumentModel doc, String[] schemas) throws Exception {
    JSONObject json = new JSONObject();
    json.element("entity-type", "document");
    json.element("repository", doc.getRepositoryName());
    json.element("uid", doc.getId());
    json.element("path", doc.getPathAsString());
    json.element("type", doc.getType());
    json.element("state", doc.getCurrentLifeCycleState());
    json.element("lock", doc.getLock()); // old
    Lock lock = doc.getLockInfo();
    if (lock != null) {
        json.element("lockOwner", lock.getOwner());
        json.element("lockCreated", ISODateTimeFormat.dateTime().print(new DateTime(lock.getCreated())));
    }//from   ww  w.  j a v  a 2s. c  o m
    json.element("title", doc.getTitle());
    Calendar cal = (Calendar) doc.getPart("dublincore").getValue("modified");
    if (cal != null) {
        json.element("lastModified", DateParser.formatW3CDateTime(cal.getTime()));
    }

    if (schemas == null || schemas.length == 0) {
        return json;
    }

    JSONObject props = new JSONObject();
    if (schemas.length == 1 && "*".equals(schemas[0])) { // full
        // document
        for (String schema : doc.getSchemas()) {
            addSchema(props, doc, schema);
        }
    } else {
        for (String schema : schemas) {
            addSchema(props, doc, schema);
        }
    }

    json.element("properties", props);
    return json;
}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.writers.JsonDocumentWriter.java

License:Open Source License

public static void writeDocument(JsonGenerator jg, DocumentModel doc, String[] schemas) throws Exception {
    jg.writeStartObject();/*w  ww. j a v  a  2 s .  c  o  m*/
    jg.writeStringField("entity-type", "document");
    jg.writeStringField("repository", doc.getRepositoryName());
    jg.writeStringField("uid", doc.getId());
    jg.writeStringField("path", doc.getPathAsString());
    jg.writeStringField("type", doc.getType());
    jg.writeStringField("state", doc.getCurrentLifeCycleState());
    Lock lock = doc.getLockInfo();
    if (lock != null) {
        jg.writeStringField("lockOwner", lock.getOwner());
        jg.writeStringField("lockCreated", ISODateTimeFormat.dateTime().print(new DateTime(lock.getCreated())));
    } else {
        jg.writeStringField("lock", doc.getLock()); // old
    }
    jg.writeStringField("title", doc.getTitle());
    try {
        Calendar cal = (Calendar) doc.getPropertyValue("dc:modified");
        if (cal != null) {
            jg.writeStringField("lastModified", DateParser.formatW3CDateTime(cal.getTime()));
        }
    } catch (PropertyNotFoundException e) {
        // ignore
    }

    if (schemas != null && schemas.length > 0) {
        jg.writeObjectFieldStart("properties");
        if (schemas.length == 1 && "*".equals(schemas[0])) {
            // full document
            for (String schema : doc.getSchemas()) {
                writeProperties(jg, doc, schema);
            }
        } else {
            for (String schema : schemas) {
                writeProperties(jg, doc, schema);
            }
        }
        jg.writeEndObject();
    }

    jg.writeArrayFieldStart("facets");
    for (String facet : doc.getFacets()) {
        jg.writeString(facet);
    }
    jg.writeEndArray();
    jg.writeStringField("changeToken", doc.getChangeToken());

    jg.writeEndObject();
    jg.flush();
}