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

@FromString
public static DateTime parse(String str) 

Source Link

Document

Parses a DateTime from the specified string.

Usage

From source file:google.registry.rde.RdeModule.java

License:Open Source License

@Provides
@Parameter(PARAM_WATERMARK)
static DateTime provideWatermark(HttpServletRequest req) {
    return DateTime.parse(RequestParameters.extractRequiredParameter(req, PARAM_WATERMARK));
}

From source file:google.registry.request.RequestParameters.java

License:Open Source License

/**
 * Returns first request parameter associated with {@code name} parsed as an
 * <a href="https://goo.gl/pk5Q2k">ISO 8601</a> timestamp, e.g. {@code 1984-12-18TZ},
 * {@code 2000-01-01T16:20:00Z}./*from   w  w  w.ja  v a  2 s.co  m*/
 *
 * @throws BadRequestException if request parameter named {@code name} is absent, empty, or could
 *     not be parsed as an ISO 8601 timestamp
 */
public static DateTime extractRequiredDatetimeParameter(HttpServletRequest req, String name) {
    String stringValue = extractRequiredParameter(req, name);
    try {
        return DateTime.parse(stringValue);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException("Bad ISO 8601 timestamp: " + name);
    }
}

From source file:google.registry.request.RequestParameters.java

License:Open Source License

/**
 * Returns first request parameter associated with {@code name} parsed as an
 * <a href="https://goo.gl/pk5Q2k">ISO 8601</a> timestamp, e.g. {@code 1984-12-18TZ},
 * {@code 2000-01-01T16:20:00Z}./*from w  ww. jav a  2 s  .co  m*/
 *
 * @throws BadRequestException if request parameter is present but not a valid {@link DateTime}.
 */
public static Optional<DateTime> extractOptionalDatetimeParameter(HttpServletRequest req, String name) {
    String stringParam = req.getParameter(name);
    try {
        return isNullOrEmpty(stringParam) ? Optional.<DateTime>absent()
                : Optional.of(DateTime.parse(stringParam));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException("Bad ISO 8601 timestamp: " + name);
    }
}

From source file:google.registry.testing.FullFieldsTestEntityHelper.java

License:Open Source License

public static HostResource makeHostResource(String fqhn, @Nullable String ip1, @Nullable String ip2) {
    HostResource.Builder builder = new HostResource.Builder().setRepoId(generateNewContactHostRoid())
            .setFullyQualifiedHostName(Idn.toASCII(fqhn))
            .setCreationTimeForTest(DateTime.parse("2000-10-08T00:45:00Z"));
    if ((ip1 != null) || (ip2 != null)) {
        ImmutableSet.Builder<InetAddress> ipBuilder = new ImmutableSet.Builder<>();
        if (ip1 != null) {
            ipBuilder.add(InetAddresses.forString(ip1));
        }//from   w  ww.  ja v  a 2  s .  c  o m
        if (ip2 != null) {
            ipBuilder.add(InetAddresses.forString(ip2));
        }
        builder.setInetAddresses(ipBuilder.build());
    }
    return builder.build();
}

From source file:google.registry.testing.FullFieldsTestEntityHelper.java

License:Open Source License

public static ContactResource makeContactResource(String id, String name, @Nullable String email,
        @Nullable List<String> street) {
    PostalInfo.Builder postalBuilder = new PostalInfo.Builder().setType(PostalInfo.Type.INTERNATIONALIZED)
            .setName(name).setOrg("GOOGLE INCORPORATED <script>");
    if (street != null) {
        postalBuilder.setAddress(new ContactAddress.Builder().setStreet(ImmutableList.copyOf(street))
                .setCity("KOKOMO").setState("BM").setZip("31337").setCountryCode("US").build());
    }/*  w ww  . j  a  v a2 s  .c o m*/
    ContactResource.Builder builder = new ContactResource.Builder().setContactId(id)
            .setRepoId(generateNewContactHostRoid())
            .setCreationTimeForTest(DateTime.parse("2000-10-08T00:45:00Z"))
            .setInternationalizedPostalInfo(postalBuilder.build())
            .setVoiceNumber(new ContactPhoneNumber.Builder().setPhoneNumber("+1.2126660420").build())
            .setFaxNumber(new ContactPhoneNumber.Builder().setPhoneNumber("+1.2126660420").build());
    if (email != null) {
        builder.setEmailAddress(email);
    }
    return builder.build();
}

From source file:google.registry.testing.FullFieldsTestEntityHelper.java

License:Open Source License

public static DomainResource makeDomainResource(String domain, @Nullable ContactResource registrant,
        @Nullable ContactResource admin, @Nullable ContactResource tech, @Nullable HostResource ns1,
        @Nullable HostResource ns2, Registrar registrar) {
    DomainResource.Builder builder = new DomainResource.Builder()
            .setFullyQualifiedDomainName(Idn.toASCII(domain))
            .setRepoId(generateNewDomainRoid(getTldFromDomainName(Idn.toASCII(domain))))
            .setLastEppUpdateTime(DateTime.parse("2009-05-29T20:13:00Z"))
            .setCreationTimeForTest(DateTime.parse("2000-10-08T00:45:00Z"))
            .setRegistrationExpirationTime(DateTime.parse("2110-10-08T00:44:59Z"))
            .setCurrentSponsorClientId(registrar.getClientId())
            .setStatusValues(/*  ww w . j av  a  2  s  .com*/
                    ImmutableSet.of(StatusValue.CLIENT_DELETE_PROHIBITED, StatusValue.CLIENT_RENEW_PROHIBITED,
                            StatusValue.CLIENT_TRANSFER_PROHIBITED, StatusValue.SERVER_UPDATE_PROHIBITED))
            .setDsData(ImmutableSet.of(new DelegationSignerData()));
    if (registrant != null) {
        builder.setRegistrant(Key.create(registrant));
    }
    if ((admin != null) || (tech != null)) {
        ImmutableSet.Builder<DesignatedContact> contactsBuilder = new ImmutableSet.Builder<>();
        if (admin != null) {
            contactsBuilder.add(DesignatedContact.create(DesignatedContact.Type.ADMIN, Key.create(admin)));
        }
        if (tech != null) {
            contactsBuilder.add(DesignatedContact.create(DesignatedContact.Type.TECH, Key.create(tech)));
        }
        builder.setContacts(contactsBuilder.build());
    }
    if ((ns1 != null) || (ns2 != null)) {
        ImmutableSet.Builder<Key<HostResource>> nsBuilder = new ImmutableSet.Builder<>();
        if (ns1 != null) {
            nsBuilder.add(Key.create(ns1));
        }
        if (ns2 != null) {
            nsBuilder.add(Key.create(ns2));
        }
        builder.setNameservers(nsBuilder.build());
    }
    return builder.build();
}

From source file:google.registry.tmch.ClaimsListParser.java

License:Open Source License

/**
 * Converts the lines from the DNL CSV file into a {@link ClaimsListShard} object.
 *
 * <p>Please note that this does <b>not</b> insert the object into the datastore.
 *//*from ww  w. ja  va 2s.  c  om*/
public static ClaimsListShard parse(List<String> lines) {
    ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();

    // First line: <version>,<DNL List creation datetime>
    List<String> firstLine = Splitter.on(',').splitToList(lines.get(0));
    checkArgument(firstLine.size() == 2,
            String.format("Line 1: Expected 2 elements, found %d", firstLine.size()));

    Integer version = Integer.valueOf(firstLine.get(0));
    DateTime creationTime = DateTime.parse(firstLine.get(1));
    checkArgument(version == 1, String.format("Line 1: Expected version 1, found %d", version));

    // Second line contains headers: DNL,lookup-key,insertion-datetime
    List<String> secondLine = Splitter.on(',').splitToList(lines.get(1));
    checkArgument(secondLine.size() == 3,
            String.format("Line 2: Expected 3 elements, found %d", secondLine.size()));
    checkArgument("DNL".equals(secondLine.get(0)),
            String.format("Line 2: Expected header \"DNL\", found \"%s\"", secondLine.get(0)));
    checkArgument("lookup-key".equals(secondLine.get(1)),
            String.format("Line 2: Expected header \"lookup-key\", found \"%s\"", secondLine.get(1)));
    checkArgument("insertion-datetime".equals(secondLine.get(2)),
            String.format("Line 2: Expected header \"insertion-datetime\", found \"%s\"", secondLine.get(2)));

    // Subsequent lines: <DNL>,<lookup key>,<DNL insertion datetime>
    for (int i = 2; i < lines.size(); i++) {
        List<String> currentLine = Splitter.on(',').splitToList(lines.get(i));
        checkArgument(currentLine.size() == 3,
                String.format("Line %d: Expected 3 elements, found %d", i + 1, currentLine.size()));

        String label = currentLine.get(0);
        String lookupKey = currentLine.get(1);
        DateTime.parse(currentLine.get(2)); // This is the insertion time, currently unused.
        builder.put(label, lookupKey);
    }

    return ClaimsListShard.create(creationTime, builder.build());
}

From source file:google.registry.tmch.LordnLog.java

License:Open Source License

/** Turns lines of NORDN log returned by MarksDB into a data structure. */
public static LordnLog parse(List<String> lines) {
    // First line: <version>,<LORDN Log creation datetime>,<LORDN file creation datetime>,
    //             <LORDN Log Identifier>,<Status flag>,<Warning flag>,<Number of DN Lines>
    List<String> firstLine = Splitter.on(',').splitToList(lines.get(0));
    checkArgument(firstLine.size() == 7,
            String.format("Line 1: Expected 7 elements, found %d", firstLine.size()));

    // +  <version>, version of the file, this field MUST be 1.
    int version = Integer.parseInt(firstLine.get(0));
    checkArgument(version == 1, String.format("Line 1: Expected version 1, found %d", version));

    // +  <LORDN Log creation datetime>, date and time in UTC that the
    //    LORDN Log was created.
    DateTime logCreation = DateTime.parse(firstLine.get(1));

    // +  <LORDN file creation datetime>, date and time in UTC of
    //    creation for the LORDN file that this log file is referring
    //    to./* w  w w.j a v  a 2 s .c o  m*/
    DateTime lordnCreation = DateTime.parse(firstLine.get(2));

    // +  <LORDN Log Identifier>, unique identifier of the LORDN Log
    //    provided by the TMDB.  This identifier could be used by the
    //    Registry Operator to unequivocally identify the LORDN Log.
    //    The identified will be a string of a maximum LENGTH of 60
    //    characters from the Base 64 alphabet.
    String logId = firstLine.get(3);
    checkArgument(LOG_ID_PATTERN.matcher(logId).matches(), "Line 1: Log ID does not match base64 pattern: %s",
            logId);

    // +  <Status flag>, whether the LORDN file has been accepted for
    //    processing by the TMDB.  Possible values are "accepted" or
    //    "rejected".
    Status status = Status.valueOf(Ascii.toUpperCase(firstLine.get(4)));

    // +  <Warning flag>, whether the LORDN Log has any warning result
    //    codes.  Possible values are "no-warnings" or "warnings-
    //    present".
    boolean hasWarnings = !"no-warnings".equals(firstLine.get(5));

    // +  <Number of DN Lines>, number of DNs effective allocations
    //    processed in the LORDN file.
    int dnLines = Integer.parseInt(firstLine.get(6));
    int actual = lines.size() - 2;
    checkArgument(dnLines == actual, "Line 1: Number of entries (%s) differs from declaration (%s)",
            String.valueOf(actual), String.valueOf(dnLines));

    // Second line contains headers: roid,result-code
    checkArgument(lines.get(1).equals("roid,result-code"), "Line 2: Unexpected header list: %s", lines.get(1));

    // Subsequent lines: <roid>,<result code>
    ImmutableMap.Builder<String, Result> builder = new ImmutableMap.Builder<>();
    for (int i = 2; i < lines.size(); i++) {
        List<String> currentLine = Splitter.on(',').splitToList(lines.get(i));
        checkArgument(currentLine.size() == 2,
                String.format("Line %d: Expected 2 elements, found %d", i + 1, currentLine.size()));
        String roid = currentLine.get(0);
        int code = Integer.parseInt(currentLine.get(1));
        Result result = checkNotNull(RESULTS.get(code), "Line %s: Unknown result code: %s", i, code);
        builder.put(roid, result);
    }

    return new LordnLog(logId, status, logCreation, lordnCreation, hasWarnings, builder.build());
}

From source file:google.registry.tmch.SmdrlCsvParser.java

License:Open Source License

/** Converts the lines from the DNL CSV file into a data structure. */
public static SignedMarkRevocationList parse(List<String> lines) {
    ImmutableMap.Builder<String, DateTime> revokes = new ImmutableMap.Builder<>();

    // First line: <version>,<SMD Revocation List creation datetime>
    List<String> firstLine = Splitter.on(',').splitToList(lines.get(0));
    checkArgument(firstLine.size() == 2,
            String.format("Line 1: Expected 2 elements, found %d", firstLine.size()));
    Integer version = Integer.valueOf(firstLine.get(0));
    checkArgument(version == 1, String.format("Line 1: Expected version 1, found %d", version));
    DateTime creationTime = DateTime.parse(firstLine.get(1)).withZone(UTC);

    // Second line contains headers: smd-id,insertion-datetime
    List<String> secondLine = Splitter.on(',').splitToList(lines.get(1));
    checkArgument(secondLine.size() == 2,
            String.format("Line 2: Expected 2 elements, found %d", secondLine.size()));
    checkArgument("smd-id".equals(secondLine.get(0)),
            String.format("Line 2: Expected header \"smd-id\", found \"%s\"", secondLine.get(0)));
    checkArgument("insertion-datetime".equals(secondLine.get(1)),
            String.format("Line 2: Expected header \"insertion-datetime\", found \"%s\"", secondLine.get(1)));

    // Subsequent lines: <smd-id>,<revoked SMD datetime>
    for (int i = 2; i < lines.size(); i++) {
        List<String> currentLine = Splitter.on(',').splitToList(lines.get(i));
        checkArgument(currentLine.size() == 2,
                String.format("Line %d: Expected 2 elements, found %d", i + 1, currentLine.size()));
        String smdId = currentLine.get(0);
        DateTime revokedTime = DateTime.parse(currentLine.get(1));
        revokes.put(smdId, revokedTime);
    }//from  w  w  w  .  ja  v  a2  s. c  o  m

    return SignedMarkRevocationList.create(creationTime, revokes.build());
}

From source file:google.registry.tools.server.GenerateZoneFilesAction.java

License:Open Source License

@Override
public Map<String, Object> handleJsonRequest(Map<String, ?> json) {
    @SuppressWarnings("unchecked")
    ImmutableSet<String> tlds = ImmutableSet.copyOf((List<String>) json.get("tlds"));
    final DateTime exportTime = DateTime.parse(json.get("exportTime").toString());
    // We disallow exporting within the past 2 minutes because there might be outstanding writes.
    // We can only reliably call loadAtPointInTime at times that are UTC midnight and >
    // datastoreRetention ago in the past.
    DateTime now = clock.nowUtc();/*from  www.jav  a  2 s. c  o  m*/
    if (exportTime.isAfter(now.minusMinutes(2))) {
        throw new BadRequestException("Invalid export time: must be > 2 minutes ago");
    }
    if (exportTime.isBefore(now.minus(datastoreRetention))) {
        throw new BadRequestException(String.format("Invalid export time: must be < %d days ago",
                datastoreRetention.getStandardDays()));
    }
    if (!exportTime.equals(exportTime.toDateTime(UTC).withTimeAtStartOfDay())) {
        throw new BadRequestException("Invalid export time: must be midnight UTC");
    }
    String jobId = mrRunner.setJobName("Generate bind file stanzas").setModuleName("tools")
            .setDefaultReduceShards(tlds.size()).runMapreduce(new GenerateBindFileMapper(tlds, exportTime),
                    new GenerateBindFileReducer(bucket, exportTime, gcsBufferSize),
                    ImmutableList.of(new NullInput<EppResource>(),
                            createEntityInput(DomainResource.class, HostResource.class)));
    ImmutableList<String> filenames = FluentIterable.from(tlds).transform(new Function<String, String>() {
        @Override
        public String apply(String tld) {
            return String.format(GCS_PATH_FORMAT, bucket, String.format(FILENAME_FORMAT, tld, exportTime));
        }
    }).toList();
    return ImmutableMap.<String, Object>of("jobPath", createJobPath(jobId), "filenames", filenames);
}