1 package org.kuali.common.dns.util;
2
3 import static java.lang.String.format;
4 import static org.kuali.common.util.base.Precondition.checkNotNull;
5 import static org.kuali.common.util.log.Loggers.newLogger;
6
7 import org.kuali.common.dns.api.DnsService;
8 import org.kuali.common.dns.model.CNAMEContext;
9 import org.kuali.common.dns.model.SimpleDnsRecord;
10 import org.kuali.common.util.execute.Executable;
11 import org.slf4j.Logger;
12
13 import com.google.common.base.Optional;
14
15 public final class CreateOrReplaceCNAME implements Executable {
16
17 private static final Logger logger = newLogger();
18
19 public CreateOrReplaceCNAME(DnsService service, CNAMEContext context) {
20 this(service, context, false);
21 }
22
23 public CreateOrReplaceCNAME(DnsService service, CNAMEContext context, boolean skip) {
24 this.service = checkNotNull(service, "service");
25 this.context = checkNotNull(context, "context");
26 this.skip = skip;
27 }
28
29 private final DnsService service;
30 private final CNAMEContext context;
31 private final boolean skip;
32
33 @Override
34 public void execute() {
35
36
37 if (skip) {
38 return;
39 }
40
41
42 Optional<SimpleDnsRecord> record = service.getCNAMERecord(context.getAliasFQDN());
43
44
45 if (existsAndMatches(record)) {
46 return;
47 }
48
49
50 if (record.isPresent()) {
51
52
53 logger.info(format("deleting cname record for [%s]", context.getAliasFQDN()));
54 service.deleteCNAMERecord(context.getAliasFQDN());
55 }
56
57
58
59 logger.info(format("creating cname record for [%s] -> [%s]", context.getAliasFQDN(), context.getCanonicalFQDN()));
60 service.createCNAMERecord(context.getAliasFQDN(), context.getCanonicalFQDN(), context.getTimeToLiveInSeconds());
61 }
62
63 private boolean existsAndMatches(Optional<SimpleDnsRecord> record) {
64 if (!record.isPresent()) {
65 return false;
66 }
67 String existingValue = record.get().getValue();
68 String cnameRecordValue = service.getCNAMERecordValueFromFQDN(context.getCanonicalFQDN());
69 return cnameRecordValue.equals(existingValue);
70 }
71
72 public DnsService getService() {
73 return service;
74 }
75
76 public boolean isSkip() {
77 return skip;
78 }
79
80 public CNAMEContext getContext() {
81 return context;
82 }
83
84 }