1414 * limitations under the License.
1515 */
1616
17- package com .google .gcloud .examples ;
17+ package com .google .gcloud .examples . dns ;
1818
1919import com .google .common .base .Joiner ;
2020import com .google .common .collect .ImmutableList ;
2626import com .google .gcloud .dns .Zone ;
2727import com .google .gcloud .dns .ZoneInfo ;
2828
29+ import java .text .DateFormat ;
30+ import java .text .SimpleDateFormat ;
2931import java .util .Arrays ;
32+ import java .util .Date ;
3033import java .util .HashMap ;
3134import java .util .Iterator ;
3235import java .util .Map ;
3841 * <p>This example creates, deletes, gets, and lists zones, and creates and deletes DNS records of
3942 * type A.
4043 *
41- * <p>Steps needed for running the example:<ol>
44+ * <p>Steps needed for running the example:
45+ * <ol>
4246 * <li>login using gcloud SDK - {@code gcloud auth login}.</li>
4347 * <li>compile using maven - {@code mvn compile}</li>
4448 * <li>run using maven - {@code mvn exec:java
5054 * list [<zone_name> [changes [descending | ascending] | records]] |
5155 * add-record <zone_name> <record_name> <ip> <ttl> |
5256 * delete-record <zone_name> <record_name> <ip> [<ttl>] |
53- * quota</li>
57+ * quota} </li>
5458 * </ol>
5559 *
5660 * <p>The first parameter is an optional {@code project_id} (logged-in project will be used if not
57- * supplied). Second parameter is a DNS operation (list, delete, create,...) and can be used to
58- * demonstrate the usage. The remaining arguments are specific to the operation. See each action's
59- * run method for the specific interaction.
61+ * supplied). Second parameter is a DNS operation (list, delete, create,...). The remaining
62+ * arguments are specific to the operation. See each action's run method for the specific
63+ * interaction.
6064 */
6165public class DnsExample {
6266
@@ -80,10 +84,7 @@ public void run(Dns dns, String... args) {
8084 String zoneName = args [0 ];
8185 String dnsName = args [1 ];
8286 String description = args [2 ];
83- ZoneInfo zoneInfo = ZoneInfo .builder (zoneName )
84- .dnsName (dnsName )
85- .description (description )
86- .build ();
87+ ZoneInfo zoneInfo = ZoneInfo .of (zoneName , dnsName , description );
8788 Zone zone = dns .create (zoneInfo );
8889 System .out .printf ("Successfully created zone with name %s which was assigned ID %s.%n" ,
8990 zone .name (), zone .id ());
@@ -110,11 +111,14 @@ public void run(Dns dns, String... args) {
110111 Iterator <Zone > zoneIterator = dns .listZones ().iterateAll ();
111112 if (zoneIterator .hasNext ()) {
112113 System .out .println ("The project contains the following zones:" );
113- System . out . println ( "Name \t ID \t DNS Name \t Created \t Desription " );
114+ DateFormat formatter = new SimpleDateFormat ( "YYYY-MM-dd HH:mm:ss " );
114115 while (zoneIterator .hasNext ()) {
115116 Zone zone = zoneIterator .next ();
116- System .out .printf ("%s\t %s\t %s\t %s\t %s%n" , zone .name (), zone .id (), zone .dnsName (),
117- zone .creationTimeMillis (), zone .description ());
117+ System .out .printf ("%nName: %s%n" , zone .name ());
118+ System .out .printf ("ID: %s%n" , zone .id ());
119+ System .out .printf ("Description: %s%n" , zone .description ());
120+ System .out .printf ("Created: %s%n" , formatter .format (new Date (zone .creationTimeMillis ())));
121+ System .out .printf ("Name servers: %s%n" , Joiner .on (", " ).join (zone .nameServers ()));
118122 }
119123 } else {
120124 System .out .println ("Project contains no zones." );
@@ -147,8 +151,9 @@ public void run(Dns dns, String... args) {
147151 System .out .printf ("Name: %s%n" , zone .name ());
148152 System .out .printf ("ID: %s%n" , zone .id ());
149153 System .out .printf ("Description: %s%n" , zone .description ());
150- System .out .printf ("Created: %s%n" , zone .creationTimeMillis ());
151- System .out .printf ("Name servers: %s%n" , Joiner .on ("," ).join (zone .nameServers ()));
154+ DateFormat formatter = new SimpleDateFormat ("YYYY-MM-dd HH:mm:ss" );
155+ System .out .printf ("Created: %s%n" , formatter .format (new Date (zone .creationTimeMillis ())));
156+ System .out .printf ("Name servers: %s%n" , Joiner .on (", " ).join (zone .nameServers ()));
152157 }
153158 }
154159
@@ -175,7 +180,7 @@ public void run(Dns dns, String... args) {
175180 if (deleted ) {
176181 System .out .printf ("Zone %s was deleted.%n" , zoneName );
177182 } else {
178- System .out .printf ("Zone %s was NOT deleted. It probably does not exist.%n" , zoneName );
183+ System .out .printf ("Zone %s was NOT deleted. It does not exist.%n" , zoneName );
179184 }
180185 }
181186
@@ -195,35 +200,39 @@ private static class DeleteDnsRecordAction implements DnsAction {
195200
196201 /**
197202 * Deletes a DNS record of type A from the given zone. The last parameter is ttl and it is not
198- * required.
203+ * required. If ttl is not provided, a default value of 0 is used. The service requires a
204+ * precise match (including ttl) for deleting a record.
199205 */
200206 @ Override
201207 public void run (Dns dns , String ... args ) {
202208 String zoneName = args [0 ];
203209 String recordName = args [1 ];
204210 String ip = args [2 ];
211+ int ttl = 0 ;
212+ if (args .length > 3 ) {
213+ ttl = Integer .valueOf (args [3 ]);
214+ }
205215 DnsRecord record = DnsRecord .builder (recordName , DnsRecord .Type .A )
206216 .records (ImmutableList .of (ip ))
217+ .ttl (ttl , TimeUnit .SECONDS )
207218 .build ();
208- if (args .length > 3 ) {
209- Integer ttl = Integer .valueOf (args [3 ]);
210- record = record .toBuilder ().ttl (ttl , TimeUnit .SECONDS ).build ();
211- }
212219 ChangeRequest changeRequest = ChangeRequest .builder ()
213220 .delete (record )
214221 .build ();
215222 changeRequest = dns .applyChangeRequest (zoneName , changeRequest );
216223 System .out .printf ("The request for deleting A record %s for zone %s was successfully " +
217224 "submitted and assigned ID %s.%n" , recordName , zoneName , changeRequest .id ());
225+ System .out .print ("Waiting for deletion to happen..." );
218226 while (changeRequest .status ().equals (ChangeRequest .Status .PENDING )) {
227+ System .out .print ("." );
219228 try {
220229 Thread .sleep (500 );
221230 } catch (InterruptedException e ) {
222231 System .err .println ("Thread was interrupted while waiting." );
223232 }
224233 changeRequest = dns .getChangeRequest (zoneName , changeRequest .id ());
225234 }
226- System .out .printf ("The deletion has been completed.%n" );
235+ System .out .printf ("%nThe deletion has been completed.%n" );
227236 }
228237
229238 @ Override
@@ -234,11 +243,8 @@ public String params() {
234243 @ Override
235244 public boolean check (String ... args ) {
236245 if (args .length == 4 ) {
237- try {
238- Integer .valueOf (args [3 ]);
239- } catch (Exception ex ) {
240- throw new IllegalArgumentException (ex );
241- }
246+ // to check that it can be parsed
247+ Integer .valueOf (args [3 ]);
242248 return true ;
243249 } else {
244250 return args .length == 3 ;
@@ -249,27 +255,31 @@ public boolean check(String... args) {
249255 private static class AddDnsRecordAction implements DnsAction {
250256
251257 /**
252- * Adds a DNS record of type A. The last parameter is ttl and is not required.
258+ * Adds a DNS record of type A. The last parameter is ttl and is not required. If ttl is not
259+ * provided, a default value of 0 will be used.
253260 */
254261 @ Override
255262 public void run (Dns dns , String ... args ) {
256263 String zoneName = args [0 ];
257264 String recordName = args [1 ];
258265 String ip = args [2 ];
266+ int ttl = 0 ;
267+ if (args .length > 3 ) {
268+ ttl = Integer .valueOf (args [3 ]);
269+ }
259270 DnsRecord record = DnsRecord .builder (recordName , DnsRecord .Type .A )
260271 .records (ImmutableList .of (ip ))
272+ .ttl (ttl , TimeUnit .SECONDS )
261273 .build ();
262- if (args .length > 3 ) {
263- Integer ttl = Integer .valueOf (args [3 ]);
264- record = record .toBuilder ().ttl (ttl , TimeUnit .SECONDS ).build ();
265- }
266274 ChangeRequest changeRequest = ChangeRequest .builder ()
267275 .add (record )
268276 .build ();
269277 changeRequest = dns .applyChangeRequest (zoneName , changeRequest );
270278 System .out .printf ("The request for adding A record %s for zone %s was successfully " +
271279 "submitted and assigned ID %s.%n" , recordName , zoneName , changeRequest .id ());
280+ System .out .print ("Waiting for deletion to happen..." );
272281 while (changeRequest .status ().equals (ChangeRequest .Status .PENDING )) {
282+ System .out .print ("." );
273283 try {
274284 Thread .sleep (500 );
275285 } catch (InterruptedException e ) {
@@ -288,11 +298,8 @@ public String params() {
288298 @ Override
289299 public boolean check (String ... args ) {
290300 if (args .length == 4 ) {
291- try {
292- Integer .valueOf (args [3 ]);
293- } catch (Exception ex ) {
294- throw new IllegalArgumentException (ex );
295- }
301+ // to check that it can be parsed
302+ Integer .valueOf (args [3 ]);
296303 return true ;
297304 } else {
298305 return args .length == 3 ;
@@ -311,11 +318,10 @@ public void run(Dns dns, String... args) {
311318 Iterator <DnsRecord > iterator = dns .listDnsRecords (zoneName ).iterateAll ();
312319 if (iterator .hasNext ()) {
313320 System .out .printf ("DNS records for zone %s:%n" , zoneName );
314- System .out .printf ("Record name\t TTL\t Records%n" );
315321 while (iterator .hasNext ()) {
316322 DnsRecord record = iterator .next ();
317- System .out .printf ("%s \t %s \t % s%n" , record .name (), record . ttl (),
318- Joiner .on ("," ).join (record .records ()));
323+ System .out .printf ("%nRecord name: %s%nTTL: %s%nRecords: % s%n" , record .name (),
324+ record . ttl (), Joiner .on (", " ).join (record .records ()));
319325 }
320326 } else {
321327 System .out .printf ("Zone %s has no DNS records.%n" , zoneName );
@@ -352,12 +358,14 @@ public void run(Dns dns, String... args) {
352358 }
353359 if (iterator .hasNext ()) {
354360 System .out .printf ("Change requests for zone %s:%n" , zoneName );
355- System . out . printf ( "ID \t Status \t Timestamp%n " );
361+ DateFormat formatter = new SimpleDateFormat ( "YYYY-MM-dd HH:mm:ss " );
356362 while (iterator .hasNext ()) {
357363 ChangeRequest change = iterator .next ();
358- System .out .printf ("%s\t %s\t %s%n" , change .id (), change .status (), change .startTimeMillis ());
359- System .out .printf ("\t Deletions: %s%n" , Joiner .on ("," ).join (change .deletions ()));
360- System .out .printf ("\t Additions: %s%n" , Joiner .on ("," ).join (change .additions ()));
364+ System .out .printf ("%nID: %s%n" , change .id ());
365+ System .out .printf ("Status: %s%n" , change .status ());
366+ System .out .printf ("Started: %s%n" , formatter .format (change .startTimeMillis ()));
367+ System .out .printf ("Deletions: %s%n" , Joiner .on (", " ).join (change .deletions ()));
368+ System .out .printf ("Additions: %s%n" , Joiner .on (", " ).join (change .additions ()));
361369 }
362370 } else {
363371 System .out .printf ("Zone %s has no change requests.%n" , zoneName );
@@ -371,9 +379,9 @@ public String params() {
371379
372380 @ Override
373381 public boolean check (String ... args ) {
374- System .err .println (Arrays .asList (args ));
375382 return args .length == 2
376- || (args .length == 3 && ImmutableList .of ("descending" , "ascending" ).contains (args [2 ]));
383+ || (args .length == 3
384+ && ImmutableList .of ("descending" , "ascending" ).contains (args [2 ].toLowerCase ()));
377385 }
378386 }
379387
@@ -400,7 +408,7 @@ public void run(Dns dns, String... args) {
400408
401409 @ Override
402410 public boolean check (String ... args ) {
403- if (args .length == 0 || args . length == 1 ) {
411+ if (args .length == 0 ) {
404412 return true ;
405413 }
406414 if ("records" .equals (args [1 ])) {
@@ -423,15 +431,16 @@ private static class GetProjectAction implements DnsAction {
423431 @ Override
424432 public void run (Dns dns , String ... args ) {
425433 ProjectInfo project = dns .getProject ();
434+ ProjectInfo .Quota quota = project .quota ();
426435 System .out .printf ("Project id: %s%nQuota:%n" , dns .options ().projectId ());
427- System .out .printf ("\t Zones: %d%n" , project . quota () .zones ());
428- System .out .printf ("\t DNS records per zone: %d%n" , project . quota () .rrsetsPerZone ());
436+ System .out .printf ("\t Zones: %d%n" , quota .zones ());
437+ System .out .printf ("\t DNS records per zone: %d%n" , quota .rrsetsPerZone ());
429438 System .out .printf ("\t Record sets per DNS record: %d%n" ,
430- project . quota () .resourceRecordsPerRrset ());
431- System .out .printf ("\t Additions per change: %d%n" , project . quota () .rrsetAdditionsPerChange ());
432- System .out .printf ("\t Deletions per change: %d%n" , project . quota () .rrsetDeletionsPerChange ());
439+ quota .resourceRecordsPerRrset ());
440+ System .out .printf ("\t Additions per change: %d%n" , quota .rrsetAdditionsPerChange ());
441+ System .out .printf ("\t Deletions per change: %d%n" , quota .rrsetDeletionsPerChange ());
433442 System .out .printf ("\t Total data size per change: %d%n" ,
434- project . quota () .totalRrdataSizePerChange ());
443+ quota .totalRrdataSizePerChange ());
435444 }
436445
437446 @ Override
@@ -458,7 +467,7 @@ public boolean check(String... args) {
458467 private static void printUsage () {
459468 StringBuilder actionAndParams = new StringBuilder ();
460469 for (Map .Entry <String , DnsAction > entry : ACTIONS .entrySet ()) {
461- actionAndParams .append ('\t' ). append ( System .lineSeparator ()).append (entry .getKey ());
470+ actionAndParams .append (System .lineSeparator ()). append ( '\t' ).append (entry .getKey ());
462471 String param = entry .getValue ().params ();
463472 if (param != null && !param .isEmpty ()) {
464473 actionAndParams .append (' ' ).append (param );
@@ -474,25 +483,23 @@ public static void main(String... args) throws Exception {
474483 printUsage ();
475484 return ;
476485 }
477- DnsOptions . Builder optionsBuilder = DnsOptions . builder () ;
486+ String projectId = null ;
478487 DnsAction action ;
479488 String actionName ;
480489 if (args .length >= 2 && !ACTIONS .containsKey (args [0 ])) {
481490 actionName = args [1 ];
482- optionsBuilder .projectId (args [0 ]);
483- action = ACTIONS .get (args [1 ]);
491+ projectId = args [0 ];
484492 args = Arrays .copyOfRange (args , 2 , args .length );
485493 } else {
486494 actionName = args [0 ];
487- action = ACTIONS .get (args [0 ]);
488495 args = Arrays .copyOfRange (args , 1 , args .length );
489496 }
497+ action = ACTIONS .get (actionName );
490498 if (action == null ) {
491- System .out .println ("Unrecognized action." );
499+ System .out .printf ("Unrecognized action %s.%n" , actionName );
492500 printUsage ();
493501 return ;
494502 }
495- Dns dns = optionsBuilder .build ().service ();
496503 boolean valid = false ;
497504 try {
498505 valid = action .check (args );
@@ -507,6 +514,11 @@ public static void main(String... args) throws Exception {
507514 return ;
508515 }
509516 if (valid ) {
517+ DnsOptions .Builder optionsBuilder = DnsOptions .builder ();
518+ if (projectId != null ) {
519+ optionsBuilder .projectId (projectId );
520+ }
521+ Dns dns = optionsBuilder .build ().service ();
510522 action .run (dns , args );
511523 } else {
512524 System .out .println ("Invalid input for action '" + actionName + "'" );
0 commit comments