index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/rdata/NAPTRDataTest.java | package denominator.model.rdata;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static denominator.model.ResourceRecordSets.naptr;
public class NAPTRDataTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testGoodRecord() {
naptr("www.denominator.io.", "1 1 U E2U+sip !^.*$!sip:customer-service@example.com! .");
}
@Test
public void testMissingParts() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("record must have exactly six parts");
naptr("www.denominator.io.", "1 1 U E2U+sip");
}
}
| 200 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/rdata/CNAMEDataTest.java | package denominator.model.rdata;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static denominator.model.ResourceRecordSets.cname;
public class CNAMEDataTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testNullTarget() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("record");
cname("www.denominator.io.", (String) null);
}
}
| 201 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/rdata/SSHFPDataTest.java | package denominator.model.rdata;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static denominator.model.ResourceRecordSets.sshfp;
public class SSHFPDataTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testGoodRecord() {
sshfp("www.denominator.io.", "1 1 B33F");
}
@Test
public void testMissingParts() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("record must have exactly three parts");
sshfp("www.denominator.io.", "1");
}
}
| 202 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/rdata/SRVDataTest.java | package denominator.model.rdata;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static denominator.model.ResourceRecordSets.srv;
public class SRVDataTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testGoodRecord() {
srv("www.denominator.io.", "0 1 80 www.foo.com.");
}
@Test
public void testMissingParts() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("record must have exactly four parts");
srv("www.denominator.io.", "0 1 80");
}
}
| 203 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/rdata/NSDataTest.java | package denominator.model.rdata;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static denominator.model.ResourceRecordSets.ns;
public class NSDataTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testNullTargetNS() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("record");
ns("www.denominator.io.", (String) null);
}
}
| 204 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/rdata/SPFDataTest.java | package denominator.model.rdata;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static denominator.model.ResourceRecordSets.spf;
public class SPFDataTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testSinglePart() {
spf("www.denominator.io.", "v=spf1 a mx -all");
}
@Test
public void testMultiPart() {
spf("www.denominator.io.", "\"v=spf1 a mx -all\" \"v=spf1 aaaa mx -all\"");
}
}
| 205 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/rdata/MXDataTest.java | package denominator.model.rdata;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static denominator.model.ResourceRecordSets.mx;
public class MXDataTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testGoodRecord() {
mx("www.denominator.io.", "1 mx1.denominator.io.");
}
@Test
public void testMissingParts() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("record must have exactly two parts");
mx("www.denominator.io.", "1");
}
}
| 206 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/profile/GeoTest.java | package denominator.model.profile;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
public class GeoTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void immutableRegions() {
thrown.expect(UnsupportedOperationException.class);
Map<String, Collection<String>> regions = new LinkedHashMap<String, Collection<String>>();
regions.put("US", Arrays.asList("US-VA", "US-CA"));
Geo geo = Geo.create(regions);
geo.regions().remove("US");
}
}
| 207 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/profile/GeosTest.java | package denominator.model.profile;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import denominator.model.ResourceRecordSet;
import denominator.model.rdata.AData;
import static denominator.assertj.ModelAssertions.assertThat;
public class GeosTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
Geo geo = Geo.create(new LinkedHashMap<String, Collection<String>>() {
{
put("US", Arrays.asList("US-VA", "US-CA"));
put("IM", Arrays.asList("IM"));
}
});
ResourceRecordSet<AData> geoRRS = ResourceRecordSet.<AData>builder()//
.name("www.denominator.io.")//
.type("A")//
.qualifier("US-East")//
.ttl(3600)//
.add(AData.create("1.1.1.1"))//
.geo(geo).build();
Weighted weighted = Weighted.create(2);
ResourceRecordSet<AData> weightedRRS = ResourceRecordSet.<AData>builder()//
.name("www.denominator.io.")//
.type("A")//
.qualifier("US-East")//
.ttl(3600)//
.add(AData.create("1.1.1.1"))//
.weighted(Weighted.create(2)).build();
@Test
public void withAdditionalRegionsIdentityWhenAlreadyHaveRegions() {
assertThat(Geos.withAdditionalRegions(geoRRS, geo.regions())).isEqualTo(geoRRS);
}
@Test
public void withAdditionalRegionsAddsNewTerritory() {
Map<String, Collection<String>> oregon = new LinkedHashMap<String, Collection<String>>();
oregon.put("US", Arrays.asList("US-OR"));
ResourceRecordSet<?> withOregon = Geos.withAdditionalRegions(geoRRS, oregon);
assertThat(withOregon)
.containsRegion("US", "US-VA", "US-CA", "US-OR")
.containsRegion("IM", "IM");
}
@Test
public void withAdditionalRegionsAddsNewRegion() {
Map<String, Collection<String>> gb = new LinkedHashMap<String, Collection<String>>();
gb.put("GB", Arrays.asList("GB-SLG", "GB-LAN"));
ResourceRecordSet<?> withGB = Geos.withAdditionalRegions(geoRRS, gb);
assertThat(withGB)
.containsRegion("US", "US-VA", "US-CA")
.containsRegion("IM", "IM")
.containsRegion("GB", "GB-SLG", "GB-LAN");
}
@Test
public void withAdditionalRegionsDoesntAffectOtherProfiles() {
ResourceRecordSet<AData> geoRRS = ResourceRecordSet.<AData>builder()//
.name("www.denominator.io.")//
.type("A")//
.qualifier("US-East")//
.ttl(3600)//
.add(AData.create("1.1.1.1"))//
.weighted(weighted)
.geo(geo).build();
Map<String, Collection<String>> oregon = new LinkedHashMap<String, Collection<String>>();
oregon.put("US", Arrays.asList("US-OR"));
ResourceRecordSet<?> withOregon = Geos.withAdditionalRegions(geoRRS, oregon);
assertThat(withOregon)
.containsRegion("US", "US-VA", "US-CA", "US-OR")
.containsRegion("IM", "IM");
assertThat(withOregon.weighted()).isEqualTo(weighted);
}
@Test
public void withAdditionalRegionsEmpty() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("no regions specified");
Geos.withAdditionalRegions(geoRRS, Collections.<String, Collection<String>>emptyMap());
}
@Test
public void withAdditionalRegionsNoGeoProfile() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("rrset does not include geo configuration:");
Geos.withAdditionalRegions(weightedRRS, geo.regions());
}
}
| 208 |
0 | Create_ds/denominator/model/src/test/java/denominator/model | Create_ds/denominator/model/src/test/java/denominator/model/profile/WeightedTest.java | package denominator.model.profile;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class WeightedTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testInvalidWeight() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("weight must be positive");
Weighted.create(-1);
}
}
| 209 |
0 | Create_ds/denominator/model/src/main/java | Create_ds/denominator/model/src/main/java/denominator/ResourceTypeToValue.java | package denominator;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.Map;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Some apis use numerical type value of a resource record rather than their names. This class helps
* convert the numerical values to what people more commonly use. Note that this does not complain a
* complete mapping and may need updates over time.
*/
public class ResourceTypeToValue {
private static Map<String, Integer> lookup = new LinkedHashMap<String, Integer>();
private static Map<Integer, String> inverse = new LinkedHashMap<Integer, String>();
static {
for (ResourceTypes r : EnumSet.allOf(ResourceTypes.class)) {
lookup.put(r.name(), r.value);
inverse.put(r.value, r.name());
}
}
/**
* look up the value (ex. {@code 28}) for the mnemonic name (ex. {@code AAAA} ).
*
* @param type type to look up. ex {@code AAAA}
* @throws IllegalArgumentException if the type was not configured.
*/
public static Integer lookup(String type) throws IllegalArgumentException {
checkNotNull(type, "resource type was null");
checkArgument(lookup.containsKey(type), "%s do not include %s; types: %s",
ResourceTypes.class.getSimpleName(),
type, EnumSet.allOf(ResourceTypes.class));
return lookup.get(type);
}
/**
* look up a mnemonic name (ex. {@code AAAA} ) by its value (ex. {@code 28} ).
*
* @param type type to look up. ex {@code 28}
* @throws IllegalArgumentException if the type was not configured.
*/
public static String lookup(Integer type) throws IllegalArgumentException {
checkNotNull(type, "resource type was null");
checkArgument(inverse.containsKey(type), "%s do not include %s; types: %s",
ResourceTypes.class.getSimpleName(), type, EnumSet.allOf(ResourceTypes.class));
return inverse.get(type);
}
/**
* Taken from <a href= "http://www.iana.org/assignments/dns-parameters/dns-parameters.xml#dns-parameters-3"
* >iana types</a>.
*/
// enum only to look and format prettier than fluent bimap builder calls
enum ResourceTypes {
/**
* a host address
*/
A(1),
/**
* an authoritative name server
*/
NS(2),
/**
* the canonical name for an alias
*/
CNAME(5),
/**
* marks the start of a zone of authority
*/
SOA(6),
/**
* a domain name pointer
*/
PTR(12),
/**
* mail exchange
*/
MX(15),
/**
* text strings
*/
TXT(16),
/**
* IP6 Address
*/
AAAA(28),
/**
* Location record
*/
LOC(29),
/**
* Naming Authority Pointer
*/
NAPTR(35),
/**
* Certificate record
*/
CERT(37),
/**
* Delegation signer
*/
DS(43),
/**
* SSH Public Key Fingerprint
*/
SSHFP(44),
/**
* TLSA certificate association
*/
TLSA(52),
/**
* Sender Policy Framework
*/
SPF(99),
/**
* Server Selection
*/
SRV(33);
private final int value;
ResourceTypes(int value) {
this.value = value;
}
}
}
| 210 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/common/Preconditions.java | package denominator.common;
import static java.lang.String.format;
/**
* cherry-picks from guava {@code com.google.common.base.Preconditions}.
*/
public class Preconditions {
private Preconditions() { // no instances
}
public static void checkArgument(boolean expression, String errorMessageTemplate,
Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
}
public static <T> T checkNotNull(T reference, String errorMessageTemplate,
Object... errorMessageArgs) {
if (reference == null) {
throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
public static void checkState(boolean expression, String errorMessageTemplate,
Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
}
}
}
| 211 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/common/Util.java | package denominator.common;
import java.io.IOException;
import java.io.Reader;
import java.net.InetAddress;
import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import denominator.model.rdata.AAAAData;
import denominator.model.rdata.AData;
import denominator.model.rdata.CERTData;
import denominator.model.rdata.CNAMEData;
import denominator.model.rdata.MXData;
import denominator.model.rdata.NAPTRData;
import denominator.model.rdata.NSData;
import denominator.model.rdata.PTRData;
import denominator.model.rdata.SOAData;
import denominator.model.rdata.SPFData;
import denominator.model.rdata.SRVData;
import denominator.model.rdata.SSHFPData;
import denominator.model.rdata.TXTData;
import static denominator.common.Preconditions.checkNotNull;
/**
* Utilities, inspired by or adapted from guava.
*/
public class Util {
private static final int BUF_SIZE = 0x800; // 2K chars (4K bytes)
private Util() { // no instances
}
public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* returns the {@code reader} as a string without closing it.
*/
public static String slurp(Reader reader) throws IOException {
StringBuilder to = new StringBuilder();
CharBuffer buf = CharBuffer.allocate(BUF_SIZE);
while (reader.read(buf) != -1) {
buf.flip();
to.append(buf);
buf.clear();
}
return to.toString();
}
public static String join(char delim, Object... parts) {
if (parts == null || parts.length == 0) {
return "";
}
StringBuilder to = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
to.append(parts[i]);
if (i + 1 < parts.length) {
to.append(delim);
}
}
return to.toString();
}
/**
* empty fields will result in null elements in the result.
*/
public static List<String> split(char delim, String toSplit) {
checkNotNull(toSplit, "toSplit");
if (toSplit.indexOf(delim) == -1) {
return Arrays.asList(toSplit); // sortable in JRE 7 and 8
}
List<String> out = new LinkedList<String>();
StringBuilder currentString = new StringBuilder();
for (char c : toSplit.toCharArray()) {
if (c == delim) {
out.add(emptyToNull(currentString.toString()));
currentString.setLength(0);
} else {
currentString.append(c);
}
}
out.add(emptyToNull(currentString.toString()));
return out;
}
private static String emptyToNull(String field) {
return "".equals(field) ? null : field;
}
public static <T> T nextOrNull(Iterator<T> it) {
return it.hasNext() ? it.next() : null;
}
public static <T> Iterator<T> singletonIterator(final T nullableValue) {
if (nullableValue == null) {
return (Iterator<T>) EMPTY_ITERATOR;
}
return new Iterator<T>() {
boolean done;
@Override
public boolean hasNext() {
return !done;
}
@Override
public T next() {
if (done) {
throw new NoSuchElementException();
}
done = true;
return nullableValue;
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
private static final Iterator<Object> EMPTY_ITERATOR = new Iterator<Object>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
public static <T> PeekingIterator<T> peekingIterator(final Iterator<T> iterator) {
checkNotNull(iterator, "iterator");
return new PeekingIterator<T>() {
protected T computeNext() {
if (iterator.hasNext()) {
return iterator.next();
}
return endOfData();
}
};
}
public static <T> Iterator<T> concat(final Iterator<T> first, final Iterator<T> second) {
checkNotNull(first, "first");
checkNotNull(second, "second");
return new PeekingIterator<T>() {
Iterator<? extends T> current = first;
protected T computeNext() {
if (!current.hasNext() && current != second) {
current = second;
}
while (current.hasNext()) {
T element = current.next();
if (element != null) {
return element;
}
}
return endOfData();
}
};
}
public static <T> Iterator<T> concat(final Iterable<? extends Iterable<? extends T>> i) {
final Iterator<? extends Iterable<? extends T>> inputs = checkNotNull(i, "inputs").iterator();
return new PeekingIterator<T>() {
Iterator<? extends T> current = Collections.<T>emptyList().iterator();
protected T computeNext() {
while (!current.hasNext() && inputs.hasNext()) {
current = inputs.next().iterator();
}
while (current.hasNext()) {
T element = current.next();
if (element != null) {
return element;
}
}
return endOfData();
}
};
}
public static <T> Iterator<T> filter(final Iterator<T> unfiltered,
final Filter<? super T> filter) {
checkNotNull(unfiltered, "unfiltered");
checkNotNull(filter, "filter");
return new PeekingIterator<T>() {
protected T computeNext() {
while (unfiltered.hasNext()) {
T element = unfiltered.next();
if (filter.apply(element)) {
return element;
}
}
return endOfData();
}
};
}
public static <T> Filter<T> and(final Filter<T> first, final Filter<? super T> second) {
checkNotNull(first, "first");
checkNotNull(second, "second");
return new Filter<T>() {
public boolean apply(T in) {
if (!first.apply(in)) {
return false;
}
return second.apply(in);
}
};
}
public static String flatten(Map<String, Object> input) {
Collection<Object> orderedRdataValues = input.values();
if (orderedRdataValues.size() == 1) {
Object rdata = orderedRdataValues.iterator().next();
return rdata instanceof InetAddress ? InetAddress.class.cast(rdata).getHostAddress()
: rdata.toString();
}
return join(' ', orderedRdataValues.toArray());
}
public static Map<String, Object> toMap(String type, String rdata) {
return "TXT".equals(type) ? TXTData.create(rdata) : toMap(type, Util.split(' ', rdata));
}
public static Map<String, Object> toMap(String type, List<String> parts) {
if ("A".equals(type)) {
return AData.create(parts.get(0));
} else if ("AAAA".equals(type)) {
return AAAAData.create(parts.get(0));
} else if ("CNAME".equals(type)) {
return CNAMEData.create(parts.get(0));
} else if ("MX".equals(type)) {
return MXData.create(Integer.valueOf(parts.get(0)), parts.get(1));
} else if ("NS".equals(type)) {
return NSData.create(parts.get(0));
} else if ("PTR".equals(type)) {
return PTRData.create(parts.get(0));
} else if ("SOA".equals(type)) {
return SOAData.builder().mname(parts.get(0)).rname(parts.get(1))
.serial(Integer.valueOf(parts.get(2)))
.refresh(Integer.valueOf(parts.get(3))).retry(Integer.valueOf(parts.get(4)))
.expire(Integer.valueOf(parts.get(5))).minimum(Integer.valueOf(parts.get(6))).build();
} else if ("SPF".equals(type)) {
return SPFData.create(parts.get(0));
} else if ("SRV".equals(type)) {
return SRVData.builder().priority(Integer.valueOf(parts.get(0)))
.weight(Integer.valueOf(parts.get(1)))
.port(Integer.valueOf(parts.get(2))).target(parts.get(3)).build();
} else if ("TXT".equals(type)) {
return TXTData.create(parts.get(0));
} else if ("CERT".equals(type)) {
return CERTData.builder().format(Integer.valueOf(parts.get(0)))
.tag(Integer.valueOf(parts.get(1)))
.algorithm(Integer.valueOf(parts.get(2)))
.certificate(parts.get(3))
.build();
} else if ("NAPTR".equals(type)) {
return NAPTRData.builder().order(Integer.valueOf(parts.get(0)))
.preference(Integer.valueOf(parts.get(1)))
.flags(parts.get(2))
.services(parts.get(3))
.regexp(parts.get(4))
.replacement(parts.get(5))
.build();
} else if ("SSHFP".equals(type)) {
return SSHFPData.builder().algorithm(Integer.valueOf(parts.get(0)))
.fptype(Integer.valueOf(parts.get(1)))
.fingerprint(parts.get(2))
.build();
} else {
throw new IllegalArgumentException("unsupported type: " + type);
}
}
}
| 212 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/common/PeekingIterator.java | package denominator.common;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* adapted from guava's {@code com.google.common.collect.AbstractIterator}.
*/
public abstract class PeekingIterator<T> implements Iterator<T> {
private PeekingIterator.State state = State.NOT_READY;
private T next;
/**
* Constructor for use by subclasses.
*/
protected PeekingIterator() {
}
protected abstract T computeNext();
protected final T endOfData() {
state = State.DONE;
return null;
}
@Override
public final boolean hasNext() {
switch (state) {
case DONE:
return false;
case READY:
return true;
default:
}
return tryToComputeNext();
}
private boolean tryToComputeNext() {
next = computeNext();
if (state != State.DONE) {
state = State.READY;
return true;
}
return false;
}
@Override
public final T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
state = State.NOT_READY;
return next;
}
public T peek() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private enum State {
/**
* We have computed the next element and haven't returned it yet.
*/
READY,
/**
* We haven't yet computed or have already returned the element.
*/
NOT_READY,
/**
* We have reached the end of the data and are finished.
*/
DONE,
}
}
| 213 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/common/Filter.java | package denominator.common;
/**
* adapted from guava's {@code com.google.common.base.Predicate}.
*/
public interface Filter<T> {
/**
* @param in to evaluate, could be null
* @return true if not null and should be retained.
*/
boolean apply(T in);
}
| 214 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/model/AbstractRecordSetBuilder.java | package denominator.model;
import java.util.List;
import java.util.Map;
import denominator.model.profile.Geo;
import denominator.model.profile.Weighted;
/**
* Capable of building record sets from rdata input types expressed as {@code E}
*
* @param <E> input type of rdata
* @param <D> portable type of the rdata in the {@link ResourceRecordSet}
*/
abstract class AbstractRecordSetBuilder<E, D extends Map<String, Object>, B extends AbstractRecordSetBuilder<E, D, B>> {
private String name;
private String type;
private String qualifier;
private Integer ttl;
private Geo geo;
private Weighted weighted;
/**
* @see ResourceRecordSet#name()
*/
@SuppressWarnings("unchecked")
public B name(String name) {
this.name = name;
return (B) this;
}
/**
* @see ResourceRecordSet#type()
*/
@SuppressWarnings("unchecked")
public B type(String type) {
this.type = type;
return (B) this;
}
/**
* @see ResourceRecordSet#qualifier()
*/
@SuppressWarnings("unchecked")
public B qualifier(String qualifier) {
this.qualifier = qualifier;
return (B) this;
}
/**
* @see ResourceRecordSet#ttl()
*/
@SuppressWarnings("unchecked")
public B ttl(Integer ttl) {
this.ttl = ttl;
return (B) this;
}
/**
* @see ResourceRecordSet#geo()
*/
@SuppressWarnings("unchecked")
public B geo(Geo geo) {
this.geo = geo;
return (B) this;
}
/**
* @see ResourceRecordSet#weighted()
*/
@SuppressWarnings("unchecked")
public B weighted(Weighted weighted) {
this.weighted = weighted;
return (B) this;
}
public ResourceRecordSet<D> build() {
return new ResourceRecordSet<D>(name, type, qualifier, ttl, records(), geo, weighted);
}
/**
* aggregate collected rdata values
*/
protected abstract List<D> records();
}
| 215 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/model/NumbersAreUnsignedIntsLinkedHashMap.java | package denominator.model;
import java.util.LinkedHashMap;
/**
* Ensures we don't accidentally serialize whole numbers as floats.
*/
public class NumbersAreUnsignedIntsLinkedHashMap extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
protected NumbersAreUnsignedIntsLinkedHashMap() {
}
// only overriding put, as putAll uses this, and we aren't exposing
// a ctor that allows passing a map.
@Override
public Object put(String key, Object val) {
val = val != null && val instanceof Number ? Number.class.cast(val).intValue() : val;
return super.put(key, val);
}
}
| 216 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/model/Zones.java | package denominator.model;
import denominator.common.Filter;
import static denominator.common.Preconditions.checkNotNull;
/**
* Static utility methods for {@code Zone} instances.
*/
public final class Zones {
/**
* Evaluates to true if the input {@link denominator.model.Zone} exists with {@link
* denominator.model.Zone#name() name} corresponding to the {@code name} parameter.
*
* @param name the {@link denominator.model.Zone#name() name} of the desired zone.
*/
public static Filter<Zone> nameEqualTo(final String name) {
checkNotNull(name, "name");
return new Filter<Zone>() {
@Override
public boolean apply(Zone in) {
return in != null && name.equals(in.name());
}
@Override
public String toString() {
return "nameEqualTo(" + name + ")";
}
};
}
private Zones() {
}
}
| 217 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/model/StringRecordBuilder.java | package denominator.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import denominator.model.rdata.CNAMEData;
import static denominator.common.Preconditions.checkNotNull;
/**
* Capable of building record sets where rdata types more easily expressed as Strings, such as
* {@link CNAMEData}
*
* @param <D> portable type of the rdata in the {@link ResourceRecordSet}
*/
abstract class StringRecordBuilder<D extends Map<String, Object>> extends
AbstractRecordSetBuilder<String, D, StringRecordBuilder<D>> {
private List<D> records = new ArrayList<D>();
/**
* adds a value to the builder.
*
* ex.
*
* <pre>
* builder.add("192.0.2.1");
* </pre>
*/
public StringRecordBuilder<D> add(String record) {
this.records.add(apply(checkNotNull(record, "record")));
return this;
}
/**
* adds values to the builder
*
* ex.
*
* <pre>
* builder.addAll("192.0.2.1", "192.0.2.2");
* </pre>
*/
public StringRecordBuilder<D> addAll(String... records) {
return addAll(Arrays.asList(checkNotNull(records, "records")));
}
/**
* adds a value to the builder.
*
* ex.
*
* <pre>
* builder.addAll("192.0.2.1", "192.0.2.2");
* </pre>
*/
public StringRecordBuilder<D> addAll(Collection<String> records) {
for (String value : checkNotNull(records, "records")) {
add(value);
}
return this;
}
@Override
protected List<D> records() {
return records;
}
/**
* Override to properly convert the input to a string-based RData value;
*/
protected abstract D apply(String in);
}
| 218 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/model/ResourceRecordSet.java | package denominator.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import denominator.model.profile.Geo;
import denominator.model.profile.Weighted;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
import static denominator.common.Util.equal;
/**
* A grouping of resource records by name and type. In implementation, this is an unmodifiable list
* of rdata values corresponding to records sharing the same {@link #name() name} and {@link
* #type}.
*
* @param <D> RData type shared across elements. This may be empty in the case of special profile
* such as `alias`.
*
* See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public class ResourceRecordSet<D extends Map<String, Object>> {
private final String name;
private final String type;
private final String qualifier;
private final Integer ttl;
private final List<D> records;
private final Geo geo;
private final Weighted weighted;
ResourceRecordSet(String name, String type, String qualifier, Integer ttl, List<D> records,
Geo geo, Weighted weighted) {
checkArgument(checkNotNull(name, "name").length() <= 255, "Name must be <= 255 characters");
this.name = name;
this.type = checkNotNull(type, "type of %s", name);
this.qualifier = qualifier;
if (ttl != null) {
boolean rfc2181 = ttl >= 0 && ttl.longValue() <= 0x7FFFFFFFL;
checkArgument(rfc2181, "Invalid ttl value: %s, must be 0-2147483647", ttl);
}
this.ttl = ttl;
this.records =
Collections.unmodifiableList(records != null ? records : Collections.<D>emptyList());
this.geo = geo;
this.weighted = weighted;
}
public static <D extends Map<String, Object>> Builder<D> builder() {
return new Builder<D>();
}
/**
* an owner name, i.e., the name of the node to which this resource record pertains.
*
* @since 1.3
*/
public String name() {
return name;
}
/**
* The mnemonic type of the record. ex {@code CNAME}
*
* @since 1.3
*/
public String type() {
return type;
}
/**
* A user-defined identifier that differentiates among multiple resource record sets that have the
* same combination of DNS name and type. Only present when there's a {@link Geo geo} or {@link
* Weighted} profile which affects visibility to resolvers.
*
* @return qualifier or null.
* @since 1.3
*/
public String qualifier() {
return qualifier;
}
/**
* Indicates the time interval that the resource record may be cached. Zero implies it is not
* cached. Absent means use whatever the default is.
*
* <p/>Caution: The concept of a default TTL varies per provider. Some providers use the SOA's
* ttl, others an account default by record type, and others are hard-coded. It is best to always
* pass ttl explicitly.
*
* @return ttl or null.
* @since 1.3
*/
public Integer ttl() {
return ttl;
}
/**
* When present, this record set has a {@link #qualifier() qualifier} and is visible to a subset
* of all {@link Geo#regions() regions}.
*
* <br> For example, if this record set is intended for resolvers in Utah, the geo profile would
* be present and its {@link denominator.model.profile.Geo#regions() regions} might contain `Utah`
* or `US-UT`.
*
* @return geo profile or null.
* @since 3.7
*/
public Geo geo() {
return geo;
}
/**
* When present, this record set has a {@link #qualifier() qualifier} and is served to its {@link
* Weighted#weight() weight}.
*
* @return geo profile or null.
* @since 3.7
*/
public Weighted weighted() {
return weighted;
}
/**
* RData type shared across elements. This may be empty in the case of special profile such as
* `alias`.
*
* @since 2.3
*/
public List<D> records() {
return records;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ResourceRecordSet) {
ResourceRecordSet<?> other = (ResourceRecordSet) obj;
return equal(name(), other.name())
&& equal(type(), other.type())
&& equal(qualifier(), other.qualifier())
&& equal(ttl(), other.ttl())
&& equal(records(), other.records())
&& equal(geo(), other.geo())
&& equal(weighted(), other.weighted());
}
return false;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name().hashCode();
result = 31 * result + type().hashCode();
result = 31 * result + (qualifier() != null ? qualifier().hashCode() : 0);
result = 31 * result + (ttl() != null ? ttl().hashCode() : 0);
result = 31 * result + records().hashCode();
result = 31 * result + (geo() != null ? geo().hashCode() : 0);
result = 31 * result + (weighted() != null ? weighted().hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ResourceRecordSet [");
builder.append("name=").append(name());
builder.append(", ").append("type=").append(type());
if (qualifier() != null) {
builder.append(", ").append("qualifier=").append(qualifier());
}
if (ttl() != null) {
builder.append(", ").append("ttl=").append(ttl());
}
builder.append(", ").append("records=").append(records());
if (geo() != null) {
builder.append(", ").append("geo=").append(geo());
}
if (weighted() != null) {
builder.append(", ").append("weighted=").append(weighted());
}
builder.append("]");
return builder.toString();
}
/**
* Allows creation or mutation of record sets based on the portable RData form {@code D} as
* extends {@code Map<String, Object>}
*
* @param <D> RData type shared across elements. see package {@code denominator.model.rdata}
*/
public static class Builder<D extends Map<String, Object>>
extends AbstractRecordSetBuilder<D, D, Builder<D>> {
private List<D> records = new ArrayList<D>();
/**
* adds a value to the builder.
*
* ex.
*
* <pre>
* builder.add(srvData);
* </pre>
*/
public Builder<D> add(D record) {
this.records.add(checkNotNull(record, "record"));
return this;
}
/**
* replaces all records values in the builder
*
* ex.
*
* <pre>
* builder.addAll(srvData1, srvData2);
* </pre>
*/
public Builder<D> addAll(D... records) {
this.records.addAll(Arrays.asList(checkNotNull(records, "records")));
return this;
}
/**
* replaces all records values in the builder
*
* ex.
*
* <pre>
*
* builder.addAll(otherRecordSet);
* </pre>
*/
public <R extends D> Builder<D> addAll(Collection<R> records) {
this.records.addAll(checkNotNull(records, "records"));
return this;
}
@Override
protected List<D> records() {
return records;
}
}
}
| 219 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/model/ResourceRecordSets.java | package denominator.model;
import java.util.Collection;
import java.util.Map;
import denominator.common.Filter;
import denominator.model.rdata.AAAAData;
import denominator.model.rdata.AData;
import denominator.model.rdata.CERTData;
import denominator.model.rdata.CNAMEData;
import denominator.model.rdata.MXData;
import denominator.model.rdata.NAPTRData;
import denominator.model.rdata.NSData;
import denominator.model.rdata.PTRData;
import denominator.model.rdata.SOAData;
import denominator.model.rdata.SPFData;
import denominator.model.rdata.SRVData;
import denominator.model.rdata.SSHFPData;
import denominator.model.rdata.TXTData;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Static utility methods that build {@code ResourceRecordSet} instances.
*/
public class ResourceRecordSets {
private ResourceRecordSets() {
}
public static Filter<ResourceRecordSet<?>> notNull() {
return new Filter<ResourceRecordSet<?>>() {
@Override
public boolean apply(ResourceRecordSet<?> in) {
return in != null;
}
};
}
/**
* evaluates to true if the input {@link ResourceRecordSet} exists with {@link
* ResourceRecordSet#name() name} corresponding to the {@code name} parameter.
*
* @param name the {@link ResourceRecordSet#name() name} of the desired record set
*/
public static Filter<ResourceRecordSet<?>> nameEqualTo(final String name) {
checkNotNull(name, "name");
return new Filter<ResourceRecordSet<?>>() {
@Override
public boolean apply(ResourceRecordSet<?> in) {
return in != null && name.equals(in.name());
}
@Override
public String toString() {
return "nameEqualTo(" + name + ")";
}
};
}
/**
* evaluates to true if the input {@link ResourceRecordSet} exists with {@link
* ResourceRecordSet#name() name} corresponding to the {@code name} parameter and {@link
* ResourceRecordSet#type() type} corresponding to the {@code type} parameter.
*
* @param name the {@link ResourceRecordSet#name() name} of the desired record set
* @param type the {@link ResourceRecordSet#type() type} of the desired record set
*/
public static Filter<ResourceRecordSet<?>> nameAndTypeEqualTo(final String name,
final String type) {
checkNotNull(name, "name");
checkNotNull(type, "type");
return new Filter<ResourceRecordSet<?>>() {
@Override
public boolean apply(ResourceRecordSet<?> in) {
return in != null && name.equals(in.name()) && type.equals(in.type());
}
@Override
public String toString() {
return "nameAndTypeEqualTo(" + name + "," + type + ")";
}
};
}
/**
* evaluates to true if the input {@link ResourceRecordSet} exists with {@link
* ResourceRecordSet#name() name} corresponding to the {@code name} parameter, {@link
* ResourceRecordSet#type() type} corresponding to the {@code type} parameter, and {@link
* ResourceRecordSet#qualifier() qualifier} corresponding to the {@code qualifier} parameter.
*
* @param name the {@link ResourceRecordSet#name() name} of the desired record set
* @param type the {@link ResourceRecordSet#type() type} of the desired record set
* @param qualifier the {@link ResourceRecordSet#qualifier() qualifier} of the desired record set
*/
public static Filter<ResourceRecordSet<?>> nameTypeAndQualifierEqualTo(final String name,
final String type,
final String qualifier) {
checkNotNull(name, "name");
checkNotNull(type, "type");
checkNotNull(qualifier, "qualifier");
return new Filter<ResourceRecordSet<?>>() {
@Override
public boolean apply(ResourceRecordSet<?> in) {
return in != null && name.equals(in.name()) && type.equals(in.type())
&& qualifier.equals(in.qualifier());
}
@Override
public String toString() {
return "nameTypeAndQualifierEqualTo(" + name + "," + type + "," + qualifier + ")";
}
};
}
/**
* evaluates to true if the input {@link ResourceRecordSet} exists and contains the {@code record}
* specified.
*
* @param record the record in the desired record set
*/
public static Filter<ResourceRecordSet<?>> containsRecord(Map<String, ?> record) {
return new ContainsRecord(record);
}
/**
* Returns true if the input has no visibility qualifier. Typically indicates a basic record set.
*/
public static Filter<ResourceRecordSet<?>> alwaysVisible() {
return new Filter<ResourceRecordSet<?>>() {
@Override
public boolean apply(ResourceRecordSet<?> in) {
return in != null && in.qualifier() == null;
}
@Override
public String toString() {
return "alwaysVisible()";
}
};
}
/**
* Returns an updated SOA rrset, with an incremented serial number and the specified parameters.
*/
public static ResourceRecordSet<SOAData> soa(ResourceRecordSet<?> soa, String email, int ttl) {
SOAData soaData = (SOAData) soa.records().get(0);
soaData = soaData.toBuilder().serial(soaData.serial() + 1).rname(email).build();
return ResourceRecordSet.<SOAData>builder()
.name(soa.name())
.type("SOA")
.ttl(ttl)
.add(soaData)
.build();
}
/**
* creates a set of a single {@link denominator.model.rdata.AData A} record for the specified
* name.
*
* @param name ex. {@code www.denominator.io.}
* @param address ex. {@code 192.0.2.1}
*/
public static ResourceRecordSet<AData> a(String name, String address) {
return new ABuilder().name(name).add(address).build();
}
/**
* creates a set of a single {@link denominator.model.rdata.AData A} record for the specified name
* and ttl.
*
* @param name ex. {@code www.denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param address ex. {@code 192.0.2.1}
*/
public static ResourceRecordSet<AData> a(String name, int ttl, String address) {
return new ABuilder().name(name).ttl(ttl).add(address).build();
}
/**
* creates a set of {@link denominator.model.rdata.AData A} records for the specified name.
*
* @param name ex. {@code www.denominator.io.}
* @param addresses address values ex. {@code [192.0.2.1, 192.0.2.2]}
*/
public static ResourceRecordSet<AData> a(String name, Collection<String> addresses) {
return new ABuilder().name(name).addAll(addresses).build();
}
/**
* creates a set of {@link denominator.model.rdata.AData A} records for the specified name and
* ttl.
*
* @param name ex. {@code www.denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param addresses address values ex. {@code [192.0.2.1, 192.0.2.2]}
*/
public static ResourceRecordSet<AData> a(String name, int ttl, Collection<String> addresses) {
return new ABuilder().name(name).ttl(ttl).addAll(addresses).build();
}
/**
* creates aaaa set of aaaa single {@link denominator.model.rdata.AAAAData AAAA} record for the
* specified name.
*
* @param name ex. {@code www.denominator.io.}
* @param address ex. {@code 1234:ab00:ff00::6b14:abcd}
*/
public static ResourceRecordSet<AAAAData> aaaa(String name, String address) {
return new AAAABuilder().name(name).add(address).build();
}
/**
* creates aaaa set of aaaa single {@link denominator.model.rdata.AAAAData AAAA} record for the
* specified name and ttl.
*
* @param name ex. {@code www.denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param address ex. {@code 1234:ab00:ff00::6b14:abcd}
*/
public static ResourceRecordSet<AAAAData> aaaa(String name, int ttl, String address) {
return new AAAABuilder().name(name).ttl(ttl).add(address).build();
}
/**
* creates aaaa set of {@link denominator.model.rdata.AAAAData AAAA} records for the specified
* name.
*
* @param name ex. {@code www.denominator.io.}
* @param addresses address values ex. {@code [1234:ab00:ff00::6b14:abcd,
* 5678:ab00:ff00::6b14:abcd]}
*/
public static ResourceRecordSet<AAAAData> aaaa(String name, Collection<String> addresses) {
return new AAAABuilder().name(name).addAll(addresses).build();
}
/**
* creates aaaa set of {@link denominator.model.rdata.AAAAData AAAA} records for the specified
* name and ttl.
*
* @param name ex. {@code www.denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param addresses address values ex. {@code [1234:ab00:ff00::6b14:abcd,
* 5678:ab00:ff00::6b14:abcd]}
*/
public static ResourceRecordSet<AAAAData> aaaa(String name, int ttl,
Collection<String> addresses) {
return new AAAABuilder().name(name).ttl(ttl).addAll(addresses).build();
}
/**
* creates cname set of cname single {@link denominator.model.rdata.CNAMEData CNAME} record for
* the specified name.
*
* @param name ex. {@code www.denominator.io.}
* @param cname ex. {@code www1.denominator.io.}
*/
public static ResourceRecordSet<CNAMEData> cname(String name, String cname) {
return new CNAMEBuilder().name(name).add(cname).build();
}
/**
* creates cname set of cname single {@link denominator.model.rdata.CNAMEData CNAME} record for
* the specified name and ttl.
*
* @param name ex. {@code www.denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param cname ex. {@code www1.denominator.io.}
*/
public static ResourceRecordSet<CNAMEData> cname(String name, int ttl, String cname) {
return new CNAMEBuilder().name(name).ttl(ttl).add(cname).build();
}
/**
* creates cname set of {@link denominator.model.rdata.CNAMEData CNAME} records for the specified
* name.
*
* @param name ex. {@code www.denominator.io.}
* @param cnames cname values ex. {@code [www1.denominator.io., www2.denominator.io.]}
*/
public static ResourceRecordSet<CNAMEData> cname(String name, Collection<String> cnames) {
return new CNAMEBuilder().name(name).addAll(cnames).build();
}
/**
* creates cname set of {@link denominator.model.rdata.CNAMEData CNAME} records for the specified
* name and ttl.
*
* @param name ex. {@code www.denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param cnames cname values ex. {@code [www1.denominator.io., www2.denominator.io.]}
*/
public static ResourceRecordSet<CNAMEData> cname(String name, int ttl,
Collection<String> cnames) {
return new CNAMEBuilder().name(name).ttl(ttl).addAll(cnames).build();
}
/**
* creates ns set of ns single {@link denominator.model.rdata.NSData NS} record for the specified
* name.
*
* @param name ex. {@code denominator.io.}
* @param nsdname ex. {@code ns1.denominator.io.}
*/
public static ResourceRecordSet<NSData> ns(String name, String nsdname) {
return new NSBuilder().name(name).add(nsdname).build();
}
/**
* creates ns set of ns single {@link denominator.model.rdata.NSData NS} record for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param nsdname ex. {@code ns1.denominator.io.}
*/
public static ResourceRecordSet<NSData> ns(String name, int ttl, String nsdname) {
return new NSBuilder().name(name).ttl(ttl).add(nsdname).build();
}
/**
* creates ns set of {@link denominator.model.rdata.NSData NS} records for the specified name.
*
* @param name ex. {@code denominator.io.}
* @param nsdnames nsdname values ex. {@code [ns1.denominator.io., ns2.denominator.io.]}
*/
public static ResourceRecordSet<NSData> ns(String name, Collection<String> nsdnames) {
return new NSBuilder().name(name).addAll(nsdnames).build();
}
/**
* creates ns set of {@link denominator.model.rdata.NSData NS} records for the specified name and
* ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param nsdnames nsdname values ex. {@code [ns1.denominator.io., ns2.denominator.io.]}
*/
public static ResourceRecordSet<NSData> ns(String name, int ttl, Collection<String> nsdnames) {
return new NSBuilder().name(name).ttl(ttl).addAll(nsdnames).build();
}
/**
* creates ptr set of ptr single {@link denominator.model.rdata.PTRData PTR} record for the
* specified name.
*
* @param name ex. {@code denominator.io.}
* @param ptrdname ex. {@code ptr1.denominator.io.}
*/
public static ResourceRecordSet<PTRData> ptr(String name, String ptrdname) {
return new PTRBuilder().name(name).add(ptrdname).build();
}
/**
* creates ptr set of ptr single {@link denominator.model.rdata.PTRData PTR} record for the
* specified name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param ptrdname ex. {@code ptr1.denominator.io.}
*/
public static ResourceRecordSet<PTRData> ptr(String name, int ttl, String ptrdname) {
return new PTRBuilder().name(name).ttl(ttl).add(ptrdname).build();
}
/**
* creates ptr set of {@link denominator.model.rdata.PTRData PTR} records for the specified name.
*
* @param name ex. {@code denominator.io.}
* @param ptrdnames ptrdname values ex. {@code [ptr1.denominator.io., ptr2.denominator.io.]}
*/
public static ResourceRecordSet<PTRData> ptr(String name, Collection<String> ptrdnames) {
return new PTRBuilder().name(name).addAll(ptrdnames).build();
}
/**
* creates ptr set of {@link denominator.model.rdata.PTRData PTR} records for the specified name
* and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param ptrdnames ptrdname values ex. {@code [ptr1.denominator.io., ptr2.denominator.io.]}
*/
public static ResourceRecordSet<PTRData> ptr(String name, int ttl, Collection<String> ptrdnames) {
return new PTRBuilder().name(name).ttl(ttl).addAll(ptrdnames).build();
}
/**
* creates spf set of spf single {@link denominator.model.rdata.SPFData SPF} record for the
* specified name.
*
* @param name ex. {@code denominator.io.}
* @param spfdata ex. {@code v=spf1 a mx -all}
*/
public static ResourceRecordSet<SPFData> spf(String name, String spfdata) {
return new SPFBuilder().name(name).add(spfdata).build();
}
/**
* creates spf set of spf single {@link denominator.model.rdata.SPFData SPF} record for the
* specified name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param spfdata ex. {@code v=spf1 a mx -all}
*/
public static ResourceRecordSet<SPFData> spf(String name, int ttl, String spfdata) {
return new SPFBuilder().name(name).ttl(ttl).add(spfdata).build();
}
/**
* creates spf set of {@link denominator.model.rdata.SPFData SPF} records for the specified name.
*
* @param name ex. {@code denominator.io.}
* @param spfdata spfdata values ex. {@code [v=spf1 a mx -all, v=spf1 ipv6 -all]}
*/
public static ResourceRecordSet<SPFData> spf(String name, Collection<String> spfdata) {
return new SPFBuilder().name(name).addAll(spfdata).build();
}
/**
* creates spf set of {@link denominator.model.rdata.SPFData SPF} records for the specified name
* and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param spfdata spfdata values ex. {@code [v=spf1 a mx -all, v=spf1 ipv6 -all]}
*/
public static ResourceRecordSet<SPFData> spf(String name, int ttl, Collection<String> spfdata) {
return new SPFBuilder().name(name).ttl(ttl).addAll(spfdata).build();
}
/**
* creates txt set of txt single {@link denominator.model.rdata.TXTData TXT} record for the
* specified name.
*
* @param name ex. {@code denominator.io.}
* @param txtdata ex. {@code "made in sweden"}
*/
public static ResourceRecordSet<TXTData> txt(String name, String txtdata) {
return new TXTBuilder().name(name).add(txtdata).build();
}
/**
* creates txt set of txt single {@link denominator.model.rdata.TXTData TXT} record for the
* specified name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param txtdata ex. {@code "made in sweden"}
*/
public static ResourceRecordSet<TXTData> txt(String name, int ttl, String txtdata) {
return new TXTBuilder().name(name).ttl(ttl).add(txtdata).build();
}
/**
* creates txt set of {@link denominator.model.rdata.TXTData TXT} records for the specified name.
*
* @param name ex. {@code denominator.io.}
* @param txtdata txtdata values ex. {@code ["made in sweden", "made in norway"]}
*/
public static ResourceRecordSet<TXTData> txt(String name, Collection<String> txtdata) {
return new TXTBuilder().name(name).addAll(txtdata).build();
}
/**
* creates txt set of {@link denominator.model.rdata.TXTData TXT} records for the specified name
* and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param txtdata txtdata values ex. {@code ["made in sweden", "made in norway"]}
*/
public static ResourceRecordSet<TXTData> txt(String name, int ttl, Collection<String> txtdata) {
return new TXTBuilder().name(name).ttl(ttl).addAll(txtdata).build();
}
/**
* creates mx set of {@link denominator.model.rdata.MXData MX} records for the specified name and
* ttl.
*
* @param name ex. {@code denominator.io.}
* @param mxdata {@code 1 mx1.denominator.io.}
*/
public static ResourceRecordSet<MXData> mx(String name, String mxdata) {
return new MXBuilder().name(name).add(mxdata).build();
}
/**
* creates mx set of {@link denominator.model.rdata.MXData MX} records for the specified name and
* ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param mxdata {@code 1 mx1.denominator.io.}
*/
public static ResourceRecordSet<MXData> mx(String name, int ttl, String mxdata) {
return new MXBuilder().name(name).ttl(ttl).add(mxdata).build();
}
/**
* creates mx set of {@link denominator.model.rdata.MXData MX} records for the specified name and
* ttl.
*
* @param name ex. {@code denominator.io.}
* @param mxdata mxdata values ex. {@code [1 mx1.denominator.io., 2 mx2.denominator.io.]}
*/
public static ResourceRecordSet<MXData> mx(String name, Collection<String> mxdata) {
return new MXBuilder().name(name).addAll(mxdata).build();
}
/**
* creates mx set of {@link denominator.model.rdata.MXData MX} records for the specified name and
* ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param mxdata mxdata values ex. {@code [1 mx1.denominator.io., 2 mx2.denominator.io.]}
*/
public static ResourceRecordSet<MXData> mx(String name, int ttl, Collection<String> mxdata) {
return new MXBuilder().name(name).ttl(ttl).addAll(mxdata).build();
}
/**
* creates srv set of {@link denominator.model.rdata.SRVData SRV} records for the specified name
* and ttl.
*
* @param name ex. {@code denominator.io.}
* @param srvdata {@code 0 1 80 www.foo.com.}
*/
public static ResourceRecordSet<SRVData> srv(String name, String srvdata) {
return new SRVBuilder().name(name).add(srvdata).build();
}
/**
* creates srv set of {@link denominator.model.rdata.SRVData SRV} records for the specified name
* and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param srvdata {@code 0 1 80 www.foo.com.}
*/
public static ResourceRecordSet<SRVData> srv(String name, int ttl, String srvdata) {
return new SRVBuilder().name(name).ttl(ttl).add(srvdata).build();
}
/**
* creates srv set of {@link denominator.model.rdata.SRVData SRV} records for the specified name
* and ttl.
*
* @param name ex. {@code denominator.io.}
* @param srvdata srvdata values ex. {@code [0 1 80 www.foo.com., 0 1 443 www.foo.com.]}
*/
public static ResourceRecordSet<SRVData> srv(String name, Collection<String> srvdata) {
return new SRVBuilder().name(name).addAll(srvdata).build();
}
/**
* creates srv set of {@link denominator.model.rdata.SRVData SRV} records for the specified name
* and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param srvdata srvdata values ex. {@code [0 1 80 www.foo.com., 0 1 443 www.foo.com.]}
*/
public static ResourceRecordSet<SRVData> srv(String name, int ttl, Collection<String> srvdata) {
return new SRVBuilder().name(name).ttl(ttl).addAll(srvdata).build();
}
/**
* creates cert set of {@link denominator.model.rdata.CERTData CERT} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param certdata {@code 12345 1 1 B33F}
*/
public static ResourceRecordSet<CERTData> cert(String name, String certdata) {
return new CERTBuilder().name(name).add(certdata).build();
}
/**
* creates cert set of {@link denominator.model.rdata.CERTData CERT} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param certdata {@code 12345 1 1 B33F}
*/
public static ResourceRecordSet<CERTData> cert(String name, int ttl, String certdata) {
return new CERTBuilder().name(name).ttl(ttl).add(certdata).build();
}
/**
* creates cert set of {@link denominator.model.rdata.CERTData CERT} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param certdata certdata values ex. {@code [12345 1 1 B33F, 6789 1 1 F00M00]}
*/
public static ResourceRecordSet<CERTData> cert(String name, Collection<String> certdata) {
return new CERTBuilder().name(name).addAll(certdata).build();
}
/**
* creates cert set of {@link denominator.model.rdata.CERTData CERT} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param certdata certdata values ex. {@code [12345 1 1 B33F, 6789 1 1 F00M00]}
*/
public static ResourceRecordSet<CERTData> cert(String name, int ttl,
Collection<String> certdata) {
return new CERTBuilder().name(name).ttl(ttl).addAll(certdata).build();
}
/**
* creates naptr set of {@link denominator.model.rdata.NAPTRData NAPTR} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param naptrdata naptrdata values ex. {@code 1 1 U E2U+sip !^.*$!sip:customer-service@example.com!
* .}
*/
public static ResourceRecordSet<NAPTRData> naptr(String name, String naptrdata) {
return new NAPTRBuilder().name(name).add(naptrdata).build();
}
/**
* creates naptr set of {@link denominator.model.rdata.NAPTRData NAPTR} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param naptrdata naptrdata values ex. {@code 1 1 U E2U+sip !^.*$!sip:customer-service@example.com!
* .}
*/
public static ResourceRecordSet<NAPTRData> naptr(String name, int ttl, String naptrdata) {
return new NAPTRBuilder().name(name).ttl(ttl).add(naptrdata).build();
}
/**
* creates naptr set of {@link denominator.model.rdata.NAPTRData NAPTR} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param naptrdata naptrdata values ex. {@code [1 1 U E2U+sip !^.*$!sip:customer-service@example.com!
* ., 1 1 U E2U+email !^.*$!mailto:information@example.com! .]}
*/
public static ResourceRecordSet<NAPTRData> naptr(String name, Collection<String> naptrdata) {
return new NAPTRBuilder().name(name).addAll(naptrdata).build();
}
/**
* creates naptr set of {@link denominator.model.rdata.NAPTRData NAPTR} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param naptrdata naptrdata values ex. {@code [1 1 U E2U+sip !^.*$!sip:customer-service@example.com!
* ., 1 1 U E2U+email !^.*$!mailto:information@example.com! .]}
*/
public static ResourceRecordSet<NAPTRData> naptr(String name, int ttl,
Collection<String> naptrdata) {
return new NAPTRBuilder().name(name).ttl(ttl).addAll(naptrdata).build();
}
/**
* creates sshfp set of {@link denominator.model.rdata.SSHFPData SSHFP} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param sshfpdata sshfpdata values ex. {@code 1 1 B33F}
*/
public static ResourceRecordSet<SSHFPData> sshfp(String name, String sshfpdata) {
return new SSHFPBuilder().name(name).add(sshfpdata).build();
}
/**
* creates sshfp set of {@link denominator.model.rdata.SSHFPData SSHFP} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param sshfpdata sshfpdata values ex. {@code 1 1 B33F}
*/
public static ResourceRecordSet<SSHFPData> sshfp(String name, int ttl, String sshfpdata) {
return new SSHFPBuilder().name(name).ttl(ttl).add(sshfpdata).build();
}
/**
* creates sshfp set of {@link denominator.model.rdata.SSHFPData SSHFP} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param sshfpdata sshfpdata values ex. {@code [1 1 B33F, 2 1 F00M00]}
*/
public static ResourceRecordSet<SSHFPData> sshfp(String name, Collection<String> sshfpdata) {
return new SSHFPBuilder().name(name).addAll(sshfpdata).build();
}
/**
* creates sshfp set of {@link denominator.model.rdata.SSHFPData SSHFP} records for the specified
* name and ttl.
*
* @param name ex. {@code denominator.io.}
* @param ttl see {@link ResourceRecordSet#ttl()}
* @param sshfpdata sshfpdata values ex. {@code [1 1 B33F, 2 1 F00M00]}
*/
public static ResourceRecordSet<SSHFPData> sshfp(String name, int ttl,
Collection<String> sshfpdata) {
return new SSHFPBuilder().name(name).ttl(ttl).addAll(sshfpdata).build();
}
private static final class ContainsRecord implements Filter<ResourceRecordSet<?>> {
private final Map<String, ?> record;
public ContainsRecord(Map<String, ?> record) {
this.record = checkNotNull(record, "record");
}
@Override
public boolean apply(ResourceRecordSet<?> input) {
if (input == null) {
return false;
}
return input.records().contains(record);
}
@Override
public String toString() {
return "containsRecord(" + record + ")";
}
}
private static class ABuilder extends StringRecordBuilder<AData> {
private ABuilder() {
type("A");
}
public AData apply(String input) {
return AData.create(input);
}
}
private static class AAAABuilder extends StringRecordBuilder<AAAAData> {
private AAAABuilder() {
type("AAAA");
}
public AAAAData apply(String input) {
return AAAAData.create(input);
}
}
private static class CNAMEBuilder extends StringRecordBuilder<CNAMEData> {
private CNAMEBuilder() {
type("CNAME");
}
public CNAMEData apply(String input) {
return CNAMEData.create(input);
}
}
private static class NSBuilder extends StringRecordBuilder<NSData> {
private NSBuilder() {
type("NS");
}
public NSData apply(String input) {
return NSData.create(input);
}
}
private static class PTRBuilder extends StringRecordBuilder<PTRData> {
private PTRBuilder() {
type("PTR");
}
public PTRData apply(String input) {
return PTRData.create(input);
}
}
private static class SPFBuilder extends StringRecordBuilder<SPFData> {
private SPFBuilder() {
type("SPF");
}
public SPFData apply(String input) {
return SPFData.create(input);
}
}
private static class TXTBuilder extends StringRecordBuilder<TXTData> {
private TXTBuilder() {
type("TXT");
}
public TXTData apply(String input) {
return TXTData.create(input);
}
}
private static class MXBuilder extends StringRecordBuilder<MXData> {
private MXBuilder() {
type("MX");
}
public MXData apply(String input) {
String[] parts = input.split(" ");
checkArgument(parts.length == 2, "record must have exactly two parts");
return MXData.create(Integer.parseInt(parts[0]), parts[1]);
}
}
private static class SRVBuilder extends StringRecordBuilder<SRVData> {
private SRVBuilder() {
type("SRV");
}
public SRVData apply(String input) {
String[] parts = input.split(" ");
checkArgument(parts.length == 4, "record must have exactly four parts");
return SRVData.builder().priority(Integer.parseInt(parts[0]))
.weight(Integer.parseInt(parts[1]))
.port(Integer.parseInt(parts[2]))
.target(parts[3])
.build();
}
}
private static class CERTBuilder extends StringRecordBuilder<CERTData> {
private CERTBuilder() {
type("CERT");
}
public CERTData apply(String input) {
String[] parts = input.split(" ");
checkArgument(parts.length == 4, "record must have exactly four parts");
return CERTData.builder().format(Integer.parseInt(parts[0]))
.tag(Integer.parseInt(parts[1]))
.algorithm(Integer.parseInt(parts[2]))
.certificate(parts[3])
.build();
}
}
private static class NAPTRBuilder extends StringRecordBuilder<NAPTRData> {
private NAPTRBuilder() {
type("NAPTR");
}
public NAPTRData apply(String input) {
String[] parts = input.split(" ");
checkArgument(parts.length == 6, "record must have exactly six parts");
return NAPTRData.builder().order(Integer.parseInt(parts[0]))
.preference(Integer.parseInt(parts[1]))
.flags(parts[2])
.services(parts[3])
.regexp(parts[4])
.replacement(parts[5])
.build();
}
}
private static class SSHFPBuilder extends StringRecordBuilder<SSHFPData> {
private SSHFPBuilder() {
type("SSHFP");
}
public SSHFPData apply(String input) {
String[] parts = input.split(" ");
checkArgument(parts.length == 3, "record must have exactly three parts");
return SSHFPData.builder().algorithm(Integer.parseInt(parts[0]))
.fptype(Integer.parseInt(parts[1]))
.fingerprint(parts[2])
.build();
}
}
}
| 220 |
0 | Create_ds/denominator/model/src/main/java/denominator | Create_ds/denominator/model/src/main/java/denominator/model/Zone.java | package denominator.model;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
import static denominator.common.Util.equal;
/**
* A zone is a delegated portion of DNS. We use the word {@code zone} instead of {@code domain}, as
* denominator focuses on configuration aspects of DNS.
*
* @since 1.2 See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public class Zone {
private final String id;
private final String name;
private final int ttl;
private final String email;
Zone(String id, String name, int ttl, String email) {
this.id = id;
this.name = checkNotNull(name, "name");
this.email = checkNotNull(email, "email of %s", name);
checkArgument(ttl >= 0, "Invalid ttl value: %s, must be 0-%s", ttl, Integer.MAX_VALUE);
this.ttl = ttl;
}
/**
* The potentially transient and opaque string that uniquely identifies the zone. This may be null
* when used as an input object.
*
* @since 4.5
*/
public String id() {
return id;
}
/**
* The origin or starting point for the zone in the DNS tree. Usually includes a trailing dot, ex.
* "{@code netflix.com.}"
*
* <p/> The name of a zone cannot be changed.
*/
public String name() {
return name;
}
/**
* The {@link ResourceRecordSet#ttl() ttl} of the zone's {@link denominator.model.rdata.SOAData
* SOA} record.
*
* <p/>Caution: Eventhough some providers use this as a default ttl for new records, this is not
* always the case.
*
* @since 4.5
*/
public int ttl() {
return ttl;
}
/**
* Email contact for the zone. The {@literal @} in the email will be converted to a {@literal .}
* in the {@link denominator.model.rdata.SOAData#rname() SOA rname field}.
*
* @see denominator.model.rdata.SOAData#rname()
*/
public String email() {
return email;
}
/**
* @deprecated only use {@link #id()} when performing operations against a zone. This will be
* removed in version 5.
*/
@Deprecated
public String idOrName() {
return id() != null ? id() : name();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Zone) {
Zone other = (Zone) obj;
return equal(id(), other.id())
&& name().equals(other.name())
&& ttl() == other.ttl()
&& email().equals(other.email());
}
return false;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (id() != null ? id().hashCode() : 0);
result = 31 * result + name().hashCode();
result = 31 * result + ttl();
result = 31 * result + email().hashCode();
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Zone [");
if (!name().equals(id())) {
builder.append("id=").append(id()).append(", ");
}
builder.append("name=").append(name());
builder.append(", ").append("ttl=").append(ttl());
builder.append(", ").append("email=").append(email());
builder.append("]");
return builder.toString();
}
/**
* Represent a zone when its {@link #id() id} is its name.
*
* @param name corresponds to {@link #name()} and {@link #id()}
* @deprecated Use {@link #create(String, String, int, String)}. This will be removed in version
* 5.
*/
@Deprecated
public static Zone create(String name) {
return create(name, name);
}
/**
* Represent a zone with a fake email and a TTL of 86400.
*
* @param name corresponds to {@link #name()}
* @param id nullable, corresponds to {@link #id()}
* @deprecated Use {@link #create(String, String, int, String)}. This will be removed in version
* 5.
*/
@Deprecated
public static Zone create(String name, String id) {
return new Zone(id, name, 86400, "nil@" + name);
}
/**
* @param id nullable, corresponds to {@link #id()}
* @param name corresponds to {@link #name()}
* @param ttl corresponds to {@link #ttl()}
* @param email corresponds to {@link #email()}
*/
public static Zone create(String id, String name, int ttl, String email) {
return new Zone(id, name, ttl, email);
}
}
| 221 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/MXData.java | package denominator.model.rdata;
import denominator.model.NumbersAreUnsignedIntsLinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code MX} (Mail Exchange) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* MXData rdata = MXData.create(1, "mail.jclouds.org");
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public final class MXData extends NumbersAreUnsignedIntsLinkedHashMap {
private static final long serialVersionUID = 1L;
MXData(int preference, String exchange) {
checkArgument(preference <= 0xFFFF, "preference must be 65535 or less");
checkNotNull(exchange, "exchange");
put("preference", preference);
put("exchange", exchange);
}
public static MXData create(int preference, String exchange) {
return new MXData(preference, exchange);
}
/**
* specifies the preference given to this RR among others at the same owner. Lower values are
* preferred.
*
* @since 1.3
*/
public int preference() {
return Integer.class.cast(get("preference"));
}
/**
* domain-name which specifies a host willing to act as a mail exchange for the owner name.
*
* @since 1.3
*/
public String exchange() {
return get("exchange").toString();
}
}
| 222 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/SOAData.java | package denominator.model.rdata;
import denominator.model.NumbersAreUnsignedIntsLinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code SOA} (Start of Authority) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* SOAData rdata = SOAData.builder()
* .rname("foo.com.")
* .mname("admin.foo.com.")
* .serial(1)
* .refresh(3600)
* .retry(600)
* .expire(604800)
* .minimum(60).build()
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public final class SOAData extends NumbersAreUnsignedIntsLinkedHashMap {
private static final long serialVersionUID = 1L;
SOAData(String mname, String rname, int serial, int refresh, int retry, int expire, int minimum) {
checkNotNull(mname, "mname");
checkNotNull(rname, "rname of %s", mname);
checkArgument(serial >= 0, "serial of %s must be unsigned", mname);
checkArgument(refresh >= 0, "refresh of %s must be unsigned", mname);
checkArgument(retry >= 0, "retry of %s must be unsigned", mname);
checkArgument(expire >= 0, "expire of %s must be unsigned", mname);
checkArgument(minimum >= 0, "minimum of %s must be unsigned", mname);
put("mname", mname);
put("rname", rname);
put("serial", serial);
put("refresh", refresh);
put("retry", retry);
put("expire", expire);
put("minimum", minimum);
}
public static SOAData.Builder builder() {
return new Builder();
}
/**
* domain-name of the name server that was the original or primary source of data for this zone
*
* @since 1.3
*/
public String mname() {
return get("mname").toString();
}
/**
* domain-name which specifies the mailbox of the person responsible for this zone.
*
* @since 1.3
*/
public String rname() {
return get("rname").toString();
}
/**
* version number of the original copy of the zone.
*
* @since 1.3
*/
public int serial() {
return Integer.class.cast(get("serial"));
}
/**
* time interval before the zone should be refreshed
*
* @since 1.3
*/
public int refresh() {
return Integer.class.cast(get("refresh"));
}
/**
* time interval that should elapse before a failed refresh should be retried
*
* @since 1.3
*/
public int retry() {
return Integer.class.cast(get("retry"));
}
/**
* time value that specifies the upper limit on the time interval that can elapse before the zone
* is no longer authoritative.
*
* @since 1.3
*/
public int expire() {
return Integer.class.cast(get("expire"));
}
/**
* minimum TTL field that should be exported with any RR from this zone.
*
* @since 1.3
*/
public int minimum() {
return Integer.class.cast(get("minimum"));
}
public SOAData.Builder toBuilder() {
return builder().from(this);
}
public final static class Builder {
private String mname;
private String rname;
private int serial = -1;
private int refresh = -1;
private int retry = -1;
private int expire = -1;
private int minimum = -1;
/**
* @see SOAData#mname()
*/
public SOAData.Builder mname(String mname) {
this.mname = mname;
return this;
}
/**
* @see SOAData#rname()
*/
public SOAData.Builder rname(String rname) {
this.rname = rname;
return this;
}
/**
* @see SOAData#serial()
*/
public SOAData.Builder serial(int serial) {
this.serial = serial;
return this;
}
/**
* @see SOAData#refresh()
*/
public SOAData.Builder refresh(int refresh) {
this.refresh = refresh;
return this;
}
/**
* @see SOAData#retry()
*/
public SOAData.Builder retry(int retry) {
this.retry = retry;
return this;
}
/**
* @see SOAData#expire()
*/
public SOAData.Builder expire(int expire) {
this.expire = expire;
return this;
}
/**
* @see SOAData#minimum()
*/
public SOAData.Builder minimum(int minimum) {
this.minimum = minimum;
return this;
}
public SOAData build() {
return new SOAData(mname, rname, serial, refresh, retry, expire, minimum);
}
public SOAData.Builder from(SOAData in) {
return this.mname(in.mname()).rname(in.rname()).serial(in.serial()).refresh(in.refresh())
.retry(in.retry()).expire(in.expire()).minimum(in.minimum());
}
}
}
| 223 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/SPFData.java | package denominator.model.rdata;
import java.util.LinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code SPF} (Sender Policy Framework) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* import static denominator.model.rdata.SPFData.spf;
* ...
* SPFData rdata = spf("v=spf1 +mx a:colo.example.com/28 -all");
* </pre>
*
* See <a href="http://tools.ietf.org/html/rfc4408#section-3.1.1">RFC 4408</a>
*/
public final class SPFData extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
SPFData(String txtdata) {
checkArgument(checkNotNull(txtdata, "txtdata").length() <= 65535,
"txt data is limited to 65535");
put("txtdata", txtdata);
}
public static SPFData create(String txtdata) {
return new SPFData(txtdata);
}
/**
* One or more character-strings.
*
* @since 1.3
*/
public String txtdata() {
return get("txtdata").toString();
}
}
| 224 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/AAAAData.java | package denominator.model.rdata;
import java.util.LinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code AAAA} (Address) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* AAAAData rdata = AAAAData.create("1234:ab00:ff00::6b14:abcd");
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc3596.txt">RFC 3596</a>
*/
public final class AAAAData extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
AAAAData(String address) {
checkNotNull(address, "address");
checkArgument(address.indexOf(':') != -1, "%s should be a ipv6 address", address);
put("address", address);
}
/**
* @param ipv6address valid ipv6 address. ex. {@code 1234:ab00:ff00::6b14:abcd}
* @throws IllegalArgumentException if the address is malformed or not ipv6
*/
public static AAAAData create(String ipv6address) throws IllegalArgumentException {
return new AAAAData(ipv6address);
}
/**
* a 128 bit IPv6 address
*
* @since 1.3
*/
public String address() {
return get("address").toString();
}
}
| 225 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/SSHFPData.java | package denominator.model.rdata;
import denominator.model.NumbersAreUnsignedIntsLinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code SSHFP} (SSH Fingerprint) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* SSHFPData rdata = SSHFPData.builder().algorithm(2).fptype(1).fingerprint("123456789abcdef67890123456789abcdef67890")
* .build();
* // or shortcut
* SSHFPData rdata = SSHFPData.createDSA("123456789abcdef67890123456789abcdef67890");
* </pre>
*
* See <a href="http://www.rfc-editor.org/rfc/rfc4255.txt">RFC 4255</a>
*/
public final class SSHFPData extends NumbersAreUnsignedIntsLinkedHashMap {
private static final long serialVersionUID = 1L;
SSHFPData(int algorithm, int fptype, String fingerprint) {
checkArgument(algorithm >= 0, "algorithm of %s must be unsigned", fingerprint);
checkArgument(fptype >= 0, "fptype of %s must be unsigned", fingerprint);
checkNotNull(fingerprint, "fingerprint");
put("algorithm", algorithm);
put("fptype", fptype);
put("fingerprint", fingerprint);
}
/**
* @param fingerprint {@code DSA} {@code SHA-1} fingerprint
*/
public static SSHFPData createDSA(String fingerprint) {
return builder().algorithm(2).fptype(1).fingerprint(fingerprint).build();
}
/**
* @param fingerprint {@code RSA} {@code SHA-1} fingerprint
*/
public static SSHFPData createRSA(String fingerprint) {
return builder().algorithm(1).fptype(1).fingerprint(fingerprint).build();
}
public static SSHFPData.Builder builder() {
return new Builder();
}
/**
* This algorithm number octet describes the algorithm of the public key.
*
* @return most often {@code 1} for {@code RSA} or {@code 2} for {@code DSA} .
* @since 1.3
*/
public int algorithm() {
return Integer.class.cast(get("algorithm"));
}
/**
* The fingerprint fptype octet describes the message-digest algorithm used to calculate the
* fingerprint of the public key.
*
* @return most often {@code 1} for {@code SHA-1}
* @since 1.3
*/
public int fptype() {
return Integer.class.cast(get("fptype"));
}
/**
* The fingerprint calculated over the public key blob.
*
* @since 1.3
*/
public String fingerprint() {
return get("fingerprint").toString();
}
public final static class Builder {
private int algorithm;
private int fptype;
private String fingerprint;
/**
* @see SSHFPData#algorithm()
*/
public SSHFPData.Builder algorithm(int algorithm) {
this.algorithm = algorithm;
return this;
}
/**
* @see SSHFPData#fptype()
*/
public SSHFPData.Builder fptype(int fptype) {
this.fptype = fptype;
return this;
}
/**
* @see SSHFPData#fingerprint()
*/
public SSHFPData.Builder fingerprint(String fingerprint) {
this.fingerprint = fingerprint;
return this;
}
public SSHFPData build() {
return new SSHFPData(algorithm, fptype, fingerprint);
}
}
}
| 226 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/NAPTRData.java | package denominator.model.rdata;
import denominator.model.NumbersAreUnsignedIntsLinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code NAPTR} (Naming Authority Pointer) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* NAPTRData rdata = NAPTRData.builder()
* .order(1)
* .preference(1)
* .flags("U")
* .services("E2U+sip")
* .regexp("!^.*$!sip:customer-service@example.com!")
* .replacement(".").build()
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc3403.txt">RFC 3403</a>
*/
public final class NAPTRData extends NumbersAreUnsignedIntsLinkedHashMap {
private static final long serialVersionUID = 1L;
NAPTRData(int order, int preference, String flags, String services, String regexp,
String replacement) {
checkArgument(order <= 0xFFFF, "order must be 0-65535");
checkArgument(preference <= 0xFFFF, "preference must be 0-65535");
checkNotNull(flags, "flags");
checkNotNull(services, "services");
checkNotNull(regexp, "regexp");
checkNotNull(replacement, "replacement");
put("order", order);
put("preference", preference);
put("flags", flags);
put("services", services);
put("regexp", regexp);
put("replacement", replacement);
}
public static NAPTRData.Builder builder() {
return new Builder();
}
public int order() {
return Integer.class.cast(get("order"));
}
public int preference() {
return Integer.class.cast(get("preference"));
}
public String flags() {
return get("flags").toString();
}
public String services() {
return get("services").toString();
}
public String regexp() {
return get("regexp").toString();
}
public String replacement() {
return get("replacement").toString();
}
public NAPTRData.Builder toBuilder() {
return builder().from(this);
}
public final static class Builder {
private int order = -1;
private int preference = -1;
private String flags;
private String services;
private String regexp;
private String replacement;
public NAPTRData.Builder order(int order) {
this.order = order;
return this;
}
public NAPTRData.Builder preference(int preference) {
this.preference = preference;
return this;
}
public NAPTRData.Builder flags(String flags) {
this.flags = flags;
return this;
}
public NAPTRData.Builder services(String services) {
this.services = services;
return this;
}
public NAPTRData.Builder regexp(String regexp) {
this.regexp = regexp;
return this;
}
public NAPTRData.Builder replacement(String replacement) {
this.replacement = replacement;
return this;
}
public NAPTRData build() {
return new NAPTRData(order, preference, flags, services, regexp, replacement);
}
public NAPTRData.Builder from(NAPTRData in) {
return this.order(in.order())
.preference(in.preference())
.flags(in.flags())
.services(in.services())
.regexp(in.regexp())
.replacement(in.replacement());
}
}
}
| 227 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/SRVData.java | package denominator.model.rdata;
import denominator.model.NumbersAreUnsignedIntsLinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code SRV} (Service) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* SRVData rdata = SRVData.builder()
* .priority(0)
* .weight(1)
* .port(80)
* .target("www.foo.com.").build()
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc2782.txt">RFC 2782</a>
*/
public final class SRVData extends NumbersAreUnsignedIntsLinkedHashMap {
private static final long serialVersionUID = 1L;
SRVData(int priority, int weight, int port, String target) {
checkArgument(priority <= 0xFFFF, "priority must be 0-65535");
checkArgument(weight <= 0xFFFF, "weight must be 0-65535");
checkArgument(port <= 0xFFFF, "port must be 0-65535");
checkNotNull(target, "target");
put("priority", priority);
put("weight", weight);
put("port", port);
put("target", target);
}
public static SRVData.Builder builder() {
return new Builder();
}
/**
* The priority of this target host. A client MUST attempt to contact the target host with the
* lowest-numbered priority it can reach; target hosts with the same priority SHOULD be tried in
* an order defined by the weight field.
*
* @since 1.3
*/
public int priority() {
return Integer.class.cast(get("priority"));
}
/**
* The weight field specifies a relative weight for entries with the same priority. Larger weights
* SHOULD be given a proportionately higher probability of being selected.
*
* @since 1.3
*/
public int weight() {
return Integer.class.cast(get("weight"));
}
/**
* The port on this target host of this service.
*
* @since 1.3
*/
public int port() {
return Integer.class.cast(get("port"));
}
/**
* The domain name of the target host. There MUST be one or more address records for this name,
* the name MUST NOT be an alias.
*
* @since 1.3
*/
public String target() {
return get("target").toString();
}
public SRVData.Builder toBuilder() {
return builder().from(this);
}
public final static class Builder {
private int priority = -1;
private int weight = -1;
private int port = -1;
private String target;
/**
* @see SRVData#priority()
*/
public SRVData.Builder priority(int priority) {
this.priority = priority;
return this;
}
/**
* @see SRVData#weight()
*/
public SRVData.Builder weight(int weight) {
this.weight = weight;
return this;
}
/**
* @see SRVData#port()
*/
public SRVData.Builder port(int port) {
this.port = port;
return this;
}
/**
* @see SRVData#target()
*/
public SRVData.Builder target(String target) {
this.target = target;
return this;
}
public SRVData build() {
return new SRVData(priority, weight, port, target);
}
public SRVData.Builder from(SRVData in) {
return this.priority(in.priority()).weight(in.weight()).port(in.port()).target(in.target());
}
}
}
| 228 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/PTRData.java | package denominator.model.rdata;
import java.util.LinkedHashMap;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code PTR} (Pointer) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* PTRData rdata = PTRData.create("ptr.foo.com.");
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public final class PTRData extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
PTRData(String ptrdname) {
put("ptrdname", checkNotNull(ptrdname, "ptrdname"));
}
public static PTRData create(String ptrdname) {
return new PTRData(ptrdname);
}
/**
* domain-name which points to some location in the domain name space.
*
* @since 1.3
*/
public String ptrdname() {
return get("ptrdname").toString();
}
}
| 229 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/CERTData.java | package denominator.model.rdata;
import denominator.model.NumbersAreUnsignedIntsLinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code CERT} (Certificate) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* CERTData rdata = CERTData.builder()
* .format(12345)
* .tag(1)
* .algorithm(1)
* .certificate("B33F").build()
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc4398.txt">RFC 4398</a>
*/
public final class CERTData extends NumbersAreUnsignedIntsLinkedHashMap {
private static final long serialVersionUID = 1L;
CERTData(int format, int tag, int algorithm, String certificate) {
checkArgument(format <= 0xFFFF, "format must be 0-65535");
checkArgument(tag <= 0xFFFF, "tag must be 0-65535");
checkArgument(algorithm <= 0xFF, "algorithm must be 0-255");
checkNotNull(certificate, "certificate");
put("format", format);
put("tag", tag);
put("algorithm", algorithm);
put("certificate", certificate);
}
public static CERTData.Builder builder() {
return new Builder();
}
/** {@code type} in the spec. This name avoids clashing on keywords. */
public int format() {
return Integer.class.cast(get("format"));
}
public int tag() {
return Integer.class.cast(get("tag"));
}
public int algorithm() {
return Integer.class.cast(get("algorithm"));
}
public String certificate() {
return get("certificate").toString();
}
public CERTData.Builder toBuilder() {
return builder().from(this);
}
public final static class Builder {
private int format = -1;
private int tag = -1;
private int algorithm = -1;
private String certificate;
public CERTData.Builder format(int format) {
this.format = format;
return this;
}
public CERTData.Builder tag(int tag) {
this.tag = tag;
return this;
}
public CERTData.Builder algorithm(int algorithm) {
this.algorithm = algorithm;
return this;
}
public CERTData.Builder certificate(String certificate) {
this.certificate = certificate;
return this;
}
public CERTData build() {
return new CERTData(format, tag, algorithm, certificate);
}
public CERTData.Builder from(CERTData in) {
return format(in.format()).tag(in.tag()).algorithm(in.algorithm()).certificate(in.certificate());
}
}
}
| 230 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/TXTData.java | package denominator.model.rdata;
import java.util.LinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code TXT} (Text) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* TXTData rdata = TXTData.create("=spf1 ip4:192.0.2.1/24 ip4:198.51.100.1/24 -all");
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public final class TXTData extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
TXTData(String txtdata) {
checkArgument(checkNotNull(txtdata, "txtdata").length() <= 65535,
"txt data is limited to 65535");
put("txtdata", txtdata);
}
public static TXTData create(String txtdata) {
return new TXTData(txtdata);
}
/**
* One or more character-strings.
*
* @since 1.3
*/
public String txtdata() {
return get("txtdata").toString();
}
}
| 231 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/NSData.java | package denominator.model.rdata;
import java.util.LinkedHashMap;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code NS} (Name Server) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* NSData rdata = NSData.create("ns.foo.com.");
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public final class NSData extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
NSData(String nsdname) {
put("nsdname", checkNotNull(nsdname, "nsdname"));
}
public static NSData create(String nsdname) {
return new NSData(nsdname);
}
/**
* domain-name which specifies a host which should be authoritative for the specified class and
* domain.
*
* @since 1.3
*/
public String nsdname() {
return get("nsdname").toString();
}
}
| 232 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/CNAMEData.java | package denominator.model.rdata;
import java.util.LinkedHashMap;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code CNAME} (Canonical Name) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* CNAMEData rdata = CNAMEData.create("cname.foo.com.");
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public final class CNAMEData extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
CNAMEData(String cname) {
put("cname", checkNotNull(cname, "cname"));
}
public static CNAMEData create(String cname) {
return new CNAMEData(cname);
}
/**
* domain-name which specifies the canonical or primary name for the owner. The owner name is an
* alias.
*
* @since 1.3
*/
public String cname() {
return get("cname").toString();
}
}
| 233 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/package-info.java | /**
* DNS record data ({@code rdata}) in <a href="http://tools.ietf.org/html/rfc1035">Master File Format</a> are represented as {@code Map<String, Object>}, preferring values to be unsigned integers or {@code String}.
*/
package denominator.model.rdata;
| 234 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/rdata/AData.java | package denominator.model.rdata;
import java.util.LinkedHashMap;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
/**
* Corresponds to the binary representation of the {@code A} (Address) RData
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* AData rdata = AData.create("192.0.2.1");
* </pre>
*
* See <a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>
*/
public final class AData extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
AData(String address) {
checkNotNull(address, "address");
checkArgument(address.indexOf('.') != -1, "%s should be a ipv4 address", address);
put("address", address);
}
/**
* @param ipv4address valid ipv4 address. ex. {@code 192.0.2.1}
* @throws IllegalArgumentException if the address is malformed or not ipv4
*/
public static AData create(String ipv4address) throws IllegalArgumentException {
return new AData(ipv4address);
}
/**
* a 32-bit internet address
*
* @since 1.3
*/
public String address() {
return get("address").toString();
}
}
| 235 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/profile/Geos.java | package denominator.model.profile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import denominator.model.ResourceRecordSet;
import static denominator.common.Preconditions.checkArgument;
/**
* Utilities for manipulating record sets that contain a {@link Geo} profile.
*/
public class Geos {
/**
* Build a {@link ResourceRecordSet} with additional {@link Geo#regions()}.
*
* <br> If the existing record set contained no {@link Geo} configuration, the return value will
* contain only the regions specified. If the existing record set's regions are identical to
* {@code regionsToAdd}, {@code existing} will be returned directly.
*
* @return {@code existing} if there is no change, adding the regions
* @throws IllegalArgumentException if {code regionsToAdd} were empty or the {@code existing}
* rrset did not contain a geo profile.
*/
public static ResourceRecordSet<?> withAdditionalRegions(ResourceRecordSet<?> existing,
Map<String, Collection<String>> regionsToAdd)
throws IllegalArgumentException {
checkArgument(!regionsToAdd.isEmpty(), "no regions specified");
checkArgument(existing.geo() != null, "rrset does not include geo configuration: %s", existing);
Map<String, Collection<String>> regionsToApply =
new LinkedHashMap<String, Collection<String>>();
for (Entry<String, Collection<String>> entry : existing.geo().regions().entrySet()) {
regionsToApply.put(entry.getKey(), entry.getValue());
}
for (Entry<String, Collection<String>> entry : regionsToAdd.entrySet()) {
List<String> updates = new ArrayList<String>();
if (regionsToApply.containsKey(entry.getKey())) {
updates.addAll(regionsToApply.get(entry.getKey()));
}
updates.addAll(entry.getValue());
regionsToApply.put(entry.getKey(), updates);
}
boolean noop = true;
for (Entry<String, Collection<String>> entry : regionsToApply.entrySet()) {
if (!existing.geo().regions().containsKey(entry.getKey())) {
noop = false;
break;
}
Collection<String> existingTerritories = existing.geo().regions().get(entry.getKey());
if (!existingTerritories.containsAll(entry.getValue())) {
noop = false;
break;
}
}
if (noop) {
return existing;
}
return ResourceRecordSet.<Map<String, Object>>builder()//
.name(existing.name())//
.type(existing.type())//
.qualifier(existing.qualifier())//
.ttl(existing.ttl())//
.geo(Geo.create(regionsToApply))//
.weighted(existing.weighted())//
.addAll(existing.records()).build();
}
}
| 236 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/profile/Weighted.java | package denominator.model.profile;
import static denominator.common.Preconditions.checkArgument;
/**
* Record sets with this profile are load balanced, differentiated by an integer {@code weight}.
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* Weighted profile = Weighted.create(2);
* </pre>
*
* @since 1.3
*/
public class Weighted {
private final int weight;
private Weighted(int weight) {
checkArgument(weight >= 0, "weight must be positive");
this.weight = weight;
}
/**
* @param weight corresponds to {@link #weight()}
*/
public static Weighted create(int weight) {
return new Weighted(weight);
}
/**
* {@code 0} to always serve the record. Otherwise, provider-specific range of positive numbers
* which differentiate the load to send to this record set vs another.
*
* <br> <br> <b>Note</b><br>
*
* In some implementation, such as UltraDNS, only even number weights are supported! For highest
* portability, use even numbers between {@code 0-100}
*/
public int weight() {
return weight;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Weighted && weight() == ((Weighted) obj).weight();
}
@Override
public int hashCode() {
return 37 * 17 + weight();
}
@Override
public String toString() {
return new StringBuilder().append("Weighted [weight=").append(weight()).append("]").toString();
}
}
| 237 |
0 | Create_ds/denominator/model/src/main/java/denominator/model | Create_ds/denominator/model/src/main/java/denominator/model/profile/Geo.java | package denominator.model.profile;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import static denominator.common.Preconditions.checkNotNull;
/**
* Record sets with this profile are visible to the regions specified.
*
* <br> <br> <b>Example</b><br>
*
* <pre>
* Geo profile = Geo.create(Map.of("United States (US)", Collection.of("Maryland")));
* </pre>
*/
public class Geo {
private final Map<String, Collection<String>> regions;
private Geo(Map<String, Collection<String>> regions) {
this.regions = Collections.unmodifiableMap(checkNotNull(regions, "regions"));
}
/**
* @param regions corresponds to {@link #regions()}
* @since 1.3
*/
public static Geo create(Map<String, Collection<String>> regions) {
return new Geo(regions);
}
/**
* a filtered view of {@code denominator.profile.GeoResourceRecordSetApi.supportedRegions()} ,
* which describes the traffic desired for this profile.
*
* @since 1.3
*/
public Map<String, Collection<String>> regions() {
return regions;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Geo && regions().equals(((Geo) obj).regions());
}
@Override
public int hashCode() {
return regions().hashCode();
}
@Override
public String toString() {
return new StringBuilder().append("Geo [regions=").append(regions()).append("]").toString();
}
}
| 238 |
0 | Create_ds/denominator/example-daemon/src/test/java/denominator | Create_ds/denominator/example-daemon/src/test/java/denominator/denominatord/DenominatorDTest.java | package denominator.denominatord;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import denominator.DNSApiManager;
import denominator.Denominator;
import denominator.mock.MockProvider;
import denominator.model.ResourceRecordSet;
import denominator.model.Zone;
import denominator.model.profile.Geo;
import denominator.model.profile.Weighted;
import denominator.model.rdata.AData;
import denominator.model.rdata.CNAMEData;
import feign.Feign;
import feign.FeignException;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import static denominator.model.ResourceRecordSets.a;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class DenominatorDTest {
static DNSApiManager mock;
static DenominatorD server;
static DenominatorDApi client;
@BeforeClass
public static void start() throws IOException {
mock = Denominator.create(new MockProvider());
server = new DenominatorD(mock);
int port = server.start();
client = Feign.builder()
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.target(DenominatorDApi.class, "http://localhost:" + port);
mock.api().basicRecordSetsInZone("denominator.io.").put(ResourceRecordSet.<AData>builder()
.name("www.denominator.io.")
.type("A")
.add(AData.create("192.0.2.1")).build());
mock.api().weightedRecordSetsInZone("denominator.io.").put(ResourceRecordSet.<CNAMEData>builder()
.name("www.weighted.denominator.io.")
.type("CNAME")
.qualifier("EU-West")
.weighted(Weighted.create(1))
.add(CNAMEData.create("www1.denominator.io.")).build());
mock.api().weightedRecordSetsInZone("denominator.io.").put(ResourceRecordSet.<CNAMEData>builder()
.name("www.weighted.denominator.io.")
.type("CNAME")
.qualifier("US-West")
.weighted(Weighted.create(1))
.add(CNAMEData.create("www2.denominator.io.")).build());
}
@AfterClass
public static void stop() throws IOException {
server.shutdown();
}
@Test
public void healthcheckOK() {
assertThat(client.healthcheck().status()).isEqualTo(200);
}
@Test
public void zones() {
assertThat(client.zones())
.containsAll(mock.api().zones());
}
@Test
public void zonesByName() {
assertThat(client.zonesByName("denominator.io."))
.containsAll(toList(mock.api().zones().iterateByName("denominator.io.")));
}
@Test
public void putZone_new() {
Zone zone = Zone.create(null, "putzone_new.denominator.io.", 86400, "nil@denominator.io");
String id =
client.putZone(zone).headers().get("Location").iterator().next().replace("/zones/", "");
assertThat(mock.api().zones().iterateByName(zone.name()))
.containsExactly(Zone.create(id, zone.name(), zone.ttl(), zone.email()));
}
@Test
public void putZone_update() {
Zone zone = Zone.create(null, "putzone_update.denominator.io.", 86400, "nil@denominator.io");
String id = mock.api().zones().put(zone);
Zone update = Zone.create(id, zone.name(), 300, "test@denominator.io");
client.putZone(update);
assertThat(mock.api().zones().iterateByName(zone.name()))
.containsExactly(update);
}
@Test
public void deleteZone() {
Zone zone = Zone.create(null, "zonetest.denominator.io.", 86400, "nil@denominator.io");
String id = mock.api().zones().put(zone);
client.deleteZone(id);
assertThat(mock.api().zones().iterateByName(zone.name()))
.isEmpty();
}
@Test
public void recordSets() {
assertThat(client.recordSets("denominator.io.")).isNotEmpty();
}
@Test
public void recordSetsWrongZoneIs400() {
try {
client.recordSets("moomoo.io.");
} catch (FeignException e) {
assertThat(e.getMessage()).startsWith("status 400");
}
}
@Test
public void recordSetsByName() {
ResourceRecordSet<AData> a =
a("www.denominator.io.", asList("192.0.2.1", "198.51.100.1", "203.0.113.1"));
mock.api().basicRecordSetsInZone("denominator.io.").put(a);
assertThat(client.recordSetsByName("denominator.io.", a.name()))
.containsExactly(a);
}
@Test
public void recordSetsByNameWhenNotFound() {
assertThat(client.recordSetsByName("denominator.io.", "moomoo.denominator.io.")).isEmpty();
}
@Test
public void recordSetsByNameAndType() {
assertThat(client.recordSetsByNameAndType("denominator.io.", "denominator.io.", "NS"))
.containsAll(toList(mock.api().recordSetsInZone("denominator.io.")
.iterateByNameAndType("denominator.io.", "NS")));
}
@Test
public void recordSetsByNameAndTypeWhenNotFound() {
assertThat(client.recordSetsByNameAndType("denominator.io.", "denominator.io.", "A")).isEmpty();
}
@Test
public void recordSetsByNameTypeAndQualifier() {
ResourceRecordSet<CNAMEData> weighted = ResourceRecordSet.<CNAMEData>builder()
.name("www.weighted.denominator.io.")
.type("A")
.qualifier("EU-West")
.add(CNAMEData.create("www.denominator.io."))
.weighted(Weighted.create(10))
.build();
mock.api().weightedRecordSetsInZone("denominator.io.").put(weighted);
assertThat(client.recordsetsByNameAndTypeAndQualifier("denominator.io.",
weighted.name(), weighted.type(),
weighted.qualifier()))
.containsOnly(weighted);
}
@Test
public void recordSetsByNameTypeAndQualifierWhenNotFound() {
assertThat(client.recordsetsByNameAndTypeAndQualifier("denominator.io.",
"www.weighted.denominator.io.", "CNAME",
"AU-West")).isEmpty();
}
@Test
public void deleteRecordSetByNameAndType() {
client.deleteRecordSetByNameAndType("denominator.io.", "www1.denominator.io.", "A");
assertThat(client.recordSetsByNameAndType("denominator.io.", "www1.denominator.io.", "A"))
.isEmpty();
}
@Test
public void deleteRecordSetByNameAndTypeWhenNotFound() {
client.deleteRecordSetByNameAndType("denominator.io.", "denominator.io.", "A");
}
@Test
public void deleteRecordSetByNameTypeAndQualifier() {
client.deleteRecordSetByNameTypeAndQualifier("denominator.io.", "www.weighted.denominator.io.",
"CNAME", "US-West");
assertThat(client.recordsetsByNameAndTypeAndQualifier("denominator.io.",
"www.weighted.denominator.io.", "CNAME",
"US-West")).isEmpty();
}
@Test
public void deleteRecordSetByNameTypeAndQualifierWhenNotFound() {
client.deleteRecordSetByNameTypeAndQualifier("denominator.io.", "www.weighted.denominator.io.",
"CNAME", "AU-West");
}
@Test
public void putRecordSet() {
Map<String, Collection<String>> antarctica = new LinkedHashMap<String, Collection<String>>();
antarctica.put("Antarctica",
Arrays.asList("Bouvet Island", "French Southern Territories", "Antarctica"));
ResourceRecordSet<CNAMEData> recordSet = ResourceRecordSet.<CNAMEData>builder()
.name("www.beta.denominator.io.")
.type("CNAME")
.qualifier("Antarctica")
.ttl(300)
.add(CNAMEData.create("www-south.denominator.io."))
.geo(Geo.create(antarctica))
.build();
client.putRecordSet("denominator.io.", recordSet);
assertThat(
client.recordSetsByNameAndType("denominator.io.", recordSet.name(), recordSet.type()))
.containsOnly(recordSet);
}
static <T> List<T> toList(Iterator<T> iterator) {
List<T> inMock = new ArrayList<T>();
while (iterator.hasNext()) {
inMock.add(iterator.next());
}
return inMock;
}
}
| 239 |
0 | Create_ds/denominator/example-daemon/src/main/java/denominator | Create_ds/denominator/example-daemon/src/main/java/denominator/denominatord/RecordSetDispatcher.java | package denominator.denominatord;
import com.squareup.okhttp.mockwebserver.Dispatcher;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import java.util.Iterator;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import denominator.AllProfileResourceRecordSetApi;
import denominator.DNSApiManager;
import denominator.ReadOnlyResourceRecordSetApi;
import denominator.model.ResourceRecordSet;
import static denominator.common.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
public class RecordSetDispatcher extends Dispatcher {
static final Pattern RECORDSET_PATTERN = Pattern.compile("/zones/([\\.\\w]+)/recordsets(\\?.*)?");
private final Logger log = Logger.getLogger(Dispatcher.class.getName());
private final DNSApiManager mgr;
private final JsonCodec codec;
RecordSetDispatcher(DNSApiManager mgr, JsonCodec codec) {
this.mgr = mgr;
this.codec = codec;
}
@Override
public MockResponse dispatch(RecordedRequest request) {
Matcher matcher = RECORDSET_PATTERN.matcher(request.getPath());
if (!matcher.matches()) {
return new MockResponse().setResponseCode(404);
}
String zoneIdOrName = matcher.group(1);
AllProfileResourceRecordSetApi api = mgr.api().recordSetsInZone(zoneIdOrName);
checkArgument(api != null, "cannot control record sets in zone %s", zoneIdOrName);
if (request.getMethod().equals("GET")) {
Query query = Query.from(request.getPath());
return codec.toJsonArray(recordSetsForQuery(api, query));
} else if (request.getMethod().equals("PUT")) {
ResourceRecordSet<?> recordSet = codec.readJson(request, ResourceRecordSet.class);
Query query = Query.from(recordSet);
long s = currentTimeMillis();
log.info(format("replacing recordset %s", query));
api.put(recordSet);
log.info(format("replaced recordset %s in %sms", query, currentTimeMillis() - s));
return new MockResponse().setResponseCode(204);
} else if (request.getMethod().equals("DELETE")) {
Query query = Query.from(request.getPath());
long s = currentTimeMillis();
log.info(format("deleting recordset %s ", query));
if (query.qualifier != null) {
api.deleteByNameTypeAndQualifier(query.name, query.type, query.qualifier);
} else if (query.type != null) {
checkArgument(query.name != null, "name query required with type");
api.deleteByNameAndType(query.name, query.type);
} else if (query.name != null) {
throw new IllegalArgumentException("you must specify both name and type when deleting");
}
log.info(format("deleted recordset %s in %sms", query, currentTimeMillis() - s));
return new MockResponse().setResponseCode(204);
} else {
return new MockResponse().setResponseCode(405);
}
}
static Iterator<?> recordSetsForQuery(ReadOnlyResourceRecordSetApi api, Query query) {
if (query.qualifier != null) {
ResourceRecordSet<?> rrset =
api.getByNameTypeAndQualifier(query.name, query.type, query.qualifier);
return rrset != null ? singleton(rrset).iterator() : emptySet().iterator();
} else if (query.type != null) {
return api.iterateByNameAndType(query.name, query.type);
} else if (query.name != null) {
return api.iterateByName(query.name);
}
return api.iterator();
}
}
| 240 |
0 | Create_ds/denominator/example-daemon/src/main/java/denominator | Create_ds/denominator/example-daemon/src/main/java/denominator/denominatord/DenominatorDispatcher.java | package denominator.denominatord;
import com.squareup.okhttp.mockwebserver.Dispatcher;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import denominator.DNSApiManager;
import static denominator.denominatord.RecordSetDispatcher.RECORDSET_PATTERN;
public class DenominatorDispatcher extends Dispatcher {
private final DNSApiManager mgr;
private final Dispatcher zones;
private final Dispatcher recordSets;
DenominatorDispatcher(DNSApiManager mgr, JsonCodec codec) {
this.mgr = mgr;
this.zones = new ZoneDispatcher(mgr.api().zones(), codec);
this.recordSets = new RecordSetDispatcher(mgr, codec);
}
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
try {
if ("/healthcheck".equals(request.getPath())) {
if (!request.getMethod().equals("GET")) {
return new MockResponse().setResponseCode(405);
}
return new MockResponse().setResponseCode(mgr.checkConnection() ? 200 : 503);
} else if (RECORDSET_PATTERN.matcher(request.getPath()).matches()) {
return recordSets.dispatch(request);
} else if (request.getPath() != null && request.getPath().startsWith("/zones")) {
return zones.dispatch(request);
} else {
return new MockResponse().setResponseCode(404);
}
} catch (InterruptedException e) {
throw e;
} catch (RuntimeException e) {
return new MockResponse().setResponseCode(e instanceof IllegalArgumentException ? 400 : 500)
.addHeader("Content-Type", "text/plain")
.setBody(e.getMessage() + "\n"); // curl nice
}
}
}
| 241 |
0 | Create_ds/denominator/example-daemon/src/main/java/denominator | Create_ds/denominator/example-daemon/src/main/java/denominator/denominatord/JsonCodec.java | package denominator.denominatord;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
class JsonCodec {
private final Gson json;
JsonCodec() {
this.json = new GsonBuilder().setPrettyPrinting().create();
}
<T> T readJson(RecordedRequest request, Class<T> clazz) {
return json.fromJson(request.getUtf8Body(), clazz);
}
<T> MockResponse toJsonArray(Iterator<T> elements) {
elements.hasNext(); // defensive to make certain error cases eager.
StringWriter out = new StringWriter(); // MWS cannot do streaming responses.
try {
JsonWriter writer = new JsonWriter(out);
writer.setIndent(" ");
writer.beginArray();
while (elements.hasNext()) {
Object next = elements.next();
json.toJson(next, next.getClass(), writer);
}
writer.endArray();
writer.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
return new MockResponse().setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(out.toString() + "\n"); // curl nice
}
}
| 242 |
0 | Create_ds/denominator/example-daemon/src/main/java/denominator | Create_ds/denominator/example-daemon/src/main/java/denominator/denominatord/DenominatorDApi.java | package denominator.denominatord;
import java.util.List;
import denominator.model.ResourceRecordSet;
import denominator.model.Zone;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import feign.Response;
/**
* Defines the interface of {@link DenominatorD}, where all responses are in json. <p/> All
* responses throw a 400 if there is a problem with the request data. <p/> 404 would be unexpected
* as that implies a malformed request.
*/
public interface DenominatorDApi {
@RequestLine("GET /healthcheck")
Response healthcheck();
@RequestLine("GET /zones")
List<Zone> zones();
@RequestLine("GET /zones?name={name}")
List<Zone> zonesByName(@Param("name") String name);
@RequestLine("PUT /zones")
@Headers("Content-Type: application/json")
Response putZone(Zone update);
@RequestLine("DELETE /zones/{zoneId}")
void deleteZone(@Param("zoneId") String zoneId);
@RequestLine("GET /zones/{zoneId}/recordsets")
List<ResourceRecordSet<?>> recordSets(@Param("zoneId") String zoneId);
@RequestLine("GET /zones/{zoneId}/recordsets?name={name}")
List<ResourceRecordSet<?>> recordSetsByName(@Param("zoneId") String zoneId,
@Param("name") String name);
@RequestLine("GET /zones/{zoneId}/recordsets?name={name}&type={type}")
List<ResourceRecordSet<?>> recordSetsByNameAndType(@Param("zoneId") String zoneId,
@Param("name") String name,
@Param("type") String type);
@RequestLine("GET /zones/{zoneId}/recordsets?name={name}&type={type}&qualifier={qualifier}")
List<ResourceRecordSet<?>> recordsetsByNameAndTypeAndQualifier(
@Param("zoneId") String zoneId, @Param("name") String name,
@Param("type") String type, @Param("qualifier") String qualifier);
@RequestLine("PUT /zones/{zoneId}/recordsets?name={name}")
@Headers("Content-Type: application/json")
void putRecordSet(@Param("zoneId") String zoneId, ResourceRecordSet<?> update);
@RequestLine("DELETE /zones/{zoneId}/recordsets?name={name}&type={type}")
void deleteRecordSetByNameAndType(@Param("zoneId") String zoneId,
@Param("name") String name,
@Param("type") String type);
@RequestLine("DELETE /zones/{zoneId}/recordsets?name={name}&type={type}&qualifier={qualifier}")
void deleteRecordSetByNameTypeAndQualifier(@Param("zoneId") String zoneId,
@Param("name") String name,
@Param("type") String type,
@Param("qualifier") String qualifier);
}
| 243 |
0 | Create_ds/denominator/example-daemon/src/main/java/denominator | Create_ds/denominator/example-daemon/src/main/java/denominator/denominatord/DenominatorD.java | package denominator.denominatord;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import dagger.Module;
import dagger.Provides;
import denominator.DNSApiManager;
import denominator.Denominator;
import denominator.Provider;
import denominator.Providers;
import feign.Feign;
import static denominator.CredentialsConfiguration.anonymous;
import static denominator.CredentialsConfiguration.credentials;
import static denominator.common.Preconditions.checkArgument;
import static java.lang.System.currentTimeMillis;
public class DenominatorD {
private static final String SYNTAX = "syntax: provider credentialArg1 credentialArg2 ...";
private static final Logger log = Logger.getLogger(DenominatorD.class.getName());
private final MockWebServer server;
public DenominatorD(DNSApiManager mgr) {
this.server = new MockWebServer();
server.setDispatcher(new DenominatorDispatcher(mgr, new JsonCodec()));
}
public int start() throws IOException {
server.start();
return server.getPort();
}
public void start(int port) throws IOException {
server.start(port);
}
public void shutdown() throws IOException {
server.shutdown();
}
/**
* Presents a {@link DenominatorDApi REST api} to users, by default listening on port 8080.
*/
public static void main(final String... args) throws IOException {
checkArgument(args.length > 0, SYNTAX);
setupLogging();
String portOverride = System.getenv("DENOMINATORD_PORT");
int port = portOverride != null ? Integer.parseInt(portOverride) : 8080;
Provider provider = Providers.getByName(args[0]);
log.info("proxying " + provider);
Object credentials = credentialsFromArgs(args);
DNSApiManager mgr = Denominator.create(provider, credentials, new JavaLogger());
new DenominatorD(mgr).start(port);
}
static Object credentialsFromArgs(String[] args) {
switch (args.length) {
case 4:
return credentials(args[1], args[2], args[3]);
case 3:
return credentials(args[1], args[2]);
case 1:
return anonymous();
default:
throw new IllegalArgumentException(SYNTAX);
}
}
@Module(library = true, overrides = true)
static class JavaLogger {
@Provides
feign.Logger.Level provideLevel() {
return feign.Logger.Level.BASIC;
}
@Provides
feign.Logger logger() {
return new feign.Logger.JavaLogger();
}
}
static void setupLogging() {
final long start = currentTimeMillis();
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.FINE);
handler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
return String.format("%7d - %s%n", record.getMillis() - start, record.getMessage());
}
});
Logger[] loggers = {
Logger.getLogger(DenominatorD.class.getPackage().getName()),
Logger.getLogger(feign.Logger.class.getName()),
Logger.getLogger(MockWebServer.class.getName())
};
for (Logger logger : loggers) {
logger.setLevel(Level.FINE);
logger.setUseParentHandlers(false);
logger.addHandler(handler);
}
}
}
| 244 |
0 | Create_ds/denominator/example-daemon/src/main/java/denominator | Create_ds/denominator/example-daemon/src/main/java/denominator/denominatord/Query.java | package denominator.denominatord;
import java.net.URI;
import java.util.List;
import denominator.common.Util;
import denominator.model.ResourceRecordSet;
import static denominator.common.Preconditions.checkArgument;
class Query {
static Query from(String path) {
String decoded = URI.create(path).getQuery();
if (decoded == null) {
return new Query(null, null, null);
}
String name = null;
String type = null;
String qualifier = null;
for (String nameValueString : Util.split('&', decoded)) {
List<String> nameValue = Util.split('=', nameValueString);
String queryName = nameValue.get(0);
String queryValue = nameValue.size() > 1 ? nameValue.get(1) : null;
if (queryName.equals("name")) {
name = queryValue;
} else if (queryName.equals("type")) {
type = queryValue;
} else if (queryName.equals("qualifier")) {
qualifier = queryValue;
}
}
return new Query(name, type, qualifier);
}
static Query from(ResourceRecordSet<?> recordSet) {
return new Query(recordSet.name(), recordSet.type(), recordSet.qualifier());
}
final String name;
final String type;
final String qualifier;
private Query(String name, String type, String qualifier) {
this.name = name;
this.type = type;
this.qualifier = qualifier;
if (qualifier != null) {
checkArgument(type != null && name != null, "name and type query required with qualifier");
} else if (type != null) {
checkArgument(name != null, "name query required with type");
}
}
@Override
public String toString() {
return new StringBuilder()
.append("name=").append(name)
.append(", type=").append(type)
.append(", qualifier=").append(qualifier).toString();
}
}
| 245 |
0 | Create_ds/denominator/example-daemon/src/main/java/denominator | Create_ds/denominator/example-daemon/src/main/java/denominator/denominatord/ZoneDispatcher.java | package denominator.denominatord;
import com.squareup.okhttp.mockwebserver.Dispatcher;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import denominator.ZoneApi;
import denominator.model.Zone;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
public class ZoneDispatcher extends Dispatcher {
private final Logger log = Logger.getLogger(Dispatcher.class.getName());
private final ZoneApi api;
private final JsonCodec codec;
ZoneDispatcher(ZoneApi api, JsonCodec codec) {
this.api = api;
this.codec = codec;
}
@Override
public MockResponse dispatch(RecordedRequest request) {
if (request.getMethod().equals("GET")) {
Query query = Query.from(request.getPath());
if (query.name != null) {
return codec.toJsonArray(api.iterateByName(query.name));
}
return codec.toJsonArray(api.iterator());
} else if (request.getMethod().equals("PUT")) {
Zone zone = codec.readJson(request, Zone.class);
long s = currentTimeMillis();
log.info(format("replacing zone %s", zone));
String id = api.put(zone);
log.info(format("replaced zone %s in %sms", zone, currentTimeMillis() - s));
return new MockResponse().setResponseCode(201).addHeader("Location", "/zones/" + id);
} else if (request.getMethod().equals("DELETE")) {
String zoneId = request.getPath().replace("/zones/", "");
long s = currentTimeMillis();
log.info(format("deleting zone %s ", zoneId));
api.delete(zoneId);
log.info(format("deleted zone %s in %sms", zoneId, currentTimeMillis() - s));
return new MockResponse().setResponseCode(204);
} else {
return new MockResponse().setResponseCode(405);
}
}
}
| 246 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53ErrorDecoderTest.java | package denominator.route53;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Collection;
import java.util.Collections;
import feign.Response;
import feign.RetryableException;
import feign.codec.ErrorDecoder;
import static feign.Util.UTF_8;
public class Route53ErrorDecoderTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
ErrorDecoder errors = new Route53ErrorDecoder(new Route53Provider.FeignModule().decoder());
@Test
public void requestExpired() throws Exception {
thrown.expect(RetryableException.class);
thrown.expectMessage("Route53.zones() failed with error RequestExpired: Request has expired. Timestamp date is 2013-06-07T12:16:22Z");
Response
response =
response("<Response xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <Errors>\n"
+ " <Error>\n"
+ " <Code>RequestExpired</Code>\n"
+ " <Message>Request has expired. Timestamp date is 2013-06-07T12:16:22Z</Message>\n"
+ " </Error>\n"
+ " </Errors>\n"
+ " <RequestID>dc94a37b0-e297-4ab7-83c8-791a0fc8f613</RequestID>\n"
+ "</Response>");
throw errors.decode("Route53.zones()", response);
}
@Test
public void internalError() throws Exception {
thrown.expect(RetryableException.class);
thrown.expectMessage("Route53.zones() failed with error InternalError");
Response
response =
response("<Response xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <Errors>\n"
+ " <Error>\n"
+ " <Code>InternalError</Code>\n"
+ " </Error>\n"
+ " </Errors>\n"
+ " <RequestID>dc94a37b0-e297-4ab7-83c8-791a0fc8f613</RequestID>\n"
+ "</Response>");
throw errors.decode("Route53.zones()", response);
}
@Test
public void internalFailure() throws Exception {
thrown.expect(RetryableException.class);
thrown.expectMessage("Route53.zones() failed with error InternalFailure");
Response
response =
response("<Response xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <Errors>\n"
+ " <Error>\n"
+ " <Type>Receiver</Type>\n"
+ " <Code>InternalFailure</Code>\n"
+ " </Error>\n"
+ " </Errors>\n"
+ " <RequestID>dc94a37b0-e297-4ab7-83c8-791a0fc8f613</RequestID>\n"
+ "</Response>");
throw errors.decode("Route53.zones()", response);
}
@Test
public void throttling() throws Exception {
thrown.expect(RetryableException.class);
thrown.expectMessage("Route53.zones() failed with error Throttling: Rate exceeded");
Response
response =
response("<Response xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <Errors>\n"
+ " <Error>\n"
+ " <Code>Throttling</Code>\n"
+ " <Message>Rate exceeded</Message>\n"
+ " </Error>\n"
+ " </Errors>\n"
+ " <RequestID>dc94a37b0-e297-4ab7-83c8-791a0fc8f613</RequestID>\n"
+ "</Response>");
throw errors.decode("Route53.zones()", response);
}
@Test
public void priorRequestNotComplete() throws Exception {
thrown.expect(RetryableException.class);
thrown.expectMessage("Route53.zones() failed with error PriorRequestNotComplete: The request was rejected because Route 53 was still processing a prior request.");
Response
response =
response("<Response xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <Errors>\n"
+ " <Error>\n"
+ " <Code>PriorRequestNotComplete</Code>\n"
+ " <Message>The request was rejected because Route 53 was still processing a prior request.</Message>\n"
+ " </Error>\n"
+ " </Errors>\n"
+ " <RequestID>dc94a37b0-e297-4ab7-83c8-791a0fc8f613</RequestID>\n"
+ "</Response>");
throw errors.decode("Route53.zones()", response);
}
static Response response(String xml) {
return Response
.create(500, "ServerError", Collections.<String, Collection<String>>emptyMap(), xml, UTF_8);
}
}
| 247 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/MockRoute53Server.java | package denominator.route53;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.io.IOException;
import denominator.Credentials;
import denominator.CredentialsConfiguration;
import denominator.DNSApiManager;
import denominator.Denominator;
import denominator.assertj.RecordedRequestAssert;
import static denominator.Credentials.ListCredentials;
import static denominator.assertj.MockWebServerAssertions.assertThat;
final class MockRoute53Server extends Route53Provider implements TestRule {
private final MockWebServer delegate = new MockWebServer();
private String accessKey = "accessKey";
private String secretKey = "secretKey";
private String token = null;
MockRoute53Server() {
credentials(accessKey, secretKey, token);
}
@Override
public String url() {
return "http://localhost:" + delegate.getPort();
}
DNSApiManager connect() {
return Denominator.create(this, CredentialsConfiguration.credentials(credentials()));
}
Credentials credentials() {
return token == null ? ListCredentials.from(accessKey, secretKey)
: ListCredentials.from(accessKey, secretKey, token);
}
MockRoute53Server credentials(String accessKey, String secretKey, String token) {
this.accessKey = accessKey;
this.secretKey = secretKey;
this.token = token;
return this;
}
void enqueue(MockResponse mockResponse) {
delegate.enqueue(mockResponse);
}
RecordedRequestAssert assertRequest() throws InterruptedException {
return assertThat(delegate.takeRequest());
}
void shutdown() throws IOException {
delegate.shutdown();
}
@Override
public Statement apply(Statement base, Description description) {
return delegate.apply(base, description);
}
@dagger.Module(injects = DNSApiManager.class, complete = false, includes =
Route53Provider.Module.class)
static final class Module {
}
}
| 248 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/HostedZonesReadableMockTest.java | package denominator.route53;
import com.squareup.okhttp.mockwebserver.MockResponse;
import org.junit.Rule;
import org.junit.Test;
import denominator.DNSApiManager;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HostedZonesReadableMockTest {
@Rule
public MockRoute53Server server = new MockRoute53Server();
@Test
public void singleRequestOnSuccess() throws Exception {
server.enqueue(new MockResponse().setBody("<ListHostedZonesResponse />"));
DNSApiManager api = server.connect();
assertTrue(api.checkConnection());
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone");
}
@Test
public void singleRequestOnFailure() throws Exception {
server.enqueue(new MockResponse().setResponseCode(403).setBody(
"<ErrorResponse xmlns=\"https:route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <Error>\n"
+ " <Type>Sender</Type>\n"
+ " <Code>InvalidClientTokenId</Code>\n"
+ " <Message>The security token included in the request is invalid</Message>\n"
+ " </Error>\n"
+ " <RequestId>d3801bc8-f70d-11e2-8a6e-435ba83aa63f</RequestId>\n"
+ "</ErrorResponse>"));
DNSApiManager api = server.connect();
assertFalse(api.checkConnection());
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone");
}
}
| 249 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53TestGraph.java | package denominator.route53;
import denominator.DNSApiManagerFactory;
import denominator.TestGraph;
import static feign.Util.emptyToNull;
import static java.lang.System.getProperty;
public class Route53TestGraph extends TestGraph {
private static final String url = emptyToNull(getProperty("route53.url"));
private static final String zone = emptyToNull(getProperty("route53.zone"));
public Route53TestGraph() {
super(DNSApiManagerFactory.create(new Route53Provider(url)), zone);
}
}
| 250 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/EncodeChangesTest.java | package denominator.route53;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import denominator.model.ResourceRecordSet;
import denominator.model.profile.Weighted;
import denominator.model.rdata.AData;
import denominator.model.rdata.CNAMEData;
import static denominator.model.ResourceRecordSets.a;
import static org.assertj.core.api.Assertions.assertThat;
public class EncodeChangesTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void defaultsTTLTo300() {
ResourceRecordSet<AData>
rrs =
a("www.denominator.io.", Arrays.asList("192.0.2.1", "192.0.2.2"));
assertThat(EncodeChanges.apply(rrs))
.isXmlEqualTo("<ResourceRecordSet>\n"
+ " <Name>www.denominator.io.</Name>\n"
+ " <Type>A</Type>\n"
+ " <TTL>300</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>192.0.2.1</Value>\n"
+ " </ResourceRecord>\n"
+ " <ResourceRecord>\n"
+ " <Value>192.0.2.2</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ "</ResourceRecordSet>");
}
@Test
public void encodeAliasRRSet() {
ResourceRecordSet<AliasTarget>
rrs =
ResourceRecordSet.<AliasTarget>builder().name("fooo.myzone.com.")
.type("A")
.add(AliasTarget.create("Z3I0BTR7N27QRM",
"ipv4-route53recordsetlivetest.adrianc.myzone.com.")).build();
assertThat(EncodeChanges.apply(rrs))
.isXmlEqualTo("<ResourceRecordSet>\n"
+ " <Name>fooo.myzone.com.</Name>\n"
+ " <Type>A</Type>\n"
+ " <AliasTarget>\n"
+ " <HostedZoneId>Z3I0BTR7N27QRM</HostedZoneId>\n"
+ " <DNSName>ipv4-route53recordsetlivetest.adrianc.myzone.com.</DNSName>\n"
+ " <EvaluateTargetHealth>false</EvaluateTargetHealth>\n"
+ " </AliasTarget>\n"
+ "</ResourceRecordSet>");
}
@Test
public void ignoreTTLOnAliasRRSet() {
ResourceRecordSet<AliasTarget>
rrs =
ResourceRecordSet.<AliasTarget>builder().name("fooo.myzone.com.")
.type("A").ttl(600)
.add(AliasTarget.create("Z3I0BTR7N27QRM",
"ipv4-route53recordsetlivetest.adrianc.myzone.com.")).build();
assertThat(EncodeChanges.apply(rrs))
.isXmlEqualTo("<ResourceRecordSet>\n"
+ " <Name>fooo.myzone.com.</Name>\n"
+ " <Type>A</Type>\n"
+ " <AliasTarget>\n"
+ " <HostedZoneId>Z3I0BTR7N27QRM</HostedZoneId>\n"
+ " <DNSName>ipv4-route53recordsetlivetest.adrianc.myzone.com.</DNSName>\n"
+ " <EvaluateTargetHealth>false</EvaluateTargetHealth>\n"
+ " </AliasTarget>\n"
+ "</ResourceRecordSet>");
}
@Test
public void aliasRRSetMissingDNSName() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("missing DNSName in alias target ResourceRecordSet");
Map<String, Object> missingDNSName = new LinkedHashMap<String, Object>();
missingDNSName.put("HostedZoneId", "Z3I0BTR7N27QRM");
ResourceRecordSet<Map<String, Object>> rrs = ResourceRecordSet.<Map<String, Object>>builder()
.name("fooo.myzone.com.").type("A")
.add(missingDNSName).build();
EncodeChanges.apply(rrs);
}
@Test
public void identifierAndWeightedElements() {
ResourceRecordSet<CNAMEData> rrs = ResourceRecordSet.<CNAMEData>builder()
.name("www.denominator.io.")
.type("CNAME")
.qualifier("foobar")
.add(CNAMEData.create("dom1.foo.com."))
.weighted(Weighted.create(1)).build();
assertThat(EncodeChanges.apply(rrs))
.isXmlEqualTo("<ResourceRecordSet>\n"
+ " <Name>www.denominator.io.</Name>\n"
+ " <Type>CNAME</Type>\n"
+ " <SetIdentifier>foobar</SetIdentifier>\n"
+ " <Weight>1</Weight>\n"
+ " <TTL>300</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>dom1.foo.com.</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ "</ResourceRecordSet>");
}
}
| 251 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53ResourceRecordSetApiMockTest.java | package denominator.route53;
import com.squareup.okhttp.mockwebserver.MockResponse;
import org.junit.Rule;
import org.junit.Test;
import java.util.Arrays;
import denominator.ResourceRecordSetApi;
import static denominator.assertj.ModelAssertions.assertThat;
import static denominator.model.ResourceRecordSets.a;
public class Route53ResourceRecordSetApiMockTest {
@Rule
public MockRoute53Server server = new MockRoute53Server();
@Test
public void weightedRecordSetsAreFilteredOut() throws Exception {
server.enqueue(new MockResponse().setBody(
"<ListResourceRecordSetsResponse><ResourceRecordSets><ResourceRecordSet><Name>www.denominator.io.</Name><Type>CNAME</Type><SetIdentifier>Route53Service:us-east-1:PLATFORMSERVICE:i-7f0aec0d:20130313205017</SetIdentifier><Weight>1</Weight><TTL>0</TTL><ResourceRecords><ResourceRecord><Value>www1.denominator.io.</Value></ResourceRecord></ResourceRecords></ResourceRecordSet><ResourceRecordSet><Name>www.denominator.io.</Name><Type>CNAME</Type><SetIdentifier>Route53Service:us-east-1:PLATFORMSERVICE:i-fbe41089:20130312203418</SetIdentifier><Weight>1</Weight><TTL>0</TTL><ResourceRecords><ResourceRecord><Value>www2.denominator.io.</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></ResourceRecordSets></ListResourceRecordSetsResponse>"));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
assertThat(api.getByNameAndType("www.denominator.io.", "CNAME")).isNull();
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=CNAME");
}
@Test
public void putFirstRecordCreatesNewRRSet() throws Exception {
server.enqueue(new MockResponse().setBody(noRecords));
server.enqueue(new MockResponse().setBody(changeSynced));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
api.put(a("www.denominator.io.", 3600, "192.0.2.1"));
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeBatch><Changes><Change><Action>CREATE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>");
}
@Test
public void putSameRecordNoOp() throws Exception {
server.enqueue(new MockResponse().setBody(oneRecord));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
api.put(a("www.denominator.io.", 3600, "192.0.2.1"));
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
}
@Test
public void putRecreates_ttlChanged() throws Exception {
server.enqueue(new MockResponse().setBody(oneRecord));
server.enqueue(new MockResponse().setBody(changeSynced));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
api.put(a("www.denominator.io.", 10000000, Arrays.asList("192.0.2.1")));
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeBatch><Changes><Change><Action>DELETE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change><Change><Action>CREATE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>10000000</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>");
}
@Test
public void putRecreates_recordAdded() throws Exception {
server.enqueue(new MockResponse().setBody(oneRecord));
server.enqueue(new MockResponse().setBody(changeSynced));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
api.put(a("www.denominator.io.", 3600, Arrays.asList("192.0.2.1", "198.51.100.1")));
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeBatch><Changes><Change><Action>DELETE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change><Change><Action>CREATE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord><ResourceRecord><Value>198.51.100.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>");
}
@Test
public void putOneRecordReplacesRRSet() throws Exception {
server.enqueue(new MockResponse().setBody(twoRecords));
server.enqueue(new MockResponse().setBody(changeSynced));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
api.put(a("www.denominator.io.", 3600, "192.0.2.1"));
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeBatch><Changes><Change><Action>DELETE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord><ResourceRecord><Value>198.51.100.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change><Change><Action>CREATE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>");
}
@Test
public void iterateByNameWhenPresent() throws Exception {
server.enqueue(new MockResponse().setBody(twoRecords));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
assertThat(api.iterateByName("www.denominator.io."))
.contains(a("www.denominator.io.", 3600, Arrays.asList("192.0.2.1", "198.51.100.1")));
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.");
}
@Test
public void iterateByNameWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setBody(noRecords));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
assertThat(api.iterateByName("www.denominator.io.")).isEmpty();
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.");
}
@Test
public void getByNameAndTypeWhenPresent() throws Exception {
server.enqueue(new MockResponse().setBody(twoRecords));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
assertThat(api.getByNameAndType("www.denominator.io.", "A"))
.isEqualTo(a("www.denominator.io.", 3600, Arrays.asList("192.0.2.1", "198.51.100.1")));
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
}
@Test
public void getByNameAndTypeWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setBody(noRecords));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
assertThat(api.getByNameAndType("www.denominator.io.", "A")).isNull();
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
}
@Test
public void deleteRRSet() throws Exception {
server.enqueue(new MockResponse().setBody(twoRecords));
server.enqueue(new MockResponse().setBody(changeSynced));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
api.deleteByNameAndType("www.denominator.io.", "A");
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www.denominator.io.&type=A");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeBatch><Changes><Change><Action>DELETE</Action><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord><ResourceRecord><Value>198.51.100.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>");
}
@Test
public void deleteAbsentRRSDoesNothing() throws Exception {
server.enqueue(new MockResponse().setBody(oneRecord));
ResourceRecordSetApi api = server.connect().api().basicRecordSetsInZone("Z1PA6795UKMFR9");
api.deleteByNameAndType("www1.denominator.io.", "A");
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=www1.denominator.io.&type=A");
}
String
noRecords =
"<ListResourceRecordSetsResponse><ResourceRecordSets></ResourceRecordSets></ListResourceRecordSetsResponse>";
String
changeSynced =
"<GetChangeResponse><ChangeInfo><Id>/change/C2682N5HXP0BZ4</Id><Status>INSYNC</Status><SubmittedAt>2011-09-10T01:36:41.958Z</SubmittedAt></ChangeInfo></GetChangeResponse>";
String
oneRecord =
"<ListResourceRecordSetsResponse><ResourceRecordSets><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></ResourceRecordSets></ListResourceRecordSetsResponse>";
String
twoRecords =
"<ListResourceRecordSetsResponse><ResourceRecordSets><ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord><ResourceRecord><Value>198.51.100.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></ResourceRecordSets></ListResourceRecordSetsResponse>";
}
| 252 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53WeightedReadOnlyLiveTest.java | package denominator.route53;
import denominator.Live.UseTestGraph;
import denominator.profile.WeightedReadOnlyLiveTest;
@UseTestGraph(Route53TestGraph.class)
public class Route53WeightedReadOnlyLiveTest extends WeightedReadOnlyLiveTest {
}
| 253 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53ZoneApiMockTest.java | package denominator.route53;
import com.squareup.okhttp.mockwebserver.MockResponse;
import org.junit.Rule;
import org.junit.Test;
import java.util.Iterator;
import denominator.ZoneApi;
import denominator.model.Zone;
import static denominator.assertj.ModelAssertions.assertThat;
public class Route53ZoneApiMockTest {
@Rule
public MockRoute53Server server = new MockRoute53Server();
@Test
public void iteratorWhenPresent() throws Exception {
server.enqueue(new MockResponse().setBody(
"<ListHostedZonesResponse>\n"
+ " <HostedZones>\n"
+ " <HostedZone>\n"
+ " <Id>/hostedzone/Z1PA6795UKMFR9</Id>\n"
+ " <Name>denominator.io.</Name>\n"
+ " <CallerReference>denomination</CallerReference>\n"
+ " <Config>\n"
+ " <Comment>no comment</Comment>\n"
+ " </Config>\n"
+ " <ResourceRecordSetCount>17</ResourceRecordSetCount>\n"
+ " </HostedZone>\n"
+ " </HostedZones>\n"
+ "</ListHostedZonesResponse>"));
server.enqueue(new MockResponse().setBody(
"<?xml version=\"1.0\"?>\n"
+ "<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ soaRRSet
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
ZoneApi api = server.connect().api().zones();
Iterator<Zone> domains = api.iterator();
assertThat(domains).containsExactly(
Zone.create("Z1PA6795UKMFR9", "denominator.io.", 3601, "test@denominator.io")
);
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=denominator.io.&type=SOA");
}
@Test
public void iteratorWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setBody(
"<ListHostedZonesResponse><HostedZones /></ListHostedZonesResponse>"));
ZoneApi api = server.connect().api().zones();
assertThat(api.iterator()).isEmpty();
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone");
}
@Test
public void iterateByNameWhenPresent() throws Exception {
server.enqueue(new MockResponse().setBody(
"<ListHostedZonesByNameResponse xmlns=\"https://route53.amazonaws.com/doc/2013-04-01/\">\n"
+ " <HostedZones>\n"
+ " <HostedZone>\n"
+ " <Id>/hostedzone/Z2ZEEJCUZCVG56</Id>\n"
+ " <Name>denominator.io.</Name>\n"
+ " <CallerReference>Foo</CallerReference>\n"
+ " <Config>\n"
+ " <PrivateZone>false</PrivateZone>\n"
+ " </Config>\n"
+ " <ResourceRecordSetCount>3</ResourceRecordSetCount>\n"
+ " </HostedZone>\n"
+ " <HostedZone>\n"
+ " <Id>/hostedzone/Z3OQLQGABCU3T</Id>\n"
+ " <Name>denominator.io.</Name>\n"
+ " <CallerReference>Bar</CallerReference>\n"
+ " <Config>\n"
+ " <PrivateZone>false</PrivateZone>\n"
+ " </Config>\n"
+ " <ResourceRecordSetCount>2</ResourceRecordSetCount>\n"
+ " </HostedZone>\n"
+ " </HostedZones>\n"
+ " <DNSName>denominator.io.</DNSName>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListHostedZonesByNameResponse>"));
server.enqueue(new MockResponse().setBody(
"<?xml version=\"1.0\"?>\n"
+ "<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ soaRRSet
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
server.enqueue(new MockResponse().setBody(
"<?xml version=\"1.0\"?>\n"
+ "<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ soaRRSet
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
ZoneApi api = server.connect().api().zones();
assertThat(api.iterateByName("denominator.io.")).containsExactly(
Zone.create("Z2ZEEJCUZCVG56", "denominator.io.", 3601, "test@denominator.io"),
Zone.create("Z3OQLQGABCU3T", "denominator.io.", 3601, "test@denominator.io")
);
server.assertRequest()
.hasMethod("GET")
.hasPath("/2013-04-01/hostedzonesbyname?dnsname=denominator.io.");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z2ZEEJCUZCVG56/rrset?name=denominator.io.&type=SOA");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z3OQLQGABCU3T/rrset?name=denominator.io.&type=SOA");
}
/**
* Route53 list by name is only about order. We need to ensure we skip irrelevant zones.
*/
@Test
public void iterateByNameWhenIrrelevant() throws Exception {
server.enqueue(new MockResponse().setBody(
"<ListHostedZonesByNameResponse xmlns=\"https://route53.amazonaws.com/doc/2013-04-01/\">\n"
+ " <HostedZones>\n"
+ " <HostedZone>\n"
+ " <Id>/hostedzone/Z2ZEEJCUZCVG56</Id>\n"
+ " <Name>denominator.io.</Name>\n"
+ " <CallerReference>Foo</CallerReference>\n"
+ " <Config>\n"
+ " <PrivateZone>false</PrivateZone>\n"
+ " </Config>\n"
+ " <ResourceRecordSetCount>3</ResourceRecordSetCount>\n"
+ " </HostedZone>\n"
+ " </HostedZones>\n"
+ " <DNSName>denominator.io.</DNSName>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListHostedZonesByNameResponse>"));
ZoneApi api = server.connect().api().zones();
assertThat(api.iterateByName("denominator.com.")).isEmpty();
server.assertRequest()
.hasMethod("GET")
.hasPath("/2013-04-01/hostedzonesbyname?dnsname=denominator.com.");
}
@Test
public void iterateByNameWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setBody(
"<ListHostedZonesByNameResponse><HostedZones /></ListHostedZonesByNameResponse>"));
ZoneApi api = server.connect().api().zones();
assertThat(api.iterateByName("denominator.io.")).isEmpty();
server.assertRequest()
.hasMethod("GET")
.hasPath("/2013-04-01/hostedzonesbyname?dnsname=denominator.io.");
}
@Test
public void putWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setBody(
"<CreateHostedZoneResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <HostedZone>\n"
+ " <Id>/hostedzone/Z1PA6795UKMFR9</Id>\n"
+ " <Name>denominator.io.</Name>\n"
+ " <CallerReference>a228ebcc-0c93-4627-8fff-1b899f5de2a4</CallerReference>\n"
+ " <Config/>\n"
+ " <ResourceRecordSetCount>2</ResourceRecordSetCount>\n"
+ " </HostedZone>\n"
+ " <ChangeInfo>\n"
+ " <Id>/change/C1DMRYCM7MK76K</Id>\n"
+ " <Status>PENDING</Status>\n"
+ " <SubmittedAt>2015-04-04T02:50:41.602Z</SubmittedAt>\n"
+ " </ChangeInfo>\n"
+ " <DelegationSet>\n"
+ " <NameServers>\n"
+ " <NameServer>ns-534.awsdns-02.net</NameServer>\n"
+ " <NameServer>ns-448.awsdns-56.com</NameServer>\n"
+ " <NameServer>ns-1296.awsdns-34.org</NameServer>\n"
+ " <NameServer>ns-1725.awsdns-23.co.uk</NameServer>\n"
+ " </NameServers>\n"
+ " </DelegationSet>\n"
+ "</CreateHostedZoneResponse>"
));
server.enqueue(new MockResponse().setBody(
"<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ initialSOA
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
server.enqueue(changingRRSets);
ZoneApi api = server.connect().api().zones();
Zone zone = Zone.create(null, "denominator.io.", 3601, "test@denominator.io");
assertThat(api.put(zone)).isEqualTo("Z1PA6795UKMFR9");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=denominator.io.&type=SOA");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ChangeBatch>\n"
+ " <Changes>\n"
+ " <Change>\n"
+ " <Action>DELETE</Action>\n"
+ initialSOA
+ " </Change>\n"
+ " <Change>\n"
+ " <Action>CREATE</Action>\n"
+ soaRRSet
+ " </Change>\n"
+ " </Changes>\n"
+ " </ChangeBatch>\n"
+ "</ChangeResourceRecordSetsRequest>");
}
@Test
public void putWhenPresent_changingSOA() throws Exception {
server.enqueue(new MockResponse().setBody(
"<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ initialSOA
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
server.enqueue(changingRRSets);
ZoneApi api = server.connect().api().zones();
Zone zone = Zone.create("Z1PA6795UKMFR9", "denominator.io.", 3601, "test@denominator.io");
assertThat(api.put(zone)).isEqualTo(zone.id());
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=denominator.io.&type=SOA");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ChangeBatch>\n"
+ " <Changes>\n"
+ " <Change>\n"
+ " <Action>DELETE</Action>\n"
+ initialSOA
+ " </Change>\n"
+ " <Change>\n"
+ " <Action>CREATE</Action>\n"
+ soaRRSet
+ " </Change>\n"
+ " </Changes>\n"
+ " </ChangeBatch>\n"
+ "</ChangeResourceRecordSetsRequest>");
}
@Test
public void putWhenPresent_noop() throws Exception {
server.enqueue(new MockResponse().setBody(
"<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ soaRRSet
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
ZoneApi api = server.connect().api().zones();
Zone zone = Zone.create("Z1PA6795UKMFR9", "denominator.io.", 3601, "test@denominator.io");
assertThat(api.put(zone)).isEqualTo(zone.id());
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=denominator.io.&type=SOA");
}
@Test
public void deleteWhenPresent() throws Exception {
server.enqueue(oneZone);
server.enqueue(new MockResponse().setBody(
"<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ nsRRSet
+ soaRRSet
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>2</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
server.enqueue(deletingZone);
ZoneApi api = server.connect().api().zones();
api.delete("Z1PA6795UKMFR9");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset");
server.assertRequest()
.hasMethod("DELETE")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9");
}
@Test
public void deleteWhenPresent_extraRRSet() throws Exception {
// Only rrset we expect to delete manually
String aRecord = " <ResourceRecordSet>\n"
+ " <Name>ns-google.denominator.io.</Name>\n"
+ " <Type>A</Type>\n"
+ " <TTL>300</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>8.8.8.8</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ " </ResourceRecordSet>\n";
server.enqueue(oneZone);
server.enqueue(new MockResponse().setBody(
"<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ nsRRSet
+ soaRRSet
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>true</IsTruncated>\n"
+ " <NextRecordName>ns-google.denominator.io.</NextRecordName>\n"
+ " <NextRecordType>A</NextRecordType>\n"
+ " <MaxItems>2</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
server.enqueue(new MockResponse().setBody(
"<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ aRecord
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>2</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"
));
server.enqueue(changingRRSets);
server.enqueue(deletingZone);
ZoneApi api = server.connect().api().zones();
api.delete("Z1PA6795UKMFR9");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset");
server.assertRequest()
.hasMethod("GET")
.hasPath(
"/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset?name=ns-google.denominator.io.&type=A");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ChangeBatch>\n"
+ " <Changes>\n"
+ " <Change>\n"
+ " <Action>DELETE</Action>\n"
+ aRecord
+ " </Change>\n"
+ " </Changes>\n"
+ " </ChangeBatch>\n"
+ "</ChangeResourceRecordSetsRequest>");
server.assertRequest()
.hasMethod("DELETE")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9");
}
@Test
public void deleteWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setResponseCode(404).setBody(
"<ErrorResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><Error><Type>Sender</Type><Code>NoSuchHostedZone</Code><Message>The specified hosted zone does not exist.</Message></Error><RequestId>d1862286-da13-11e4-a87a-f78bcee90724</RequestId></ErrorResponse>"));
ZoneApi api = server.connect().api().zones();
api.delete("Z1PA6795UKMFR9");
server.assertRequest()
.hasMethod("GET")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9");
}
private String soaRRSet = " <ResourceRecordSet>\n"
+ " <Name>denominator.io.</Name>\n"
+ " <Type>SOA</Type>\n"
+ " <TTL>3601</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-1612.awsdns-27.net. test@denominator.io 2 7200 3601 1209600 86400</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ " </ResourceRecordSet>\n";
private String initialSOA = // Initially SOA has a TTL of 900, an amazon rname and serial number 1
soaRRSet.replaceFirst("3601", "900").replace("test@denominator.io 2",
"awsdns-hostmaster.amazon.com. 1");
private String nsRRSet = " <ResourceRecordSet>\n"
+ " <Name>denominator.io.</Name>\n"
+ " <Type>NS</Type>\n"
+ " <TTL>172800</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-1612.awsdns-09.co.uk.</Value>\n"
+ " </ResourceRecord>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-230.awsdns-28.com.</Value>\n"
+ " </ResourceRecord>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-993.awsdns-60.net.</Value>\n"
+ " </ResourceRecord>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-1398.awsdns-46.org.</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ " </ResourceRecordSet>\n";
private MockResponse oneZone = new MockResponse().setBody(
"<ListHostedZonesResponse>\n"
+ " <HostedZones>\n"
+ " <HostedZone>\n"
+ " <Id>/hostedzone/Z1PA6795UKMFR9</Id>\n"
+ " <Name>denominator.io.</Name>\n"
+ " <CallerReference>denomination</CallerReference>\n"
+ " <Config>\n"
+ " <Comment>no comment</Comment>\n"
+ " </Config>\n"
+ " <ResourceRecordSetCount>3</ResourceRecordSetCount>\n"
+ " </HostedZone>\n"
+ " </HostedZones>\n"
+ "</ListHostedZonesResponse>");
private MockResponse changingRRSets = new MockResponse().setBody(
"<ChangeResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeInfo><Id>/change/CWWCRAXTKEB72d</Id><Status>PENDING</Status><SubmittedAt>2015-04-03T14:41:54.371Z</SubmittedAt></ChangeInfo></ChangeResourceRecordSetsResponse>"
);
private MockResponse deletingZone = new MockResponse().setBody(
"<DeleteHostedZoneResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeInfo><Id>/change/C1QB5QU6VYXUHE</Id><Status>PENDING</Status><SubmittedAt>2015-04-03T14:41:54.512Z</SubmittedAt></ChangeInfo></DeleteHostedZoneResponse>"
);
}
| 254 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53WriteCommandsLiveTest.java | package denominator.route53;
import denominator.Live.UseTestGraph;
import denominator.WriteCommandsLiveTest;
@UseTestGraph(Route53TestGraph.class)
public class Route53WriteCommandsLiveTest extends WriteCommandsLiveTest {
}
| 255 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53Test.java | package denominator.route53;
import com.squareup.okhttp.mockwebserver.MockResponse;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import denominator.Credentials;
import denominator.model.ResourceRecordSet;
import denominator.route53.Route53.ActionOnResourceRecordSet;
import feign.Feign;
import static denominator.model.ResourceRecordSets.a;
public class Route53Test {
@Rule
public MockRoute53Server server = new MockRoute53Server();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void changeResourceRecordSetsRequestCreateAPending() throws Exception {
server.enqueue(new MockResponse().setBody(changeResourceRecordSetsResponsePending));
ActionOnResourceRecordSet
createA =
ActionOnResourceRecordSet.create(a("www.denominator.io.", 3600, "192.0.2.1"));
mockApi().changeResourceRecordSets("Z1PA6795UKMFR9", Arrays.asList(createA));
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(changeResourceRecordSetsRequestCreateA);
}
@Test
public void changeResourceRecordSetsWhenAliasTarget() throws Exception {
server.enqueue(new MockResponse().setBody(changeResourceRecordSetsResponsePending));
ActionOnResourceRecordSet createAlias = ActionOnResourceRecordSet
.create(ResourceRecordSet
.<AliasTarget>builder()
.name("www.denominator.io.")
.type("A")
.add(AliasTarget
.create(
"Z3I0BTR7N27QRM",
"ipv4-route53recordsetlivetest.adrianc.myzone.com."))
.build());
mockApi().changeResourceRecordSets("Z1PA6795UKMFR9", Arrays.asList(createAlias));
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795UKMFR9/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ChangeBatch>\n"
+ " <Changes>\n"
+ " <Change>\n"
+ " <Action>CREATE</Action>\n"
+ " <ResourceRecordSet>\n"
+ " <Name>www.denominator.io.</Name>\n"
+ " <Type>A</Type>\n"
+ " <AliasTarget>\n"
+ " <HostedZoneId>Z3I0BTR7N27QRM</HostedZoneId>\n"
+ " <DNSName>ipv4-route53recordsetlivetest.adrianc.myzone.com.</DNSName>\n"
+ " <EvaluateTargetHealth>false</EvaluateTargetHealth>\n"
+ " </AliasTarget>\n"
+ " </ResourceRecordSet>\n"
+ " </Change>\n"
+ " </Changes>\n"
+ " </ChangeBatch>\n"
+ "</ChangeResourceRecordSetsRequest>");
}
@Test
public void changeResourceRecordSetsRequestCreateADuplicate() throws Exception {
thrown.expect(InvalidChangeBatchException.class);
thrown.expectMessage(
"Route53#changeResourceRecordSets(String,List) failed with errors [Tried to create resource record set www.denominator.io. type A, but it already exists]");
server.enqueue(new MockResponse().setResponseCode(400).setBody(
"<InvalidChangeBatch xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <Messages>\n"
+ " <Message>Tried to create resource record set www.denominator.io. type A, but it already exists</Message>\n"
+ " </Messages>\n"
+ "</InvalidChangeBatch>"));
ActionOnResourceRecordSet
createA =
ActionOnResourceRecordSet.create(a("www.denominator.io.", 3600, "192.0.2.1"));
mockApi().changeResourceRecordSets("Z1PA6795UKMFR9", Arrays.asList(createA));
}
Route53 mockApi() {
Route53Provider.FeignModule module = new Route53Provider.FeignModule();
Feign feign = module.feign(module.logger(), module.logLevel());
return feign.newInstance(new Route53Target(new Route53Provider() {
@Override
public String url() {
return server.url();
}
}, new InvalidatableAuthenticationHeadersProvider(new javax.inject.Provider<Credentials>() {
@Override
public Credentials get() {
return server.credentials();
}
})));
}
String changeResourceRecordSetsRequestCreateA =
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">"
+ "<ChangeBatch><Changes><Change><Action>CREATE</Action>"
+ "<ResourceRecordSet><Name>www.denominator.io.</Name><Type>A</Type><TTL>3600</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet>"
+ "</Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>";
String changeResourceRecordSetsResponsePending =
"<ChangeResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ChangeInfo>\n"
+ " <Id>/change/C2682N5HXP0BZ4</Id>\n"
+ " <Status>PENDING</Status>\n"
+ " <SubmittedAt>2010-09-10T01:36:41.958Z</SubmittedAt>\n"
+ " </ChangeInfo>\n"
+ "</ChangeResourceRecordSetsResponse>";
}
| 256 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53WeightedWriteCommandsLiveTest.java | package denominator.route53;
import denominator.Live.UseTestGraph;
import denominator.profile.WeightedWriteCommandsLiveTest;
@UseTestGraph(Route53TestGraph.class)
public class Route53WeightedWriteCommandsLiveTest extends WeightedWriteCommandsLiveTest {
}
| 257 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53DecoderTest.java | package denominator.route53;
import org.junit.Test;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import denominator.model.rdata.AData;
import denominator.model.rdata.NSData;
import denominator.model.rdata.SOAData;
import denominator.route53.Route53.HostedZoneList;
import denominator.route53.Route53.ResourceRecordSetList;
import feign.Response;
import feign.codec.Decoder;
import static denominator.assertj.ModelAssertions.assertThat;
import static feign.Util.UTF_8;
import static org.assertj.core.api.Assertions.tuple;
public class Route53DecoderTest {
Decoder decoder = new Route53Provider.FeignModule().decoder();
@Test
public void decodeZoneListWithNext() throws Exception {
HostedZoneList result = (HostedZoneList) decoder.decode(response(
"<ListHostedZonesResponse xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\">\n"
+ " <HostedZones>\n"
+ " <HostedZone>\n"
+ " <Id>/hostedzone/Z21DW1QVGID6NG</Id>\n"
+ " <Name>example.com.</Name>\n"
+ " <CallerReference>a_unique_reference</CallerReference>\n"
+ " <Config>\n"
+ " <Comment>Migrate an existing domain to Route 53</Comment>\n"
+ " </Config>\n"
+ " <ResourceRecordSetCount>17</ResourceRecordSetCount>\n"
+ " </HostedZone>\n"
+ " <HostedZone>\n"
+ " <Id>/hostedzone/Z2682N5HXP0BZ4</Id>\n"
+ " <Name>example2.com.</Name>\n"
+ " <CallerReference>a_unique_reference2</CallerReference>\n"
+ " <Config>\n"
+ " <Comment>This is my 2nd hosted zone.</Comment>\n"
+ " </Config>\n"
+ " <ResourceRecordSetCount>117</ResourceRecordSetCount>\n"
+ " </HostedZone>\n"
+ " </HostedZones>\n"
+ " <Marker>Z222222VVVVVVV</Marker>\n"
+ " <IsTruncated>true</IsTruncated>\n"
+ " <NextMarker>Z333333YYYYYYY</NextMarker>\n"
+ " <MaxItems>10</MaxItems>\n"
+ "</ListHostedZonesResponse>"), HostedZoneList.class);
assertThat(result).extracting("name", "id").containsExactly(
tuple("example.com.", "Z21DW1QVGID6NG"),
tuple("example2.com.", "Z2682N5HXP0BZ4")
);
assertThat(result.next).isEqualTo("Z333333YYYYYYY");
}
@Test
public void decodeBasicResourceRecordSetListWithNext() throws Exception {
ResourceRecordSetList result = (ResourceRecordSetList) decoder.decode(response(
"<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\">\n"
+ " <ResourceRecordSets>\n"
+ " <ResourceRecordSet>\n"
+ " <Name>example.com.</Name>\n"
+ " <Type>SOA</Type>\n"
+ " <TTL>900</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-2048.awsdns-64.net. hostmaster.awsdns.com. 1 7200 900 1209600 86400</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ " </ResourceRecordSet>\n"
+ " <ResourceRecordSet>\n"
+ " <Name>example.com.</Name>\n"
+ " <Type>NS</Type>\n"
+ " <TTL>172800</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-2048.awsdns-64.com.</Value>\n"
+ " </ResourceRecord>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-2049.awsdns-65.net.</Value>\n"
+ " </ResourceRecord>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-2050.awsdns-66.org.</Value>\n"
+ " </ResourceRecord>\n"
+ " <ResourceRecord>\n"
+ " <Value>ns-2051.awsdns-67.co.uk.</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ " </ResourceRecordSet>\n"
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>true</IsTruncated>\n"
+ " <MaxItems>3</MaxItems>\n"
+ " <NextRecordName>testdoc2.example.com</NextRecordName>\n"
+ " <NextRecordType>NS</NextRecordType>\n"
+ "</ListResourceRecordSetsResponse>"),
ResourceRecordSetList.class);
assertThat(result.get(0))
.hasName("example.com.")
.hasType("SOA")
.hasTtl(900)
.containsExactlyRecords(SOAData.builder()
.mname("ns-2048.awsdns-64.net.")
.rname("hostmaster.awsdns.com.")
.serial(1)
.refresh(7200)
.retry(900)
.expire(1209600)
.minimum(86400)
.build());
assertThat(result.get(1))
.hasName("example.com.")
.hasType("NS")
.hasTtl(172800)
.containsExactlyRecords(NSData.create("ns-2048.awsdns-64.com."),
NSData.create("ns-2049.awsdns-65.net."),
NSData.create("ns-2050.awsdns-66.org."),
NSData.create("ns-2051.awsdns-67.co.uk."));
assertThat(result.next.name).isEqualTo("testdoc2.example.com");
assertThat(result.next.type).isEqualTo("NS");
assertThat(result.next.identifier).isNull();
}
@Test
public void decodeAdvancedResourceRecordSetListWithoutNext() throws Exception {
ResourceRecordSetList
result =
(ResourceRecordSetList) decoder.decode(response(
"<ListResourceRecordSetsResponse xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ResourceRecordSets>\n"
+ " <ResourceRecordSet>\n"
+ " <Name>apple.myzone.com.</Name>\n"
+ " <Type>A</Type>\n"
+ " <SetIdentifier>foobar</SetIdentifier>\n"
+ " <Weight>1</Weight>\n"
+ " <TTL>300</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>1.2.3.4</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ " </ResourceRecordSet>\n"
+ " <ResourceRecordSet>\n"
+ " <Name>fooo.myzone.com.</Name>\n"
+ " <Type>A</Type>\n"
+ " <AliasTarget>\n"
+ " <HostedZoneId>Z3I0BTR7N27QRM</HostedZoneId>\n"
+ " <DNSName>ipv4-route53recordsetlivetest.adrianc.myzone.com.</DNSName>\n"
+ " <EvaluateTargetHealth>false</EvaluateTargetHealth>\n"
+ " </AliasTarget>\n"
+ " </ResourceRecordSet>\n"
+ " </ResourceRecordSets>\n"
+ " <IsTruncated>false</IsTruncated>\n"
+ " <MaxItems>100</MaxItems>\n"
+ "</ListResourceRecordSetsResponse>"),
ResourceRecordSetList.class);
assertThat(result.get(0))
.hasName("apple.myzone.com.")
.hasType("A")
.hasQualifier("foobar")
.hasTtl(300)
.hasWeight(1)
.containsExactlyRecords(AData.create("1.2.3.4"));
assertThat(result.get(1))
.hasName("fooo.myzone.com.")
.hasType("A")
.containsExactlyRecords(AliasTarget.create("Z3I0BTR7N27QRM",
"ipv4-route53recordsetlivetest.adrianc.myzone.com."));
assertThat(result.next).isNull();
}
private Response response(String xml) throws IOException {
return Response
.create(200, "OK", Collections.<String, Collection<String>>emptyMap(), xml, UTF_8);
}
}
| 258 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53ZoneWriteCommandsLiveTest.java | package denominator.route53;
import denominator.Live.UseTestGraph;
import denominator.ZoneWriteCommandsLiveTest;
@UseTestGraph(Route53TestGraph.class)
public class Route53ZoneWriteCommandsLiveTest extends ZoneWriteCommandsLiveTest {
}
| 259 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53ProviderDynamicUpdateMockTest.java | package denominator.route53;
import com.squareup.okhttp.mockwebserver.MockResponse;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicReference;
import dagger.Module;
import dagger.Provides;
import denominator.Credentials;
import denominator.Credentials.ListCredentials;
import denominator.DNSApi;
import denominator.Denominator;
import static denominator.CredentialsConfiguration.credentials;
public class Route53ProviderDynamicUpdateMockTest {
@Rule
public MockRoute53Server server = new MockRoute53Server();
String hostedZones = "<ListHostedZonesResponse><HostedZones /></ListHostedZonesResponse>";
@Test
public void dynamicEndpointUpdates() throws Exception {
final AtomicReference<String> url = new AtomicReference<String>(server.url());
server.enqueue(new MockResponse().setBody(hostedZones));
DNSApi api = Denominator.create(new Route53Provider() {
@Override
public String url() {
return url.get();
}
}, credentials(server.credentials())).api();
api.zones().iterator();
server.assertRequest();
MockRoute53Server server2 = new MockRoute53Server();
url.set(server2.url());
server2.enqueue(new MockResponse().setBody(hostedZones));
api.zones().iterator();
server2.assertRequest();
server2.shutdown();
}
@Test
public void dynamicCredentialUpdates() throws Exception {
server.enqueue(new MockResponse().setBody(hostedZones));
AtomicReference<Credentials>
dynamicCredentials =
new AtomicReference<Credentials>(server.credentials());
DNSApi
api =
Denominator.create(server, new OverrideCredentials(dynamicCredentials)).api();
api.zones().iterator();
server.assertRequest().hasHeaderContaining("X-Amzn-Authorization", "accessKey");
dynamicCredentials.set(ListCredentials.from("accessKey2", "secretKey2", "token"));
server.credentials("accessKey2", "secretKey2", "token");
server.enqueue(new MockResponse().setBody(hostedZones));
api.zones().iterator();
server.assertRequest().hasHeaderContaining("X-Amzn-Authorization", "accessKey2");
}
@Module(complete = false, library = true, overrides = true)
static class OverrideCredentials {
final AtomicReference<Credentials> dynamicCredentials;
OverrideCredentials(AtomicReference<Credentials> dynamicCredentials) {
this.dynamicCredentials = dynamicCredentials;
}
@Provides
public Credentials get() {
return dynamicCredentials.get();
}
}
}
| 260 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53ProviderTest.java | package denominator.route53;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import dagger.ObjectGraph;
import denominator.Credentials.MapCredentials;
import denominator.DNSApiManager;
import denominator.Provider;
import static denominator.CredentialsConfiguration.anonymous;
import static denominator.CredentialsConfiguration.credentials;
import static denominator.Denominator.create;
import static denominator.Providers.list;
import static denominator.Providers.provide;
import static org.assertj.core.api.Assertions.assertThat;
public class Route53ProviderTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private static final Provider PROVIDER = new Route53Provider();
@Test
public void testRoute53Metadata() {
assertThat(PROVIDER.name()).isEqualTo("route53");
assertThat(PROVIDER.supportsDuplicateZoneNames()).isTrue();
assertThat(PROVIDER.credentialTypeToParameterNames())
.containsEntry("accessKey", Arrays.asList("accessKey", "secretKey"))
.containsEntry("session", Arrays.asList("accessKey", "secretKey", "sessionToken"));
}
@Test
public void testRoute53Registered() {
assertThat(list()).contains(PROVIDER);
}
@Test
public void testProviderWiresRoute53ZoneApiWithAccessKeyCredentials() {
DNSApiManager manager = create(PROVIDER, credentials("accesskey", "secretkey"));
assertThat(manager.api().zones()).isInstanceOf(Route53ZoneApi.class);
manager = create("route53", credentials("accesskey", "secretkey"));
assertThat(manager.api().zones()).isInstanceOf(Route53ZoneApi.class);
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("accesskey", "A");
map.put("secretkey", "S");
manager = create("route53", credentials(MapCredentials.from(map)));
assertThat(manager.api().zones()).isInstanceOf(Route53ZoneApi.class);
}
@Test
public void testProviderWiresRoute53ZoneApiWithSessionCredentials() {
DNSApiManager manager = create(PROVIDER, credentials("accesskey", "secretkey", "sessionToken"));
assertThat(manager.api().zones()).isInstanceOf(Route53ZoneApi.class);
manager = create("route53", credentials("accesskey", "secretkey", "sessionToken"));
assertThat(manager.api().zones()).isInstanceOf(Route53ZoneApi.class);
}
@Test
public void testCredentialsRequired() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(
"no credentials supplied. route53 requires one of the following forms: when type is accessKey: accessKey,secretKey; session: accessKey,secretKey,sessionToken");
// manually passing anonymous in case this test is executed from EC2
// where IAM profiles are present.
create(PROVIDER, anonymous()).api().zones().iterator();
}
@Test
public void testViaDagger() {
DNSApiManager manager = ObjectGraph
.create(provide(new Route53Provider()), new Route53Provider.Module(),
credentials("accesskey", "secretkey"))
.get(DNSApiManager.class);
assertThat(manager.api().zones()).isInstanceOf(Route53ZoneApi.class);
}
}
| 261 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/InstanceProfileCredentialsProviderTest.java | package denominator.route53;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import denominator.Credentials.MapCredentials;
import denominator.hook.InstanceMetadataHook;
import denominator.route53.InstanceProfileCredentialsProvider.ReadFirstInstanceProfileCredentialsOrNull;
import static denominator.assertj.MockWebServerAssertions.assertThat;
public class InstanceProfileCredentialsProviderTest {
@Rule
public MockWebServer server = new MockWebServer();
@Test
public void whenInstanceProfileCredentialsInMetadataServiceReturnMapCredentials()
throws Exception {
server.enqueue(new MockResponse().setBody("route53-readonly"));
server.enqueue(new MockResponse().setBody(securityCredentials));
Map<String, String> sessionCredentials = new LinkedHashMap<String, String>();
sessionCredentials.put("accessKey", "AAAAA");
sessionCredentials.put("secretKey", "SSSSSSS");
sessionCredentials.put("sessionToken", "TTTTTTT");
assertThat(new InstanceProfileCredentialsProvider(
new ReadFirstInstanceProfileCredentialsOrNull(server
.getUrl(
InstanceMetadataHook.DEFAULT_URI
.getPath())
.toURI())).get(
new Route53Provider()))
.isEqualTo(MapCredentials.from(sessionCredentials));
assertThat(server.takeRequest()).hasPath("/latest/meta-data/iam/security-credentials/");
assertThat(server.takeRequest())
.hasPath("/latest/meta-data/iam/security-credentials/route53-readonly");
}
@Test
public void whenNoInstanceProfileCredentialsInMetadataServiceReturnNull() throws Exception {
server.enqueue(new MockResponse().setBody(""));
assertThat(new ReadFirstInstanceProfileCredentialsOrNull(server.getUrl(
InstanceMetadataHook.DEFAULT_URI.getPath()).toURI()).get()).isNull();
assertThat(server.takeRequest()).hasPath("/latest/meta-data/iam/security-credentials/");
}
@Test
public void whenInstanceProfileCredentialsInMetadataServiceReturnJson() throws Exception {
server.enqueue(new MockResponse().setBody("route53-readonly"));
server.enqueue(new MockResponse().setBody(securityCredentials));
assertThat(new ReadFirstInstanceProfileCredentialsOrNull(server.getUrl(
InstanceMetadataHook.DEFAULT_URI.getPath()).toURI()).get())
.isEqualTo(securityCredentials);
assertThat(server.takeRequest()).hasPath("/latest/meta-data/iam/security-credentials/");
assertThat(server.takeRequest()).hasPath(
"/latest/meta-data/iam/security-credentials/route53-readonly");
}
@Test
public void whenMultipleInstanceProfileCredentialsInMetadataServiceReturnJsonFromFirst()
throws Exception {
server.enqueue(new MockResponse().setBody("route53-readonly\nbooberry"));
server.enqueue(new MockResponse().setBody(securityCredentials));
assertThat(new ReadFirstInstanceProfileCredentialsOrNull(server.getUrl(
InstanceMetadataHook.DEFAULT_URI.getPath()).toURI()).get())
.isEqualTo(securityCredentials);
assertThat(server.takeRequest()).hasPath("/latest/meta-data/iam/security-credentials/");
assertThat(server.takeRequest()).hasPath(
"/latest/meta-data/iam/security-credentials/route53-readonly");
}
@Test
public void testParseInstanceProfileCredentialsFromJsonWhenNull() {
assertThat(InstanceProfileCredentialsProvider.parseJson(null)).isEmpty();
}
@Test
public void testParseInstanceProfileCredentialsFromJsonWhenWrongKeys() {
assertThat(InstanceProfileCredentialsProvider.parseJson("{\"Code\" : \"Failure\"}")).isEmpty();
}
@Test
public void testParseInstanceProfileCredentialsFromJsonWhenAccessAndSecretPresent() {
assertThat(
InstanceProfileCredentialsProvider
.parseJson(
"{\"AccessKeyId\" : \"AAAAA\",\"SecretAccessKey\" : \"SSSSSSS\"}"))
.containsEntry("accessKey", "AAAAA")
.containsEntry("secretKey", "SSSSSSS");
}
@Test
public void testParseInstanceProfileCredentialsFromJsonWhenAccessSecretAndTokenPresent() {
assertThat(
InstanceProfileCredentialsProvider
.parseJson(
"{\"AccessKeyId\" : \"AAAAA\",\"SecretAccessKey\" : \"SSSSSSS\", \"Token\" : \"TTTTTTT\"}"))
.containsEntry("accessKey", "AAAAA")
.containsEntry("secretKey", "SSSSSSS")
.containsEntry("sessionToken", "TTTTTTT");
}
String securityCredentials = "{\n"
+ " \"Code\" : \"Success\",\n"
+ " \"LastUpdated\" : \"2013-02-26T02:03:57Z\",\n"
+ " \"Type\" : \"AWS-HMAC\",\n"
+ " \"AccessKeyId\" : \"AAAAA\",\n"
+ " \"SecretAccessKey\" : \"SSSSSSS\",\n"
+ " \"Token\" : \"TTTTTTT\",\n"
+ " \"Expiration\" : \"2013-02-26T08:12:23Z\"\n"
+ "}";
}
| 262 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53ReadOnlyLiveTest.java | package denominator.route53;
import denominator.Live.UseTestGraph;
import denominator.ReadOnlyLiveTest;
@UseTestGraph(Route53TestGraph.class)
public class Route53ReadOnlyLiveTest extends ReadOnlyLiveTest {
}
| 263 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53RoundRobinWriteCommandsLiveTest.java | package denominator.route53;
import denominator.Live.UseTestGraph;
import denominator.RoundRobinWriteCommandsLiveTest;
@UseTestGraph(Route53TestGraph.class)
public class Route53RoundRobinWriteCommandsLiveTest extends RoundRobinWriteCommandsLiveTest {
}
| 264 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53WeightedResourceRecordSetApiMockTest.java | package denominator.route53;
import com.squareup.okhttp.mockwebserver.MockResponse;
import org.junit.Rule;
import org.junit.Test;
import java.util.Iterator;
import denominator.model.ResourceRecordSet;
import denominator.model.profile.Weighted;
import denominator.model.rdata.CNAMEData;
import denominator.profile.WeightedResourceRecordSetApi;
import static denominator.assertj.ModelAssertions.assertThat;
public class Route53WeightedResourceRecordSetApiMockTest {
@Rule
public MockRoute53Server server = new MockRoute53Server();
@Test
public void iterateByNameWhenPresent() throws Exception {
server.enqueue(new MockResponse().setBody(twoRecords));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
Iterator<ResourceRecordSet<?>> iterator = api.iterateByName("www.denominator.io.");
assertThat(iterator.next()).isEqualTo(rrset1);
assertThat(iterator.next())
.hasName("www.denominator.io.")
.hasType("CNAME")
.hasQualifier("MyService-West")
.hasTtl(0)
.hasWeight(5)
.containsExactlyRecords(CNAMEData.create("www2.denominator.io."));
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.");
}
@Test
public void iterateByNameWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setBody(noRecords));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
assertThat(api.iterateByName("www.denominator.io.")).isEmpty();
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.");
}
@Test
public void iterateByNameAndTypeWhenPresent() throws Exception {
server.enqueue(new MockResponse().setBody(twoRecords));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
assertThat(api.iterateByNameAndType("www.denominator.io.", "CNAME")).contains(rrset1);
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.&type=CNAME");
}
@Test
public void iterateByNameAndTypeWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setBody(noRecords));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
assertThat(api.iterateByNameAndType("www.denominator.io.", "CNAME")).isEmpty();
server.assertRequest()
.hasPath("/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.&type=CNAME");
}
@Test
public void getByNameTypeAndQualifierWhenPresent() throws Exception {
server.enqueue(new MockResponse().setBody(twoRecords));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
assertThat(api.getByNameTypeAndQualifier("www.denominator.io.", "CNAME", "MyService-East"))
.isEqualTo(rrset1);
server.assertRequest()
.hasPath(
"/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.&type=CNAME&identifier=MyService-East");
}
@Test
public void getByNameTypeAndQualifierWhenAbsent() throws Exception {
server.enqueue(new MockResponse().setBody(noRecords));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
assertThat(api.getByNameTypeAndQualifier("www.denominator.io.", "CNAME", "MyService-East"))
.isNull();
server.assertRequest()
.hasPath(
"/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.&type=CNAME&identifier=MyService-East");
}
@Test
public void putRecordSet() throws Exception {
server.enqueue(new MockResponse().setBody(noRecords));
server.enqueue(new MockResponse().setBody(changeSynced));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
api.put(rrset1);
server.assertRequest()
.hasPath(
"/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.&type=CNAME&identifier=MyService-East");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ChangeBatch>\n"
+ " <Changes>\n"
+ " <Change>\n"
+ " <Action>CREATE</Action>\n"
+ " <ResourceRecordSet>\n"
+ " <Name>www.denominator.io.</Name>\n"
+ " <Type>CNAME</Type>\n"
+ " <SetIdentifier>MyService-East</SetIdentifier>\n"
+ " <Weight>1</Weight>\n"
+ " <TTL>0</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>www1.denominator.io.</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ " </ResourceRecordSet>\n"
+ " </Change>\n"
+ " </Changes>\n"
+ " </ChangeBatch>\n"
+ "</ChangeResourceRecordSetsRequest>");
}
@Test
public void putRecordSetSkipsWhenEqual() throws Exception {
server.enqueue(new MockResponse().setBody(oneRecord));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
api.put(rrset1);
server.assertRequest()
.hasPath(
"/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.&type=CNAME&identifier=MyService-East");
}
@Test
public void deleteDoesntAffectOtherQualifiers() throws Exception {
server.enqueue(new MockResponse().setBody(twoRecords));
server.enqueue(new MockResponse().setBody(changeSynced));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
api.deleteByNameTypeAndQualifier("www.denominator.io.", "CNAME", "MyService-East");
server.assertRequest()
.hasPath(
"/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.&type=CNAME&identifier=MyService-East");
server.assertRequest()
.hasMethod("POST")
.hasPath("/2012-12-12/hostedzone/Z1PA6795/rrset")
.hasXMLBody(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\">\n"
+ " <ChangeBatch>\n"
+ " <Changes>\n"
+ " <Change>\n"
+ " <Action>DELETE</Action>\n"
+ " <ResourceRecordSet>\n"
+ " <Name>www.denominator.io.</Name>\n"
+ " <Type>CNAME</Type>\n"
+ " <SetIdentifier>MyService-East</SetIdentifier>\n"
+ " <Weight>1</Weight>\n"
+ " <TTL>0</TTL>\n"
+ " <ResourceRecords>\n"
+ " <ResourceRecord>\n"
+ " <Value>www1.denominator.io.</Value>\n"
+ " </ResourceRecord>\n"
+ " </ResourceRecords>\n"
+ " </ResourceRecordSet>\n"
+ " </Change>\n"
+ " </Changes>\n"
+ " </ChangeBatch>\n"
+ "</ChangeResourceRecordSetsRequest>");
}
@Test
public void deleteAbsentRRSDoesNothing() throws Exception {
server.enqueue(new MockResponse().setBody(oneRecord));
WeightedResourceRecordSetApi api = server.connect().api().weightedRecordSetsInZone("Z1PA6795");
api.deleteByNameTypeAndQualifier("www.denominator.io.", "CNAME", "MyService-West");
server.assertRequest()
.hasPath(
"/2012-12-12/hostedzone/Z1PA6795/rrset?name=www.denominator.io.&type=CNAME&identifier=MyService-West");
}
private String
noRecords =
"<ListResourceRecordSetsResponse><ResourceRecordSets></ResourceRecordSets></ListResourceRecordSetsResponse>";
private String
oneRecord =
"<ListResourceRecordSetsResponse><ResourceRecordSets><ResourceRecordSet><Name>www.denominator.io.</Name><Type>CNAME</Type><SetIdentifier>MyService-East</SetIdentifier><Weight>1</Weight><TTL>0</TTL><ResourceRecords><ResourceRecord><Value>www1.denominator.io.</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></ResourceRecordSets></ListResourceRecordSetsResponse>";
private String
twoRecords =
"<ListResourceRecordSetsResponse><ResourceRecordSets><ResourceRecordSet><Name>www.denominator.io.</Name><Type>CNAME</Type><SetIdentifier>MyService-East</SetIdentifier><Weight>1</Weight><TTL>0</TTL><ResourceRecords><ResourceRecord><Value>www1.denominator.io.</Value></ResourceRecord></ResourceRecords></ResourceRecordSet><ResourceRecordSet><Name>www.denominator.io.</Name><Type>CNAME</Type><SetIdentifier>MyService-West</SetIdentifier><Weight>5</Weight><TTL>0</TTL><ResourceRecords><ResourceRecord><Value>www2.denominator.io.</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></ResourceRecordSets></ListResourceRecordSetsResponse>";
private String
changeSynced =
"<GetChangeResponse><ChangeInfo><Id>/change/C2682N5HXP0BZ4</Id><Status>INSYNC</Status><SubmittedAt>2011-09-10T01:36:41.958Z</SubmittedAt></ChangeInfo></GetChangeResponse>";
private ResourceRecordSet<CNAMEData> rrset1 = ResourceRecordSet.<CNAMEData>builder()
.name("www.denominator.io.")
.type("CNAME")
.qualifier("MyService-East")
.ttl(0)
.weighted(Weighted.create(1))
.add(CNAMEData.create("www1.denominator.io.")).build();
}
| 265 |
0 | Create_ds/denominator/route53/src/test/java/denominator | Create_ds/denominator/route53/src/test/java/denominator/route53/Route53CheckConnectionLiveTest.java | package denominator.route53;
import denominator.CheckConnectionLiveTest;
import denominator.Live.UseTestGraph;
@UseTestGraph(Route53TestGraph.class)
public class Route53CheckConnectionLiveTest extends CheckConnectionLiveTest {
}
| 266 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/InvalidatableAuthenticationHeadersProvider.java | package denominator.route53;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.inject.Inject;
import javax.inject.Provider;
import denominator.Credentials;
import static java.util.Locale.US;
import static denominator.common.Preconditions.checkNotNull;
// http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/RESTAuthentication.html
final class InvalidatableAuthenticationHeadersProvider {
private static final String
AUTH_FORMAT =
"AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s";
private static final String HMACSHA256 = "HmacSHA256";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final SimpleDateFormat
RFC1123 =
new SimpleDateFormat("EEE, dd MMM yyyyy HH:mm:ss Z", US);
private final javax.inject.Provider<Credentials> credentials;
private final long durationMillis;
transient volatile String lastKeystoneUrl;
transient volatile int lastCredentialsHashCode;
// The special value 0 means "not yet initialized".
transient volatile long expirationMillis;
// "value" does not need to be volatile; visibility piggy-backs
// on above
transient Map<String, String> value;
@Inject
InvalidatableAuthenticationHeadersProvider(Provider<Credentials> credentials) {
this.credentials = credentials;
// variance allowed is 5 minutes, so only re-hashing every 1m.
this.durationMillis = TimeUnit.MINUTES.toMillis(1);
}
private static synchronized String date() {
return RFC1123.format(new Date());
}
public void invalidate() {
expirationMillis = 0;
}
public Map<String, String> get() {
long currentTime = System.currentTimeMillis();
Credentials currentCreds = credentials.get();
if (needsRefresh(currentTime, currentCreds)) {
synchronized (this) {
if (needsRefresh(currentTime, currentCreds)) {
lastCredentialsHashCode = currentCreds.hashCode();
Map<String, String> t = auth(currentCreds);
value = t;
expirationMillis = currentTime + durationMillis;
return t;
}
}
}
return value;
}
private boolean needsRefresh(long currentTime, Credentials currentCreds) {
return expirationMillis == 0 || currentTime - expirationMillis >= 0
|| currentCreds.hashCode() != lastCredentialsHashCode;
}
Map<String, String> auth(Credentials currentCreds) {
String accessKey;
String secretKey;
String token;
if (currentCreds instanceof List) {
@SuppressWarnings("unchecked")
List<Object> listCreds = (List<Object>) currentCreds;
accessKey = listCreds.get(0).toString();
secretKey = listCreds.get(1).toString();
token = listCreds.size() == 3 ? listCreds.get(2).toString() : null;
} else if (currentCreds instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> mapCreds = (Map<String, Object>) currentCreds;
accessKey = checkNotNull(mapCreds.get("accessKey"), "accessKey").toString();
secretKey = checkNotNull(mapCreds.get("secretKey"), "secretKey").toString();
token = mapCreds.containsKey("sessionToken") ? mapCreds.get("sessionToken").toString() : null;
} else {
throw new IllegalArgumentException("Unsupported credential type: " + currentCreds);
}
String rfc1123Date = date();
String signature = sign(rfc1123Date, secretKey);
String auth = String.format(AUTH_FORMAT, accessKey, signature);
Map<String, String> canContainNull = new LinkedHashMap<String, String>();
canContainNull.put("Date", rfc1123Date);
canContainNull.put("X-Amzn-Authorization", auth);
// will remove if token is not set
canContainNull.put("X-Amz-Security-Token", token);
return canContainNull;
}
String sign(String rfc1123Date, String secretKey) {
try {
Mac mac = Mac.getInstance(HMACSHA256);
mac.init(new SecretKeySpec(secretKey.getBytes(UTF_8), HMACSHA256));
byte[] result = mac.doFinal(rfc1123Date.getBytes(UTF_8));
return base64(result);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* copied from <a href="https://github.com/square/okio/blob/master/okio/src/main/java/okio/Base64.java">okio</a>
*
* @author Alexander Y. Kleymenov
*/
private static String base64(byte[] in) {
int length = (in.length + 2) * 4 / 3;
byte[] out = new byte[length];
int index = 0, end = in.length - in.length % 3;
for (int i = 0; i < end; i += 3) {
out[index++] = MAP[(in[i] & 0xff) >> 2];
out[index++] = MAP[((in[i] & 0x03) << 4) | ((in[i + 1] & 0xff) >> 4)];
out[index++] = MAP[((in[i + 1] & 0x0f) << 2) | ((in[i + 2] & 0xff) >> 6)];
out[index++] = MAP[(in[i + 2] & 0x3f)];
}
switch (in.length % 3) {
case 1:
out[index++] = MAP[(in[end] & 0xff) >> 2];
out[index++] = MAP[(in[end] & 0x03) << 4];
out[index++] = '=';
out[index++] = '=';
break;
case 2:
out[index++] = MAP[(in[end] & 0xff) >> 2];
out[index++] = MAP[((in[end] & 0x03) << 4) | ((in[end + 1] & 0xff) >> 4)];
out[index++] = MAP[((in[end + 1] & 0x0f) << 2)];
out[index++] = '=';
break;
}
try {
return new String(out, 0, index, "US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
private static final byte[] MAP = new byte[]{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '+', '/'
};
}
| 267 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53Exception.java | package denominator.route53;
import feign.FeignException;
class Route53Exception extends FeignException {
private static final long serialVersionUID = 1L;
private final String code;
Route53Exception(String message, String code) {
super(message);
this.code = code;
}
/**
* The error code. ex {@code InvalidInput}
*/
public String code() {
return code;
}
}
| 268 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/ListResourceRecordSetsResponseHandler.java | package denominator.route53;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import denominator.route53.Route53.ResourceRecordSetList;
import denominator.route53.Route53.ResourceRecordSetList.NextRecord;
import feign.sax.SAXDecoder.ContentHandlerWithResult;
/**
* See <a href= "http://docs.aws.amazon.com/Route53/latest/APIReference/API_ListResourceRecordSets.html"
* />
*/
class ListResourceRecordSetsResponseHandler extends DefaultHandler implements
ContentHandlerWithResult<ResourceRecordSetList> {
private final StringBuilder currentText = new StringBuilder();
private final ResourceRecordSetList rrsets = new ResourceRecordSetList();
private ResourceRecordSetHandler resourceRecordSetHandler = new ResourceRecordSetHandler();
private NextRecord next = null;
private boolean inResourceRecordSets;
@Override
public ResourceRecordSetList result() {
rrsets.next = next;
return rrsets;
}
@Override
public void startElement(String url, String name, String qName, Attributes attributes) {
if ("ResourceRecordSets".equals(qName)) {
inResourceRecordSets = true;
}
}
@Override
public void endElement(String uri, String name, String qName) {
if (inResourceRecordSets) {
if ("ResourceRecordSets".equals(qName)) {
inResourceRecordSets = false;
} else if (qName.equals("ResourceRecordSet")) {
rrsets.add(resourceRecordSetHandler.result());
resourceRecordSetHandler = new ResourceRecordSetHandler();
} else {
resourceRecordSetHandler.endElement(uri, name, qName);
}
} else if (qName.equals("NextRecordName")) {
next = new NextRecord(currentText.toString().trim());
} else if (qName.equals("NextRecordType")) {
next.type = currentText.toString().trim();
} else if (qName.equals("NextRecordIdentifier")) {
next.identifier = currentText.toString().trim();
}
currentText.setLength(0);
}
@Override
public void characters(char ch[], int start, int length) {
if (inResourceRecordSets) {
resourceRecordSetHandler.characters(ch, start, length);
} else {
currentText.append(ch, start, length);
}
}
}
| 269 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/EncodeChanges.java | package denominator.route53;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import denominator.model.ResourceRecordSet;
import denominator.route53.Route53.ActionOnResourceRecordSet;
import feign.RequestTemplate;
import feign.codec.Encoder;
import static denominator.common.Preconditions.checkNotNull;
import static denominator.common.Util.join;
import static java.lang.String.format;
class EncodeChanges implements Encoder {
static String apply(ResourceRecordSet<?> rrs) {
StringBuilder builder = new StringBuilder().append("<ResourceRecordSet>");
builder.append("<Name>").append(rrs.name()).append("</Name>");
builder.append("<Type>").append(rrs.type()).append("</Type>");
if (rrs.qualifier() != null) {
builder.append("<SetIdentifier>")//
.append(rrs.qualifier())//
.append("</SetIdentifier>");
}
// note lowercase as this is a supported profile
if (rrs.weighted() != null) {
builder.append("<Weight>").append(rrs.weighted().weight()).append("</Weight>");
}
if (rrs.records().size() == 1 && rrs.records().get(0).containsKey("HostedZoneId")) {
builder.append("<AliasTarget>");
Map<String, Object> aliasTarget = rrs.records().get(0);
for (String attribute : new String[]{"HostedZoneId", "DNSName"}) {
builder.append('<').append(attribute).append('>');
builder.append(
checkNotNull(aliasTarget.get(attribute), "missing %s in alias target %s", attribute,
rrs));
builder.append("</").append(attribute).append('>');
}
// not valid until health checks are supported.
builder.append("<EvaluateTargetHealth>false</EvaluateTargetHealth>");
builder.append("</AliasTarget>");
} else {
// default ttl from the amazon console is 300
builder.append("<TTL>").append(rrs.ttl() == null ? 300 : rrs.ttl()).append("</TTL>");
builder.append("<ResourceRecords>");
for (Map<String, Object> data : rrs.records()) {
String textFormat = join(' ', data.values().toArray());
if ("SPF".equals(rrs.type()) || "TXT".equals(rrs.type())) {
textFormat = format("\"%s\"", textFormat);
}
builder.append("<ResourceRecord>").append("<Value>").append(textFormat).append("</Value>")
.append("</ResourceRecord>");
}
builder.append("</ResourceRecords>");
}
return builder.append("</ResourceRecordSet>").toString();
}
@Override
public void encode(Object object, Type bodyType, RequestTemplate template) {
List<ActionOnResourceRecordSet> actions = (List<ActionOnResourceRecordSet>) object;
StringBuilder b = new StringBuilder();
b.append(
"<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><ChangeBatch>");
b.append("<Changes>");
for (ActionOnResourceRecordSet change : actions) {
b.append("<Change>").append("<Action>").append(change.action).append("</Action>")
.append(apply(change.rrs))
.append("</Change>");
}
b.append("</Changes>");
b.append("</ChangeBatch></ChangeResourceRecordSetsRequest>");
template.body(b.toString());
}
}
| 270 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/AliasTarget.java | package denominator.route53;
import java.util.LinkedHashMap;
import denominator.model.ResourceRecordSet;
import static denominator.common.Preconditions.checkNotNull;
/**
* Reference to the addresses in a CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing
* load balancer, or Route 53 hosted zone. <br> Only valid when {@link ResourceRecordSet#type()} is
* {@code A} or {@code AAAA} .
*
* <br> <b>Example</b><br>
*
* <pre>
* AliasTarget rdata = AliasTarget.create("Z3DZXE0Q79N41H",
* "nccp-cbp-frontend-12345678.us-west-2.elb.amazonaws.com.");
* </pre>
*
* See <a href= "http://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html#API_ChangeResourceRecordSets_RequestAliasSyntax"
* >API to create aliases</a>
*
* @since 4.2
*/
public final class AliasTarget extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
AliasTarget(String hostedZoneId, String dnsName) {
put("HostedZoneId", checkNotNull(hostedZoneId, "HostedZoneId"));
put("DNSName", checkNotNull(dnsName, "DNSName"));
}
public static AliasTarget create(String hostedZoneId, String dnsName) {
return new AliasTarget(hostedZoneId, dnsName);
}
/**
* Hosted zone ID for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load
* balancer, or Route 53 hosted zone.
*/
public String hostedZoneId() {
return get("HostedZoneId").toString();
}
/**
* DNS domain name for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load
* balancer, or another resource record set in this hosted zone.
*/
public String dnsName() {
return get("DNSName").toString();
}
}
| 271 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/ResourceRecordSetHandler.java | package denominator.route53;
import org.xml.sax.helpers.DefaultHandler;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import denominator.model.ResourceRecordSet;
import denominator.model.ResourceRecordSet.Builder;
import denominator.model.profile.Weighted;
import denominator.model.rdata.AAAAData;
import denominator.model.rdata.AData;
import denominator.model.rdata.CNAMEData;
import denominator.model.rdata.MXData;
import denominator.model.rdata.NSData;
import denominator.model.rdata.PTRData;
import denominator.model.rdata.SOAData;
import denominator.model.rdata.SPFData;
import denominator.model.rdata.SRVData;
import denominator.model.rdata.TXTData;
import feign.sax.SAXDecoder.ContentHandlerWithResult;
import static denominator.common.Util.split;
class ResourceRecordSetHandler extends DefaultHandler
implements ContentHandlerWithResult<ResourceRecordSet<?>> {
private final StringBuilder currentText = new StringBuilder();
private final Builder<Map<String, Object>> builder = ResourceRecordSet.builder();
private String currentType;
private String hostedZoneId;
private String dnsName;
/**
* See <a href="http://aws.amazon.com/route53/faqs/#Supported_DNS_record_types" >supported
* types</a> See <a href= "http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html"
* >record type formats</a>
*/
static Map<String, Object> parseTextFormat(String type, String rdata) {
if ("A".equals(type)) {
return AData.create(rdata);
} else if ("AAAA".equals(type)) {
return AAAAData.create(rdata);
} else if ("CNAME".equals(type)) {
return CNAMEData.create(rdata);
} else if ("MX".equals(type)) {
List<String> parts = split(' ', rdata);
return MXData.create(Integer.valueOf(parts.get(0)), parts.get(1));
} else if ("NS".equals(type)) {
return NSData.create(rdata);
} else if ("PTR".equals(type)) {
return PTRData.create(rdata);
} else if ("SOA".equals(type)) {
List<String> parts = split(' ', rdata);
return SOAData.builder().mname(parts.get(0)).rname(parts.get(1))
.serial(Integer.valueOf(parts.get(2)))
.refresh(Integer.valueOf(parts.get(3))).retry(Integer.valueOf(parts.get(4)))
.expire(Integer.valueOf(parts.get(5))).minimum(Integer.valueOf(parts.get(6))).build();
} else if ("SPF".equals(type)) {
// unquote
return SPFData.create(rdata.substring(1, rdata.length() - 1));
} else if ("SRV".equals(type)) {
List<String> parts = split(' ', rdata);
return SRVData.builder().priority(Integer.valueOf(parts.get(0)))
.weight(Integer.valueOf(parts.get(1)))
.port(Integer.valueOf(parts.get(2))).target(parts.get(3)).build();
} else if ("TXT".equals(type)) {
// unquote
return TXTData.create(rdata.substring(1, rdata.length() - 1));
} else {
Map<String, Object> unknown = new LinkedHashMap<String, Object>();
unknown.put("rdata", rdata);
return unknown;
}
}
@Override
public ResourceRecordSet<?> result() {
return builder.build();
}
@Override
public void endElement(String uri, String name, String qName) {
if (qName.equals("Name")) {
builder.name(currentText.toString().trim());
} else if (qName.equals("Type")) {
builder.type(currentType = currentText.toString().trim());
} else if (qName.equals("TTL")) {
builder.ttl(Integer.parseInt(currentText.toString().trim()));
} else if (qName.equals("Value")) {
builder.add(parseTextFormat(currentType, currentText.toString().trim()));
} else if (qName.equals("SetIdentifier")) {
builder.qualifier(currentText.toString().trim());
} else if (qName.equals("HostedZoneId")) {
hostedZoneId = currentText.toString().trim();
} else if (qName.equals("DNSName")) {
dnsName = currentText.toString().trim();
} else if (qName.equals("AliasTarget")) {
builder.add(AliasTarget.create(hostedZoneId, dnsName));
} else if ("Weight".equals(qName)) {
builder.weighted(Weighted.create(Integer.parseInt(currentText.toString().trim())));
}
currentText.setLength(0);
}
@Override
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
}
| 272 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53Target.java | package denominator.route53;
import java.util.Map.Entry;
import javax.inject.Inject;
import denominator.Provider;
import feign.Request;
import feign.RequestTemplate;
import feign.Target;
class Route53Target implements Target<Route53> {
private final Provider provider;
private final InvalidatableAuthenticationHeadersProvider lazyAuthHeaders;
@Inject
Route53Target(Provider provider, InvalidatableAuthenticationHeadersProvider lazyAuthHeaders) {
this.provider = provider;
this.lazyAuthHeaders = lazyAuthHeaders;
}
@Override
public Class<Route53> type() {
return Route53.class;
}
@Override
public String name() {
return provider.name();
}
@Override
public String url() {
return provider.url();
}
@Override
public Request apply(RequestTemplate input) {
if (input.url().indexOf("http") != 0) {
input.insert(0, url());
}
for (Entry<String, String> entry : lazyAuthHeaders.get().entrySet()) {
input.header(entry.getKey(), entry.getValue());
}
return input.request();
}
}
| 273 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/InvalidChangeBatchException.java | package denominator.route53;
import java.util.List;
import feign.FeignException;
import static java.lang.String.format;
/**
* See <a href= "http://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html#API_ChangeResourceRecordSets_ExampleErrors"
* >docs</a>
*/
public class InvalidChangeBatchException extends FeignException {
private static final long serialVersionUID = 1L;
private final List<String> messages;
InvalidChangeBatchException(String methodKey, List<String> messages) {
super(format("%s failed with errors %s", methodKey, messages));
this.messages = messages;
}
/**
* Messages corresponding to the changes.
*/
public List<String> messages() {
return messages;
}
}
| 274 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/ListHostedZonesResponseHandler.java | package denominator.route53;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import denominator.route53.Route53.HostedZone;
import denominator.route53.Route53.HostedZoneList;
import feign.sax.SAXDecoder.ContentHandlerWithResult;
/**
* See <a href= "http://docs.aws.amazon.com/Route53/latest/APIReference/API_ListHostedZones.html"
* >docs</a>
*/
class ListHostedZonesResponseHandler extends DefaultHandler
implements ContentHandlerWithResult<HostedZoneList> {
private final StringBuilder currentText = new StringBuilder();
private final HostedZoneList zones = new HostedZoneList();
private HostedZone zone = new HostedZone();
@Override
public HostedZoneList result() {
return zones;
}
@Override
public void endElement(String uri, String name, String qName) {
if (qName.equals("Name")) {
zone.name = currentText.toString().trim();
} else if (qName.equals("Id")) {
zone.id = currentText.toString().trim().replace("/hostedzone/", "");
} else if (qName.equals("HostedZone")) {
zones.add(zone);
zone = new HostedZone();
} else if (qName.equals("NextMarker")) {
zones.next = currentText.toString().trim();
}
currentText.setLength(0);
}
@Override
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
}
| 275 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53WeightedResourceRecordSetApi.java | package denominator.route53;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedSet;
import javax.inject.Inject;
import javax.inject.Named;
import denominator.Provider;
import denominator.common.Filter;
import denominator.model.ResourceRecordSet;
import denominator.profile.WeightedResourceRecordSetApi;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Util.filter;
final class Route53WeightedResourceRecordSetApi implements WeightedResourceRecordSetApi {
private static final Filter<ResourceRecordSet<?>>
IS_WEIGHTED =
new Filter<ResourceRecordSet<?>>() {
@Override
public boolean apply(ResourceRecordSet<?> in) {
return in != null && in.weighted() != null;
}
};
private final Collection<String> supportedTypes;
private final SortedSet<Integer> supportedWeights;
private final Route53AllProfileResourceRecordSetApi allApi;
Route53WeightedResourceRecordSetApi(Provider provider, SortedSet<Integer> supportedWeights,
Route53AllProfileResourceRecordSetApi allProfileResourceRecordSetApi) {
this.supportedTypes = provider.profileToRecordTypes().get("weighted");
this.supportedWeights = supportedWeights;
this.allApi = allProfileResourceRecordSetApi;
}
@Override
public SortedSet<Integer> supportedWeights() {
return supportedWeights;
}
@Override
public Iterator<ResourceRecordSet<?>> iterator() {
return filter(allApi.iterator(), IS_WEIGHTED);
}
@Override
public Iterator<ResourceRecordSet<?>> iterateByName(String name) {
return filter(allApi.iterateByName(name), IS_WEIGHTED);
}
@Override
public Iterator<ResourceRecordSet<?>> iterateByNameAndType(String name, String type) {
return filter(allApi.iterateByNameAndType(name, type), IS_WEIGHTED);
}
@Override
public ResourceRecordSet<?> getByNameTypeAndQualifier(String name, String type,
String qualifier) {
return allApi.getByNameTypeAndQualifier(name, type, qualifier);
}
@Override
public void put(ResourceRecordSet<?> rrset) {
checkArgument(supportedTypes.contains(rrset.type()), "%s not a supported type for weighted: %s",
rrset.type(),
supportedTypes);
allApi.put(rrset);
}
@Override
public void deleteByNameTypeAndQualifier(String name, String type, String qualifier) {
allApi.deleteByNameTypeAndQualifier(name, type, qualifier);
}
static final class Factory implements WeightedResourceRecordSetApi.Factory {
private final Provider provider;
private final SortedSet<Integer> supportedWeights;
private final Route53AllProfileResourceRecordSetApi.Factory allApi;
@Inject
Factory(Provider provider, @Named("weighted") SortedSet<Integer> supportedWeights,
Route53AllProfileResourceRecordSetApi.Factory allApi) {
this.provider = provider;
this.supportedWeights = supportedWeights;
this.allApi = allApi;
}
@Override
public WeightedResourceRecordSetApi create(String id) {
return new Route53WeightedResourceRecordSetApi(provider, supportedWeights, allApi.create(id));
}
}
}
| 276 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53Provider.java | package denominator.route53;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Provides;
import denominator.AllProfileResourceRecordSetApi;
import denominator.BasicProvider;
import denominator.CheckConnection;
import denominator.DNSApiManager;
import denominator.ResourceRecordSetApi;
import denominator.ZoneApi;
import denominator.config.GeoUnsupported;
import denominator.config.NothingToClose;
import denominator.profile.WeightedResourceRecordSetApi;
import denominator.route53.Route53ErrorDecoder.Messages;
import denominator.route53.Route53ErrorDecoder.Route53Error;
import feign.Feign;
import feign.Logger;
import feign.codec.Decoder;
import feign.sax.SAXDecoder;
public class Route53Provider extends BasicProvider {
private final String url;
public Route53Provider() {
this(null);
}
/**
* @param url if empty or null use default
*/
public Route53Provider(String url) {
this.url = url == null || url.isEmpty() ? "https://route53.amazonaws.com" : url;
}
@Override
public String url() {
return url;
}
@Override
public boolean supportsDuplicateZoneNames() {
return true;
}
// http://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html
@Override
public Set<String> basicRecordTypes() {
Set<String> types = new LinkedHashSet<String>();
types
.addAll(Arrays.asList("A", "AAAA", "CNAME", "MX", "NS", "PTR", "SOA", "SPF", "SRV", "TXT"));
return types;
}
// http://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html
@Override
public Map<String, Collection<String>> profileToRecordTypes() {
Map<String, Collection<String>>
profileToRecordTypes =
new LinkedHashMap<String, Collection<String>>();
profileToRecordTypes
.put("weighted", Arrays.asList("A", "AAAA", "CNAME", "MX", "PTR", "SPF", "SRV", "TXT"));
profileToRecordTypes
.put("roundRobin", Arrays.asList("A", "AAAA", "MX", "NS", "PTR", "SPF", "SRV", "TXT"));
return profileToRecordTypes;
}
@Override
public Map<String, Collection<String>> credentialTypeToParameterNames() {
Map<String, Collection<String>> options = new LinkedHashMap<String, Collection<String>>();
options.put("accessKey", Arrays.asList("accessKey", "secretKey"));
options.put("session", Arrays.asList("accessKey", "secretKey", "sessionToken"));
return options;
}
@dagger.Module(injects = DNSApiManager.class, complete = false, includes = {NothingToClose.class,
GeoUnsupported.class,
InstanceProfileCredentialsProvider.class,
FeignModule.class})
public static final class Module {
@Provides
CheckConnection checkConnection(HostedZonesReadable checkConnection) {
return checkConnection;
}
@Provides
@Singleton
ZoneApi provideZoneApi(Route53 api) {
return new Route53ZoneApi(api);
}
@Provides
@Singleton
ResourceRecordSetApi.Factory provideResourceRecordSetApiFactory(
Route53AllProfileResourceRecordSetApi.Factory roApi, Route53 api) {
return new Route53ResourceRecordSetApi.Factory(roApi, api);
}
@Provides
@Singleton
AllProfileResourceRecordSetApi.Factory provideAllProfileResourceRecordSetApiFactory(
Route53 api) {
return new Route53AllProfileResourceRecordSetApi.Factory(api);
}
@Provides
WeightedResourceRecordSetApi.Factory provideWeightedResourceRecordSetApiFactory(
Route53WeightedResourceRecordSetApi.Factory in) {
return in;
}
/**
* See <a href= "http://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html"
* >valid weights</a>
*/
@Provides
@Singleton
@Named("weighted")
SortedSet<Integer> provideSupportedWeights() {
SortedSet<Integer> supportedWeights = new TreeSet<Integer>();
for (int i = 0; i <= 255; i++) {
supportedWeights.add(i);
}
return Collections.unmodifiableSortedSet(supportedWeights);
}
}
@dagger.Module(injects = Route53ResourceRecordSetApi.Factory.class,
complete = false // doesn't bind Provider used by Route53Target
)
public static final class FeignModule {
@Provides
@Singleton
Route53 route53(Feign feign, Route53Target target) {
return feign.newInstance(target);
}
@Provides
Logger logger() {
return new Logger.NoOpLogger();
}
@Provides
Logger.Level logLevel() {
return Logger.Level.NONE;
}
@Provides
@Singleton
Feign feign(Logger logger, Logger.Level logLevel) {
Decoder decoder = decoder();
return Feign.builder()
.logger(logger)
.logLevel(logLevel)
.encoder(new EncodeChanges())
.decoder(decoder)
.errorDecoder(new Route53ErrorDecoder(decoder))
.build();
}
static Decoder decoder() {
return SAXDecoder.builder()
.registerContentHandler(GetHostedZoneResponseHandler.class)
.registerContentHandler(ListHostedZonesResponseHandler.class)
.registerContentHandler(ListResourceRecordSetsResponseHandler.class)
.registerContentHandler(Messages.class)
.registerContentHandler(Route53Error.class)
.build();
}
}
}
| 277 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53ErrorDecoder.java | package denominator.route53;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import feign.FeignException;
import feign.Response;
import feign.RetryableException;
import feign.codec.Decoder;
import feign.codec.ErrorDecoder;
import feign.sax.SAXDecoder.ContentHandlerWithResult;
import static feign.Util.resolveLastTypeParameter;
import static java.lang.String.format;
class Route53ErrorDecoder implements ErrorDecoder {
private static final Type
LIST_STRING =
resolveLastTypeParameter(Messages.class, ContentHandlerWithResult.class);
private final Decoder decoder;
Route53ErrorDecoder(Decoder decoder) {
this.decoder = decoder;
}
// visible for testing;
protected long currentTimeMillis() {
return System.currentTimeMillis();
}
@Override
public Exception decode(String methodKey, Response response) {
try {
if ("Route53#changeResourceRecordSets(String,List)".equals(methodKey)) {
@SuppressWarnings("unchecked")
List<String> messages = List.class.cast(decoder.decode(response, LIST_STRING));
return new InvalidChangeBatchException(methodKey, messages);
}
Route53Error error = Route53Error.class.cast(decoder.decode(response, Route53Error.class));
if (error == null) {
return FeignException.errorStatus(methodKey, response);
}
String message = format("%s failed with error %s", methodKey, error.code);
if (error.message != null) {
message = format("%s: %s", message, error.message);
}
if ("RequestExpired".equals(error.code) || "InternalError".equals(error.code)
|| "InternalFailure".equals(error.code)) {
return new RetryableException(message, null);
} else if ("Throttling".equals(error.code) || "PriorRequestNotComplete".equals(error.code)) {
// backoff at least a second.
return new RetryableException(message, new Date(currentTimeMillis() + 1000));
} else if (error.code.startsWith("NoSuch")) {
// consider not found exception
}
return new Route53Exception(message, error.code);
} catch (IOException e) {
return FeignException.errorStatus(methodKey, response);
}
}
static class Messages extends DefaultHandler implements ContentHandlerWithResult<List<String>> {
private final StringBuilder currentText = new StringBuilder();
private final List<String> messages = new ArrayList<String>(10);
@Override
public List<String> result() {
return messages;
}
@Override
public void endElement(String uri, String name, String qName) {
if (qName.equals("Message")) {
messages.add(currentText.toString().trim());
}
currentText.setLength(0);
}
@Override
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
}
static class Route53Error extends DefaultHandler
implements ContentHandlerWithResult<Route53Error> {
private final StringBuilder currentText = new StringBuilder();
private String code;
private String message;
@Override
public Route53Error result() {
return this;
}
@Override
public void endElement(String uri, String name, String qName) {
if (qName.equals("Code")) {
code = currentText.toString().trim();
} else if (qName.equals("Message")) {
message = currentText.toString().trim();
}
currentText.setLength(0);
}
@Override
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
}
}
| 278 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/GetHostedZoneResponseHandler.java | package denominator.route53;
import org.xml.sax.helpers.DefaultHandler;
import denominator.route53.Route53.NameAndCount;
import feign.sax.SAXDecoder.ContentHandlerWithResult;
/**
* See <a href= "http://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHostedZone.html"
* >docs</a>
*/
class GetHostedZoneResponseHandler extends DefaultHandler
implements ContentHandlerWithResult<NameAndCount> {
private final StringBuilder currentText = new StringBuilder();
private NameAndCount zone = new NameAndCount();
@Override
public NameAndCount result() {
return zone;
}
@Override
public void endElement(String uri, String name, String qName) {
if (qName.equals("Name")) {
zone.name = currentText.toString().trim();
} else if (qName.equals("ResourceRecordSetCount")) {
zone.resourceRecordSetCount = Integer.parseInt(currentText.toString().trim());
}
currentText.setLength(0);
}
@Override
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
}
| 279 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53.java | package denominator.route53;
import java.util.ArrayList;
import java.util.List;
import denominator.model.ResourceRecordSet;
import feign.Body;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
interface Route53 {
@RequestLine("GET /2012-12-12/hostedzone/{zoneId}")
NameAndCount getHostedZone(@Param("zoneId") String zoneId);
@RequestLine("GET /2012-12-12/hostedzone")
HostedZoneList listHostedZones();
@RequestLine("GET /2012-12-12/hostedzone?marker={marker}")
HostedZoneList listHostedZones(@Param("marker") String marker);
@RequestLine("GET /2013-04-01/hostedzonesbyname?dnsname={dnsname}")
HostedZoneList listHostedZonesByName(@Param("dnsname") String dnsname);
@RequestLine("POST /2012-12-12/hostedzone")
@Headers("Content-Type: application/xml")
@Body("<CreateHostedZoneRequest xmlns=\"https://route53.amazonaws.com/doc/2012-12-12/\"><Name>{name}</Name><CallerReference>{reference}</CallerReference></CreateHostedZoneRequest>")
HostedZoneList createHostedZone(@Param("name") String name, @Param("reference") String reference);
@RequestLine("DELETE /2012-12-12/hostedzone/{zoneId}")
HostedZoneList deleteHostedZone(@Param("zoneId") String zoneId);
@RequestLine("GET /2012-12-12/hostedzone/{zoneId}/rrset")
ResourceRecordSetList listResourceRecordSets(@Param("zoneId") String zoneId);
@RequestLine("GET /2012-12-12/hostedzone/{zoneId}/rrset?name={name}")
ResourceRecordSetList listResourceRecordSets(@Param("zoneId") String zoneId,
@Param("name") String name);
@RequestLine("GET /2012-12-12/hostedzone/{zoneId}/rrset?name={name}&type={type}")
ResourceRecordSetList listResourceRecordSets(@Param("zoneId") String zoneId,
@Param("name") String name,
@Param("type") String type);
@RequestLine("GET /2012-12-12/hostedzone/{zoneId}/rrset?name={name}&type={type}&identifier={identifier}")
ResourceRecordSetList listResourceRecordSets(@Param("zoneId") String zoneId,
@Param("name") String name,
@Param("type") String type,
@Param("identifier") String identifier);
@RequestLine("POST /2012-12-12/hostedzone/{zoneId}/rrset")
@Headers("Content-Type: application/xml")
void changeResourceRecordSets(@Param("zoneId") String zoneId,
List<ActionOnResourceRecordSet> changes)
throws InvalidChangeBatchException;
class NameAndCount {
String name;
int resourceRecordSetCount;
}
class HostedZone {
String id;
String name;
}
class HostedZoneList extends ArrayList<HostedZone> {
public String next;
}
class ResourceRecordSetList extends ArrayList<ResourceRecordSet<?>> {
NextRecord next;
static class NextRecord {
final String name;
String type;
String identifier;
NextRecord(String name) {
this.name = name;
}
}
}
class ActionOnResourceRecordSet {
final String action;
final ResourceRecordSet<?> rrs;
private ActionOnResourceRecordSet(String action, ResourceRecordSet<?> rrs) {
this.action = action;
this.rrs = rrs;
}
static ActionOnResourceRecordSet create(ResourceRecordSet<?> rrs) {
return new ActionOnResourceRecordSet("CREATE", rrs);
}
static ActionOnResourceRecordSet delete(ResourceRecordSet<?> rrs) {
return new ActionOnResourceRecordSet("DELETE", rrs);
}
}
}
| 280 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/HostedZonesReadable.java | package denominator.route53;
import javax.inject.Inject;
import denominator.CheckConnection;
class HostedZonesReadable implements CheckConnection {
private final Route53 api;
@Inject
HostedZonesReadable(Route53 api) {
this.api = api;
}
@Override
public boolean ok() {
try {
api.listHostedZones();
return true;
} catch (RuntimeException e) {
return false;
}
}
@Override
public String toString() {
return "HostedZonesReadable";
}
}
| 281 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53AllProfileResourceRecordSetApi.java | package denominator.route53;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.inject.Inject;
import denominator.AllProfileResourceRecordSetApi;
import denominator.common.Filter;
import denominator.common.PeekingIterator;
import denominator.model.ResourceRecordSet;
import denominator.route53.Route53.ActionOnResourceRecordSet;
import denominator.route53.Route53.ResourceRecordSetList;
import denominator.route53.Route53.ResourceRecordSetList.NextRecord;
import static denominator.common.Util.filter;
import static denominator.common.Util.nextOrNull;
import static denominator.common.Util.peekingIterator;
import static denominator.model.ResourceRecordSets.nameAndTypeEqualTo;
import static denominator.model.ResourceRecordSets.nameEqualTo;
import static denominator.model.ResourceRecordSets.nameTypeAndQualifierEqualTo;
import static denominator.model.ResourceRecordSets.notNull;
import static denominator.route53.Route53.ActionOnResourceRecordSet.create;
import static denominator.route53.Route53.ActionOnResourceRecordSet.delete;
public final class Route53AllProfileResourceRecordSetApi implements AllProfileResourceRecordSetApi {
private final Route53 api;
private final String zoneId;
Route53AllProfileResourceRecordSetApi(Route53 api, String zoneId) {
this.api = api;
this.zoneId = zoneId;
}
private static Filter<ResourceRecordSet<?>> notAlias() {
return new AndNotAlias(notNull());
}
private static Filter<ResourceRecordSet<?>> andNotAlias(Filter<ResourceRecordSet<?>> first) {
return new AndNotAlias(first);
}
/**
* lists and lazily transforms all record sets who are not aliases into denominator format.
*/
@Override
public Iterator<ResourceRecordSet<?>> iterator() {
return lazyIterateRRSets(api.listResourceRecordSets(zoneId), notAlias());
}
/**
* lists and lazily transforms all record sets for a name which are not aliases into denominator
* format.
*/
@Override
public Iterator<ResourceRecordSet<?>> iterateByName(String name) {
Filter<ResourceRecordSet<?>> filter = andNotAlias(nameEqualTo(name));
return lazyIterateRRSets(api.listResourceRecordSets(zoneId, name), filter);
}
@Override
public Iterator<ResourceRecordSet<?>> iterateByNameAndType(String name, String type) {
Filter<ResourceRecordSet<?>> filter = andNotAlias(nameAndTypeEqualTo(name, type));
return lazyIterateRRSets(api.listResourceRecordSets(zoneId, name, type), filter);
}
@Override
public ResourceRecordSet<?> getByNameTypeAndQualifier(String name, String type,
String qualifier) {
Filter<ResourceRecordSet<?>> filter = andNotAlias(
nameTypeAndQualifierEqualTo(name, type, qualifier));
ResourceRecordSetList first = api.listResourceRecordSets(zoneId, name, type, qualifier);
return nextOrNull(lazyIterateRRSets(first, filter));
}
public ResourceRecordSet<?> getByNameAndType(String name, String type) {
return nextOrNull(filter(iterateByNameAndType(name, type), notAlias()));
}
@Override
public void put(ResourceRecordSet<?> rrset) {
List<ActionOnResourceRecordSet> changes = new ArrayList<ActionOnResourceRecordSet>();
ResourceRecordSet<?> oldRRS;
if (rrset.qualifier() != null) {
oldRRS = getByNameTypeAndQualifier(rrset.name(), rrset.type(), rrset.qualifier());
} else {
oldRRS = getByNameAndType(rrset.name(), rrset.type());
}
if (oldRRS != null) {
if (oldRRS.equals(rrset)) {
return;
}
changes.add(delete(oldRRS));
}
changes.add(create(rrset));
api.changeResourceRecordSets(zoneId, changes);
}
@Override
public void deleteByNameTypeAndQualifier(String name, String type, String qualifier) {
ResourceRecordSet<?> oldRRS = getByNameTypeAndQualifier(name, type, qualifier);
if (oldRRS == null) {
return;
}
api.changeResourceRecordSets(zoneId, Arrays.asList(delete(oldRRS)));
}
@Override
public void deleteByNameAndType(String name, String type) {
List<ActionOnResourceRecordSet> changes = new ArrayList<ActionOnResourceRecordSet>();
for (Iterator<ResourceRecordSet<?>> it = iterateByNameAndType(name, type); it.hasNext(); ) {
changes.add(delete(it.next()));
}
api.changeResourceRecordSets(zoneId, changes);
}
Iterator<ResourceRecordSet<?>> lazyIterateRRSets(final ResourceRecordSetList first,
final Filter<ResourceRecordSet<?>> filter) {
if (first.next == null) {
return filter(first.iterator(), filter);
}
return new Iterator<ResourceRecordSet<?>>() {
PeekingIterator<ResourceRecordSet<?>> current = peekingIterator(first.iterator());
NextRecord next = first.next;
@Override
public boolean hasNext() {
while (!current.hasNext() && next != null) {
ResourceRecordSetList nextPage;
if (next.identifier != null) {
nextPage = api.listResourceRecordSets(zoneId, next.name, next.type,
next.identifier);
} else {
nextPage = api.listResourceRecordSets(zoneId, next.name, next.type);
}
current = peekingIterator(nextPage.iterator());
next = nextPage.next;
}
return current.hasNext() && filter.apply(current.peek());
}
@Override
public ResourceRecordSet<?> next() {
return current.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
static final class Factory implements denominator.AllProfileResourceRecordSetApi.Factory {
private final Route53 api;
@Inject
Factory(Route53 api) {
this.api = api;
}
@Override
public Route53AllProfileResourceRecordSetApi create(String id) {
return new Route53AllProfileResourceRecordSetApi(api, id);
}
}
private static class AndNotAlias implements Filter<ResourceRecordSet<?>> {
private final Filter<ResourceRecordSet<?>> first;
private AndNotAlias(Filter<ResourceRecordSet<?>> first) {
this.first = first;
}
@Override
public boolean apply(ResourceRecordSet<?> input) {
if (!first.apply(input)) {
return false;
}
if (input.records().isEmpty()) {
return true;
}
return true;
}
}
}
| 282 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53ZoneApi.java | package denominator.route53;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import denominator.common.PeekingIterator;
import denominator.model.ResourceRecordSet;
import denominator.model.Zone;
import denominator.model.rdata.SOAData;
import denominator.route53.Route53.ActionOnResourceRecordSet;
import denominator.route53.Route53.HostedZone;
import denominator.route53.Route53.HostedZoneList;
import denominator.route53.Route53.NameAndCount;
import denominator.route53.Route53.ResourceRecordSetList;
import static denominator.common.Preconditions.checkState;
import static denominator.model.ResourceRecordSets.soa;
import static denominator.route53.Route53.ActionOnResourceRecordSet.create;
import static java.util.Arrays.asList;
public final class Route53ZoneApi implements denominator.ZoneApi {
private final Route53 api;
Route53ZoneApi(Route53 api) {
this.api = api;
}
@Override
public Iterator<Zone> iterator() {
return new ZipWithSOA(api.listHostedZones());
}
/**
* This implementation assumes that there isn't more than one page of zones with the same name.
*/
@Override
public Iterator<Zone> iterateByName(final String name) {
final Iterator<HostedZone> delegate = api.listHostedZonesByName(name).iterator();
return new PeekingIterator<Zone>() {
@Override
protected Zone computeNext() {
if (delegate.hasNext()) {
HostedZone next = delegate.next();
if (next.name.equals(name)) {
return zipWithSOA(next);
}
}
return endOfData();
}
};
}
@Override
public String put(Zone zone) {
String name = zone.name();
String id =
zone.id() != null ? zone.id()
: api.createHostedZone(name, UUID.randomUUID().toString()).get(0).id;
ResourceRecordSet<SOAData> soa = getSOA(id, name);
SOAData soaData = soa.records().get(0);
if (zone.email().equals(soaData.rname()) && zone.ttl() == soa.ttl().intValue()) {
return id;
}
List<ActionOnResourceRecordSet> updates =
asList(ActionOnResourceRecordSet.delete(soa), create(soa(soa, zone.email(), zone.ttl())));
api.changeResourceRecordSets(id, updates);
return id;
}
private ResourceRecordSet<SOAData> getSOA(String id, String name) {
ResourceRecordSetList soa = api.listResourceRecordSets(id, name, "SOA");
checkState(!soa.isEmpty(), "SOA record for zone %s %s was not present", id, name);
return (ResourceRecordSet<SOAData>) soa.get(0);
}
@Override
public void delete(String id) {
try {
NameAndCount nameAndCount = api.getHostedZone(id);
if (nameAndCount.resourceRecordSetCount > 2) {
deleteEverythingExceptNSAndSOA(id, nameAndCount.name);
}
api.deleteHostedZone(id);
} catch (Route53Exception e) {
if (!e.code().equals("NoSuchHostedZone")) {
throw e;
}
}
}
/**
* Works through the zone, deleting each page of rrsets, except the zone's SOA and the NS rrsets.
* Once the zone is cleared, it can be deleted.
*
* <p/>Users can modify the zone's SOA and NS rrsets, but they cannot be deleted except via
* deleting the zone.
*/
private void deleteEverythingExceptNSAndSOA(String id, String name) {
List<ActionOnResourceRecordSet> deletes = new ArrayList<ActionOnResourceRecordSet>();
ResourceRecordSetList page = api.listResourceRecordSets(id);
while (!page.isEmpty()) {
for (ResourceRecordSet<?> rrset : page) {
if (rrset.type().equals("SOA") || rrset.type().equals("NS") && rrset.name().equals(name)) {
continue;
}
deletes.add(ActionOnResourceRecordSet.delete(rrset));
}
if (!deletes.isEmpty()) {
api.changeResourceRecordSets(id, deletes);
}
if (page.next == null) {
page.clear();
} else {
deletes.clear();
page = api.listResourceRecordSets(id, page.next.name, page.next.type, page.next.identifier);
}
}
}
private Zone zipWithSOA(HostedZone next) {
ResourceRecordSetList soas = api.listResourceRecordSets(next.id, next.name, "SOA");
checkState(!soas.isEmpty(), "SOA record for zone %s %s was not present", next.id, next.name);
ResourceRecordSet<SOAData> soa = (ResourceRecordSet<SOAData>) soas.get(0);
SOAData soaData = soa.records().get(0);
return Zone.create(next.id, next.name, soa.ttl(), soaData.rname());
}
/**
* For each hosted zone, lazy fetch the corresponding SOA record and zip into a Zone object.
*/
class ZipWithSOA implements Iterator<Zone> {
HostedZoneList list;
int i = 0;
int length;
ZipWithSOA(HostedZoneList list) {
this.list = list;
this.length = list.size();
}
@Override
public boolean hasNext() {
while (i == length && list.next != null) {
list = api.listHostedZones(list.next);
length = list.size();
i = 0;
}
return i < length;
}
@Override
public Zone next() {
return zipWithSOA(list.get(i++));
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| 283 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/Route53ResourceRecordSetApi.java | package denominator.route53;
import java.util.Arrays;
import java.util.Iterator;
import javax.inject.Inject;
import denominator.ResourceRecordSetApi;
import denominator.model.ResourceRecordSet;
import static denominator.common.Util.filter;
import static denominator.model.ResourceRecordSets.alwaysVisible;
import static denominator.route53.Route53.ActionOnResourceRecordSet.delete;
public final class Route53ResourceRecordSetApi implements ResourceRecordSetApi {
private final Route53AllProfileResourceRecordSetApi allApi;
private final Route53 api;
private final String zoneId;
Route53ResourceRecordSetApi(Route53AllProfileResourceRecordSetApi allProfileResourceRecordSetApi,
Route53 api,
String zoneId) {
this.allApi = allProfileResourceRecordSetApi;
this.api = api;
this.zoneId = zoneId;
}
@Override
public Iterator<ResourceRecordSet<?>> iterator() {
return filter(allApi.iterator(), alwaysVisible());
}
@Override
public Iterator<ResourceRecordSet<?>> iterateByName(String name) {
return filter(allApi.iterateByName(name), alwaysVisible());
}
@Override
public ResourceRecordSet<?> getByNameAndType(String name, String type) {
ResourceRecordSet<?> rrset = allApi.getByNameAndType(name, type);
return alwaysVisible().apply(rrset) ? rrset : null;
}
@Override
public void put(ResourceRecordSet<?> rrset) {
allApi.put(rrset);
}
@Override
public void deleteByNameAndType(String name, String type) {
ResourceRecordSet<?> oldRRS = getByNameAndType(name, type);
if (oldRRS == null) {
return;
}
api.changeResourceRecordSets(zoneId, Arrays.asList(delete(oldRRS)));
}
static final class Factory implements denominator.ResourceRecordSetApi.Factory {
private final Route53AllProfileResourceRecordSetApi.Factory allApi;
private final Route53 api;
@Inject
Factory(Route53AllProfileResourceRecordSetApi.Factory allApi, Route53 api) {
this.allApi = allApi;
this.api = api;
}
@Override
public ResourceRecordSetApi create(String id) {
return new Route53ResourceRecordSetApi(allApi.create(id), api, id);
}
}
}
| 284 |
0 | Create_ds/denominator/route53/src/main/java/denominator | Create_ds/denominator/route53/src/main/java/denominator/route53/InstanceProfileCredentialsProvider.java | package denominator.route53;
import java.net.URI;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Provider;
import dagger.Module;
import dagger.Provides;
import denominator.Credentials;
import denominator.Credentials.MapCredentials;
import denominator.hook.InstanceMetadataHook;
import static denominator.CredentialsConfiguration.checkValidForProvider;
import static denominator.common.Preconditions.checkNotNull;
import static java.util.regex.Pattern.DOTALL;
/**
* Credentials supplier implementation that loads credentials from the Amazon EC2 Instance Metadata
* Service.
*/
@Module(injects = InstanceProfileCredentialsProvider.class, complete = false, library = true)
public class InstanceProfileCredentialsProvider {
private static final Map<String, String> keyMap = new LinkedHashMap<String, String>();
static {
keyMap.put("AccessKeyId", "accessKey");
keyMap.put("SecretAccessKey", "secretKey");
keyMap.put("Token", "sessionToken");
}
private static final Pattern JSON_FIELDS = Pattern.compile("\"([^\"]+)\" *: *\"([^\"]+)", DOTALL);
private final Provider<String> iipJsonProvider;
public InstanceProfileCredentialsProvider() {
this(new ReadFirstInstanceProfileCredentialsOrNull());
}
public InstanceProfileCredentialsProvider(URI baseUri) {
this(new ReadFirstInstanceProfileCredentialsOrNull(baseUri));
}
public InstanceProfileCredentialsProvider(Provider<String> iipJsonProvider) {
this.iipJsonProvider = checkNotNull(iipJsonProvider, "iipJsonProvider");
}
/**
* IAM Instance Profile format is simple, non-nested json.
*
* ex.
*
* <pre>
* {
* "Code" : "Success",
* "LastUpdated" : "2013-02-26T02:03:57Z",
* "Type" : "AWS-HMAC",
* "AccessKeyId" : "AAAAA",
* "SecretAccessKey" : "SSSSSSS",
* "Token" : "TTTTTTT",
* "Expiration" : "2013-02-26T08:12:23Z"
* }
*
* </pre>
*
* This impl avoids choosing a json library by parsing the simple structure above directly.
*/
static Map<String, String> parseJson(String in) {
if (in == null) {
return Collections.emptyMap();
}
String noBraces = in.replace('{', ' ').replace('}', ' ').trim();
Map<String, String> builder = new LinkedHashMap<String, String>();
Matcher matcher = JSON_FIELDS.matcher(noBraces);
while (matcher.find()) {
String key = keyMap.get(matcher.group(1));
if (key != null) {
builder.put(key, matcher.group(2));
}
}
return builder;
}
@Provides
Credentials get(denominator.Provider provider) {
return checkValidForProvider(MapCredentials.from(parseJson(iipJsonProvider.get())), provider);
}
@Override
public String toString() {
return "ParseIIPJsonFrom(" + iipJsonProvider + ")";
}
/**
* default means to grab instance credentials, or return null
*/
static class ReadFirstInstanceProfileCredentialsOrNull implements Provider<String> {
private final URI baseUri;
public ReadFirstInstanceProfileCredentialsOrNull() {
this(URI.create("http://169.254.169.254/latest/meta-data/"));
}
/**
* @param baseUri uri string with trailing slash
*/
public ReadFirstInstanceProfileCredentialsOrNull(URI baseUri) {
this.baseUri = checkNotNull(baseUri, "baseUri");
}
@Override
public String get() {
List<String> roles = InstanceMetadataHook.list(baseUri, "iam/security-credentials/");
if (roles.isEmpty()) {
return null;
}
return InstanceMetadataHook.get(baseUri, "iam/security-credentials/" + roles.get(0));
}
@Override
public String toString() {
return "ReadFirstInstanceProfileCredentialsOrNull(" + baseUri + ")";
}
}
}
| 285 |
0 | Create_ds/s3mper/test/java/com/netflix | Create_ds/s3mper/test/java/com/netflix/test/TestCaseRunner.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
/**
*
* @author dweeks
*/
public class TestCaseRunner {
public static void main(String[] args) throws ClassNotFoundException {
Request testCase = Request.method(Class.forName(args[0]), args[1]);
JUnitCore core = new JUnitCore();
Result result = core.run(testCase);
for(Failure f: result.getFailures()) {
System.out.println(f.getMessage());
f.getException().printStackTrace();
}
System.exit(result.wasSuccessful() ? 0 : 1);
}
}
| 286 |
0 | Create_ds/s3mper/test/java/com/netflix/bdp/s3mper | Create_ds/s3mper/test/java/com/netflix/bdp/s3mper/listing/ConsistentListingAspectTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.listing;
import com.netflix.bdp.s3mper.alert.impl.CloudWatchAlertDispatcher;
import com.netflix.bdp.s3mper.metastore.FileInfo;
import com.netflix.bdp.s3mper.metastore.FileSystemMetastore;
import com.netflix.bdp.s3mper.metastore.impl.DynamoDBMetastore;
import com.netflix.bdp.s3mper.metastore.impl.MetastoreJanitor;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import static java.lang.String.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.util.Progressable;
/**
*
* @author dweeks
*/
public class ConsistentListingAspectTest {
private static final Logger log = Logger.getLogger(ConsistentListingAspectTest.class.getName());
private static DynamoDBMetastore meta;
private static CloudWatchAlertDispatcher alert;
private static MetastoreJanitor janitor;
private static Configuration conf;
private static FileSystem markerFs;
private static FileSystem deleteFs;
private static Path testPath;
@BeforeClass
public static void setUpClass() throws Exception {
conf = new Configuration();
conf.setBoolean("s3mper.disable", false);
conf.setBoolean("s3mper.failOnError", true);
conf.setBoolean("s3mper.metastore.deleteMarker.enabled", true);
conf.setBoolean("s3mper.reporting.disabled", true);
conf.setLong("s3mper.listing.recheck.count", 10);
conf.setLong("s3mper.listing.recheck.period", 1000);
conf.setFloat("s3mper.listing.threshold", 1);
conf.set("s3mper.metastore.name", "ConsistentListingMetastoreTest");
testPath = new Path(System.getProperty("fs.test.path", "s3n://netflix-s3mper-test/test"));
markerFs = FileSystem.get(testPath.toUri(), conf);
Configuration deleteConf = new Configuration(conf);
deleteConf.setBoolean("s3mper.metastore.deleteMarker.enabled", false);
deleteFs = FileSystem.get(testPath.toUri(), deleteConf);
meta = new DynamoDBMetastore();
meta.initalize(testPath.toUri(), conf);
alert = new CloudWatchAlertDispatcher();
alert.init(testPath.toUri(), conf);
Configuration janitorConf = new Configuration(conf);
janitorConf.setBoolean("s3mper.metastore.deleteMarker.enabled", false);
janitor = new MetastoreJanitor();
janitor.initalize(testPath.toUri(), janitorConf);
}
@AfterClass
public static void tearDownClass() throws Exception {
janitor.clearPath(testPath);
markerFs.close();
deleteFs.close();
meta.close();
}
@Before
public void setUp() throws Exception {
System.out.println("========================== Setting Up =========================== ");
conf.setBoolean("s3mper.disable", false);
conf.setBoolean("s3mper.failOnError", true);
conf.setBoolean("s3mper.metastore.deleteMarker.enabled", true);
conf.setBoolean("s3mper.reporting.disabled", true);
conf.setLong("s3mper.listing.recheck.count", 10);
conf.setLong("s3mper.listing.recheck.period", 1000);
conf.setFloat("s3mper.listing.threshold", 1);
conf.set("s3mper.metastore.name", "ConsistentListingMetastoreTest");
janitor.clearPath(testPath);
deleteFs.delete(testPath, true);
}
@After
public void tearDown() throws Exception {
System.out.println("========================== Tearing Down =========================");
conf.setBoolean("s3mper.metastore.deleteMarker.enabled", false);
janitor.clearPath(testPath);
deleteFs.delete(testPath, true);
conf.setFloat("s3mper.listing.threshold", 1);
}
@Test
public void testFileCreateMethods() throws Throwable {
System.out.println("testFileCreateMethods");
Path file = new Path(testPath + "/create-methods.test");
//create(Path)
OutputStream fout = deleteFs.create(file);
assertNotNull(fout);
fout.close();
List<FileInfo> files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(Path, Progressable)");
fout = deleteFs.create(file, new Progressable(){
@Override
public void progress() {
}
});
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(Path, boolean)");
fout = deleteFs.create(file, true);
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(Path, short)");
fout = deleteFs.create(file, (short) 1);
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(Path, boolean, int)");
fout = deleteFs.create(file, true, 4096);
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(FileSystem, Path, FsPermission)");
fout = deleteFs.create(deleteFs, file, FsPermission.getDefault());
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(FileSystem, short, Progressable)");
fout = deleteFs.create(file, (short)1, new Progressable(){
@Override
public void progress() {
}
});
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(FileSystem, boolean, int, Progressable)");
fout = deleteFs.create(file, true, 4096, new Progressable(){
@Override
public void progress() {
}
});
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(FileSystem, boolean, int, short, long)");
fout = deleteFs.create(file, true, 4096, (short)1, 100000000);
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
System.out.println("create(FileSystem, boolean, int, short, long, Progressable)");
fout = deleteFs.create(file, true, 4096, (short)1, 100000000,new Progressable(){
@Override
public void progress() {
}
});
assertNotNull(fout);
fout.close();
files = meta.list(Collections.singletonList(file.getParent()));
assertEquals(1, files.size());
deleteFs.delete(file.getParent(), true);
janitor.clearPath(testPath);
}
@Test
public void testUpdateMetastore() throws Throwable {
System.out.println("updateMetastore");
Path arg1Path = new Path(testPath + "/update.test");
OutputStream fout = deleteFs.create(arg1Path);
assertNotNull(fout);
fout.close();
List<FileInfo> files = meta.list(Collections.singletonList(arg1Path.getParent()));
assertEquals(1, files.size());
deleteFs.delete(arg1Path, true);
janitor.clearPath(testPath);
}
@Test
public void testWritePerformace() throws Throwable {
System.out.println("testWritePerformace");
int fileCount = Integer.getInteger("test.file.count", 10);
int threadCount = Integer.getInteger("test.thread.count", 5);
List<FileCreator> writeThreads = new ArrayList<FileCreator>();
for (int i = 0; i < threadCount; i++) {
FileCreator f = new FileCreator(deleteFs, fileCount, i);
f.start();
writeThreads.add(f);
}
long start = System.currentTimeMillis();
for(FileCreator t : writeThreads) {
t.join();
}
long stop = System.currentTimeMillis();
for(FileCreator t : writeThreads) {
log.info(t.getName() + " failures: " + t.failures);
}
log.info("Total time for writes: " + (stop - start));
List<FileInfo> files = meta.list(Collections.singletonList(testPath));
assertEquals(fileCount * threadCount, files.size());
janitor.clearPath(testPath);
}
@Test
public void testAlerts() throws Exception {
System.out.println("testAlerts");
Path alertFile = new Path(testPath+"/alert.test");
conf.setLong("s3mper.listing.recheck.count", 0);
meta.add(alertFile, false);
int count = Integer.getInteger("test.alert.count", 5);
int sleep = Integer.getInteger("test.alert.sleep", 1000);
int alerts = 0;
for(int i=0; i<count; i++) {
try {
deleteFs.listStatus(testPath);
} catch (Exception e) {
log.info(format("[%d of %d alerts]: %s",i,count,e.getMessage()));
alerts++;
}
Thread.sleep(sleep);
}
assertEquals("Listing failures didn't match", count, alerts);
meta.delete(alertFile);
}
@Test
public void testRecursiveDelete() throws Exception {
System.out.println("testDeleteDirectory");
Path p = testPath;
System.out.println("Creating dirs/files");
for (int level=0; level<5; level++) {
p = new Path(p, ""+level);
deleteFs.mkdirs(p);
deleteFs.create(new Path(p,"file.txt")).close();
}
p = testPath;
for (int level=0; level<5; level++) {
p = new Path(p, ""+level);
assertTrue("Incorrect Entry Count: " + p, meta.list(Collections.singletonList(p)).size() >= 1);
}
System.out.println("Sleeping for 5s");
Thread.sleep(5000);
System.out.println("Calling delete . . .");
deleteFs.delete(new Path(testPath+"/0"), true);
System.out.println("Sleeping for 5s");
Thread.sleep(5000);
p = testPath;
for (int level=0; level<5; level++) {
p = new Path(p, ""+level);
boolean empty = false;
List<FileInfo> listing = meta.list(Collections.singletonList(p));
if(listing.isEmpty()) {
empty = true;
} else {
empty = true;
for(FileInfo f : listing) {
if(!f.isDeleted()) {
empty = false;
break;
}
}
}
assertTrue("Entry found for path: " + p, empty);
}
p = testPath;
for (int level=0; level<5; level++) {
p = new Path(p, ""+level);
janitor.clearPath(p);
}
}
@Test
public void testTimeout() throws Exception {
System.out.println("testTimeout");
int currentTimeout = meta.getTimeout();
meta.setTimeout(5);
int count = Integer.getInteger("test.timeout.count", 4);
int sleep = Integer.getInteger("test.timeout.sleep", 1000);
int timeouts = 0;
for (int i = 0; i < count; i++) {
try {
meta.list(Collections.singletonList(testPath));
} catch (Exception e) {
if( !(e instanceof TimeoutException)) {
fail("Caught non-timeout exception");
}
timeouts++;
log.info("Caught exception: " + e.getClass());
}
Thread.sleep(sleep);
}
meta.setTimeout(currentTimeout);
assertEquals("Timeouts test failed", count, timeouts);
}
@Test
public void testTimeoutAlerts() throws Exception {
System.out.println("testTimeoutAlerts");
for (int i = 0; i < 10; i++) {
alert.timeout("testAlert", Collections.singletonList(testPath));
}
}
@Test
public void testRecheckBackoff() throws Exception {
System.out.println("testRecheckBackoff");
Path path = new Path(testPath.toUri() + "/backoff.test");
meta.add(path, false);
long start = System.currentTimeMillis();
try {
deleteFs.listStatus(testPath);
} catch (Exception e) {}
long stop = System.currentTimeMillis();
long time = stop-start;
meta.delete(path);
System.out.println("Time taken (ms): " + time);
assertTrue("Recheck Backoff Failed", time > TimeUnit.SECONDS.toMillis(10));
}
@Test
public void testDeleteMarker() throws Exception {
System.out.println("testDeleteMarker");
Path path = new Path(testPath.toUri() + "/deleteMarker.test");
OutputStream fout = deleteFs.create(path);
fout.close();
List<FileInfo> listing = meta.list(Collections.singletonList(testPath));
assertEquals("Metastore listing size was incorrected", 1, listing.size());
deleteFs.delete(path, true);
listing = meta.list(Collections.singletonList(testPath));
assertEquals("Metastore listing size after delete was incorrected", 1, listing.size());
assertTrue("Delete marker was not present", listing.get(0).isDeleted());
meta.delete(path);
}
@Test
public void testDeleteMarkerListing() throws Exception {
Path p1 = new Path(testPath.toUri() + "/deleteMarkerListing-1.test");
Path p2 = new Path(testPath.toUri() + "/deleteMarkerListing-2.test");
Path p3 = new Path(testPath.toUri() + "/deleteMarkerListing-3.test");
deleteFs.create(p1).close();
deleteFs.create(p2).close();
deleteFs.create(p3).close();
deleteFs.delete(p1, false);
deleteFs.delete(p3, false);
assertEquals("Wrong number of fs listed files", 1, deleteFs.listStatus(testPath).length);
assertEquals("Wrong number of metastore listed files", 3, meta.list(Collections.singletonList(testPath)).size());
}
@Test
public void testThreshold() throws Exception {
Path p1 = new Path(testPath.toUri() + "/deleteMarkerListing-1.test");
Path p2 = new Path(testPath.toUri() + "/deleteMarkerListing-2.test");
Path p3 = new Path(testPath.toUri() + "/deleteMarkerListing-3.test");
deleteFs.create(p1).close();
deleteFs.create(p2).close();
meta.add(p3, false);
conf.setFloat("s3mper.listing.threshold", 0.5f);
System.out.println("Watining for s3 . . .");
Thread.sleep(10000);
try {
FileStatus [] files = deleteFs.listStatus(testPath);
assertEquals("Didn't list the correct number of files", 2, files.length);
} catch (Exception e) {
fail("Threshold not met, but should have been");
}
}
@Test
public void testRecoveryMessage() throws Exception {
Path p1 = new Path(testPath.toUri() + "/recovery-1.test");
final Path p2 = new Path(testPath.toUri() + "/recovery-2.test");
conf.setBoolean("s3mper.reporting.disabled", false);
deleteFs.create(p1).close();
meta.add(p2, false);
System.out.println("Watining for s3 . . .");
Thread.sleep(10000);
Thread t = new Thread(new Runnable(){
@Override
public void run() {
try {
System.out.println("Creating missing file");
Thread.sleep(1500);
deleteFs.create(p2).close();
} catch (Exception e) { }
}
});
t.start();
deleteFs.listStatus(testPath);
}
@Test
public void testTaskFailure() throws Exception {
Path p1 = new Path(testPath.toUri() + "/task-fail-1.test");
}
private static class FileCreator extends Thread {
int instance;
int count;
FileSystem fs;
volatile int failures = 0;
public FileCreator(FileSystem fs, int count, int instance) {
super("Test FileCreateThread-" + instance);
this.fs = fs;
this.count = count;
this.instance = instance;
}
@Override
public void run() {
try {
for (int i = 0; i < count; i++) {
Path p = new Path(testPath + "/perf-"+instance+"-"+i);
log.debug(("Creating file: "+p));
try {
fs.create(p);
} catch (Exception e) {
log.error("",e);
failures ++;
}
}
} catch (Exception e) {
log.error("",e);
}
}
}
} | 287 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert/AlertDispatcher.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.alert;
import java.net.URI;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
/**
* Interface for sending alerts.
*
* @author dweeks
*/
public interface AlertDispatcher {
void alert(List<Path> paths);
void timeout(String operation, List<Path> paths);
void init(URI uri, Configuration conf);
void setConfig(Configuration conf);
void recovered(List<Path> paths);
}
| 288 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert/impl/AbstractMessage.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.alert.impl;
import java.util.List;
/**
* Common message parent for SQS messaging.
*
* @author dweeks
*/
public class AbstractMessage {
public static enum QueryType {
Hive, Pig, Unknown
}
private long epoch;
private String timestamp;
private String username;
private String hostname;
private String jobId;
private String taskId;
private String attemptId;
private String dataovenId;
private String genieId;
private String inputFile;
private String logFile;
private QueryType queryType;
private String queryId;
private List<String> stackTrace;
private String email;
public AbstractMessage() {
}
public String getAttemptId() {
return attemptId;
}
public void setAttemptId(String attemptId) {
this.attemptId = attemptId;
}
public String getDataovenId() {
return dataovenId;
}
public void setDataovenId(String dataovenId) {
this.dataovenId = dataovenId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getEpoch() {
return epoch;
}
public void setEpoch(long epoch) {
this.epoch = epoch;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getLogFile() {
return logFile;
}
public void setLogFile(String logFile) {
this.logFile = logFile;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getInputFile() {
return inputFile;
}
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
public String getGenieId() {
return genieId;
}
public void setGenieId(String genieId) {
this.genieId = genieId;
}
public QueryType getQueryType() {
return queryType;
}
public void setQueryType(QueryType queryType) {
this.queryType = queryType;
}
public String getQueryId() {
return queryId;
}
public void setQueryId(String queryId) {
this.queryId = queryId;
}
public List<String> getStackTrace() {
return stackTrace;
}
public void setStackTrace(List<String> stackTrace) {
this.stackTrace = stackTrace;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
| 289 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert/impl/S3mperTimeoutMessage.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.alert.impl;
/**
* A message that describes an operation timeout.
*
* @author dweeks
*/
public class S3mperTimeoutMessage extends AbstractMessage {
private String operation;
public S3mperTimeoutMessage() {
}
public S3mperTimeoutMessage(String operation) {
this.operation = operation;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
}
| 290 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert/impl/AlertJanitor.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.alert.impl;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.DeleteMessageBatchRequest;
import com.amazonaws.services.sqs.model.DeleteMessageBatchRequestEntry;
import com.amazonaws.services.sqs.model.GetQueueUrlRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;
import static java.lang.String.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
* Simple utility for writing out logs from SQS queue and deleting messages.
*
* @author dweeks
*/
public class AlertJanitor {
private static final Logger log = Logger.getLogger(AlertJanitor.class.getName());
private String consistencyQueue = "s3mper-alert-queue";
private String timeoutQueue = "s3mper-timeout-queue";
private Configuration conf;
private AmazonSQSClient sqs;
private int batchCount = Integer.getInteger("s3mper.alert.janitor.batch.count", 10);
public void initalize(URI uri, Configuration conf) {
this.conf = conf;
String keyId = conf.get("fs."+uri.getScheme()+".awsAccessKeyId");
String keySecret = conf.get("fs."+uri.getScheme()+".awsSecretAccessKey");
//An override option for accessing across accounts
keyId = conf.get("fs."+uri.getScheme()+".override.awsAccessKeyId", keyId);
keySecret = conf.get("fs."+uri.getScheme()+".override.awsSecretAccessKey", keySecret);
sqs = new AmazonSQSClient(new BasicAWSCredentials(keyId, keySecret));
//SQS Consistency Queue
consistencyQueue = conf.get("fs"+uri.getScheme()+".alert.sqs.queue", consistencyQueue);
consistencyQueue = sqs.getQueueUrl(new GetQueueUrlRequest(consistencyQueue)).getQueueUrl();
//SQS Timeout Queue
timeoutQueue = conf.get("fs"+uri.getScheme()+".timeout.sqs.queue", timeoutQueue);
timeoutQueue = sqs.getQueueUrl(new GetQueueUrlRequest(timeoutQueue)).getQueueUrl();
}
/**
* Deletes all messages in the given queue.
*
* @param queue
*/
public void clearAll(String queue) {
do {
List<Message> messages = pull(queue, batchCount);
if(messages.isEmpty()) {
break;
}
delete(queue, messages);
} while(true);
}
/**
* Writes out logs to the given path as a separate JSON message per line.
*
* @param queue
* @param path
* @throws IOException
*/
public void writeLogs(String queue, Path path) throws IOException {
FileSystem fs = FileSystem.get(path.toUri(), conf);
DataOutputStream fout = fs.create(path);
do {
List<Message> messages = pull(queue, batchCount);
if(messages.isEmpty()) {
break;
}
for(Message m : messages) {
fout.write((m.getBody().replaceAll("[\n|\r]", " ")+"\n").getBytes("UTF8"));
}
delete(queue, messages);
} while(true);
fout.close();
fs.close();
}
private void delete(String queue, List<Message> messages) {
List<DeleteMessageBatchRequestEntry> deleteRequests = new ArrayList<DeleteMessageBatchRequestEntry>();
for(Message m : messages) {
deleteRequests.add(new DeleteMessageBatchRequestEntry().withId(m.getMessageId()).withReceiptHandle(m.getReceiptHandle()));
}
log.info(format("Deleting %s messages", deleteRequests.size()));
DeleteMessageBatchRequest batchDelete = new DeleteMessageBatchRequest();
batchDelete.setQueueUrl(queue);
batchDelete.setEntries(deleteRequests);
sqs.deleteMessageBatch(batchDelete);
}
private List<Message> pull(String queue, int max) {
ReceiveMessageResult result = sqs.receiveMessage(new ReceiveMessageRequest(queue).withMaxNumberOfMessages(max));
return result.getMessages();
}
/**
* Translate the SQS queue name to the fully qualified URL.
*
* @param name
* @return
*/
public String resolveQueueUrl(String name) {
return sqs.getQueueUrl(new GetQueueUrlRequest(name)).getQueueUrl();
}
public String getConsistencyQueue() {
return consistencyQueue;
}
public String getTimeoutQueue() {
return timeoutQueue;
}
public static void main(String[] args) throws Exception {
AlertJanitor janitor = new AlertJanitor();
janitor.initalize(new URI("s3n://placeholder"), new Configuration());
if("clearAll".equalsIgnoreCase(args[0])) {
janitor.clearAll(janitor.consistencyQueue);
janitor.clearAll(janitor.timeoutQueue);
}
if("log".equalsIgnoreCase(args[0])) {
String queue = args[1];
Path path = new Path(args[2]);
if("timeout".equals(queue)) {
janitor.writeLogs(janitor.timeoutQueue, path);
}
if("alert".equals(queue)) {
janitor.writeLogs(janitor.consistencyQueue, path);
}
}
}
}
| 291 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert/impl/S3ConsistencyMessage.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.alert.impl;
import java.util.List;
/**
* Message that describes an inconsistent listing.
*
* @author dweeks
*/
public class S3ConsistencyMessage extends AbstractMessage {
private List<String> paths;
private boolean truncated;
private boolean recovered;
private int missingFiles;
public S3ConsistencyMessage() {
super();
}
public List<String> getPaths() {
return paths;
}
public void setPaths(List<String> paths) {
this.paths = paths;
}
public boolean isRecovered() {
return recovered;
}
public void setRecovered(boolean recovered) {
this.recovered = recovered;
}
public boolean isTruncated() {
return truncated;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
public int getMissingFiles() {
return missingFiles;
}
public void setMissingFiles(int missingFiles) {
this.missingFiles = missingFiles;
}
}
| 292 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/alert/impl/CloudWatchAlertDispatcher.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.alert.impl;
import com.netflix.bdp.s3mper.alert.AlertDispatcher;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchAsyncClient;
import com.amazonaws.services.cloudwatch.model.MetricDatum;
import com.amazonaws.services.cloudwatch.model.PutMetricDataRequest;
import com.amazonaws.services.cloudwatch.model.StandardUnit;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.GetQueueUrlRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.netflix.bdp.s3mper.alert.impl.AbstractMessage.QueryType;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
/**
* Dispatches CloudWatch Metrics and SQS Messages on the event of consistency
* failure or timeout.
*
* @author dweeks
*/
public class CloudWatchAlertDispatcher implements AlertDispatcher {
private static final Logger log = Logger.getLogger(CloudWatchAlertDispatcher.class.getName());
private AmazonCloudWatchAsyncClient cloudWatch;
private AmazonSQSClient sqs;
private String namespace = "netflix";
private String cloudWatchConsistencyMetric = "com.netflix.bdp.s3mper.consistency.failures";
private String cloudWatchTimeoutMetric = "com.netflix.bdp.s3mper.consistency.timeout";
private String consistencyQueue = "s3mper-alert-queue";
private String timeoutQueue = "s3mper-timeout-queue";
private String notificationQueue = "s3mper-notification-queue";
private String consistencyQueueUrl = "";
private String timeoutQueueUrl = "";
private String notificationQueueUrl = "";
private boolean reportingDisabled = false;
private URI uri;
private Configuration conf;
private int pathReportLimit = 10;
private int traceDepth = 15;
@Override
public void init(URI uri, Configuration conf) {
this.uri = uri;
this.conf = conf;
}
/**
* Don't initialize the SQS queues unless we actually need to send a message.
*/
private void lazyInit() {
String keyId = conf.get("fs."+uri.getScheme()+".awsAccessKeyId");
String keySecret = conf.get("fs."+uri.getScheme()+".awsSecretAccessKey");
//An override option for accessing across accounts
keyId = conf.get("fs."+uri.getScheme()+".override.awsAccessKeyId", keyId);
keySecret = conf.get("fs."+uri.getScheme()+".override.awsSecretAccessKey", keySecret);
synchronized(this) {
if(cloudWatch == null) {
initCloudWatch(keyId, keySecret);
}
if(sqs == null) {
initSqs(keyId, keySecret);
}
}
}
private void initCloudWatch(String keyId, String keySecret) {
log.debug("Initializing CloudWatch Client");
cloudWatch = new AmazonCloudWatchAsyncClient(new BasicAWSCredentials(keyId, keySecret));
}
private void initSqs(String keyId, String keySecret) {
log.debug("Initializing SQS Client");
sqs = new AmazonSQSClient(new BasicAWSCredentials(keyId, keySecret));
//SQS Consistency Queue
consistencyQueue = conf.get("s3mper.alert.sqs.queue", consistencyQueue);
consistencyQueueUrl = sqs.getQueueUrl(new GetQueueUrlRequest(consistencyQueue)).getQueueUrl();
//SQS Timeout Queue
timeoutQueue = conf.get("s3mper.timeout.sqs.queue", timeoutQueue);
timeoutQueueUrl = sqs.getQueueUrl(new GetQueueUrlRequest(timeoutQueue)).getQueueUrl();
//SQS Notification Queue
notificationQueue = conf.get("s3mper.notification.sqs.queue", notificationQueue);
notificationQueueUrl = sqs.getQueueUrl(new GetQueueUrlRequest(notificationQueue)).getQueueUrl();
//Disable reporting (Testing purposes mostly)
reportingDisabled = conf.getBoolean("s3mper.reporting.disabled", reportingDisabled);
}
/**
* Sends an alert detailing that the given paths were missing from a list
* operation.
*
* @param missingPaths
*/
@Override
public void alert(List<Path> missingPaths) {
lazyInit();
if(reportingDisabled) {
return;
}
sendCloudWatchConsistencyAlert();
sendSQSConsistencyMessage(missingPaths, false);
}
private void sendCloudWatchConsistencyAlert() {
MetricDatum datum = new MetricDatum();
datum.setMetricName(cloudWatchConsistencyMetric);
datum.setUnit(StandardUnit.Count);
datum.setValue(1.0);
PutMetricDataRequest request = new PutMetricDataRequest();
request.setNamespace(namespace);
request.setMetricData(Collections.singleton(datum));
cloudWatch.putMetricData(request);
}
/**
* Sends a message that a listing was initially inconsistent but was
* recovered by delaying/retrying.
*
* @param paths
*/
@Override
public void recovered(List<Path> paths) {
lazyInit();
if(reportingDisabled) {
return;
}
sendSQSConsistencyMessage(paths, true);
}
private void sendSQSConsistencyMessage(List<Path> paths, boolean recovered) {
S3ConsistencyMessage message = new S3ConsistencyMessage();
buildMessage(message);
List<String> pathStrings = new ArrayList<String>();
boolean truncated = false;
for(Path p : paths) {
pathStrings.add(p.toUri().toString());
//Truncate if the message payload gets to be too large (i.e. to many missing files)
if(pathStrings.size() >= pathReportLimit) {
truncated = true;
break;
}
}
message.setPaths(pathStrings);
message.setTruncated(truncated);
int missingFiles = paths.size();
if(recovered) {
missingFiles = 0;
}
message.setMissingFiles(missingFiles);
message.setRecovered(recovered);
sendMessage(consistencyQueueUrl, message);
if(!recovered) {
sendMessage(notificationQueueUrl, message);
}
}
/**
* Sends a message to the timeout queue indicating that a dynamodb operation
* timedout.
*
* @param operation
* @param paths
*/
@Override
public void timeout(String operation, List<Path> paths) {
lazyInit();
if(reportingDisabled) {
return;
}
//TODO: Being over-protective about these timeout messages.
try {
sendCloudWatchTimeoutAlert();
} catch (Exception e) {
log.error("Failed to send cloud watch timeout alert.", e);
}
try {
sendSQSTimeoutMessage(operation);
} catch (Exception e) {
log.error("Filed to send SQS timeout message.", e);
}
}
private void sendCloudWatchTimeoutAlert() {
MetricDatum datum = new MetricDatum();
datum.setMetricName(cloudWatchTimeoutMetric);
datum.setUnit(StandardUnit.Count);
datum.setValue(1.0);
PutMetricDataRequest request = new PutMetricDataRequest();
request.setNamespace(namespace);
request.setMetricData(Collections.singleton(datum));
cloudWatch.putMetricData(request);
}
private void sendSQSTimeoutMessage(String operation) {
S3mperTimeoutMessage message = new S3mperTimeoutMessage();
buildMessage(message);
message.setOperation(operation);
sendMessage(timeoutQueueUrl, message);
}
private void buildMessage(AbstractMessage message) {
String hostname = "unknown";
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
log.warn("Failed to identify hostname",e);
}
message.setEpoch(System.currentTimeMillis());
message.setTimestamp(new Date(message.getEpoch()).toString());
message.setHostname(hostname);
String username = conf.get("user.name", System.getProperty("user.name"));
try {
username = UserGroupInformation.getCurrentUser().getUserName();
} catch (IOException e) {
log.warn("Failed to identify user using hadoop library.", e);
}
message.setUsername(username);
message.setGenieId(conf.get("genie.job.id"));
message.setDataovenId(conf.get("dataoven.job.id"));
String queryId = conf.get("hive.query.id");
QueryType queryType = QueryType.Unknown;
if(queryId != null) {
queryType = QueryType.Hive;
message.setLogFile(conf.get("hive.log.file"));
} else {
queryId = conf.get("pig.script.id");
if(queryId != null) {
queryType = QueryType.Pig;
message.setLogFile(conf.get("pig.logfile"));
}
}
message.setQueryId(queryId);
message.setQueryType(queryType);
message.setJobId(conf.get("mapred.job.id"));
message.setTaskId(conf.get("mapred.tip.id"));
message.setAttemptId(conf.get("mapred.task.id"));
message.setInputFile(conf.get("mapred.input.file"));
message.setEmail(conf.get("s3mper.email"));
try {
//We have to guess at this since it may not be explicitly in the config
if(message.getJobId() == null) {
String[] split = conf.get("mapreduce.job.dir").split("/");
String jobId = split[split.length - 1];
message.setJobId(jobId);
}
} catch (RuntimeException e) {
log.debug("Failed to determine job id");
}
try {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
List<String> stackTrace = new ArrayList<String>(traceDepth);
for (int i = 0; i < traceDepth && i < stack.length; i++) {
stackTrace.add(stack[i].toString());
}
message.setStackTrace(stackTrace);
} catch (Exception e) {
log.debug("Stacktrace generation failed", e);
}
}
private void sendMessage(String url, AbstractMessage message) {
SendMessageRequest sqsRequest = null;
try {
String payload = new ObjectMapper().writeValueAsString(message);
if(log.isDebugEnabled()) {
log.debug("Sending SQS: " + payload);
}
sqsRequest = new SendMessageRequest(url, payload);
} catch (IOException e) {
log.error("Failed to map json object.", e);
}
sqs.sendMessage(sqsRequest);
}
@Override
public void setConfig(Configuration conf) {
this.conf = conf;
}
public void setUri(URI uri) {
this.uri = uri;
}
}
| 293 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/cli/FileSystemVerifyCommand.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.cli;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.netflix.bdp.s3mper.common.PathUtil;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.OptionHandlerFilter;
/**
*
* @author dweeks
*/
public class FileSystemVerifyCommand extends Command {
private static final Logger log = Logger.getLogger(FileSystemVerifyCommand.class.getName());
@Option(name="-t",usage="Number of threads")
private int threads = 10;
@Option(name="-f",usage="Number of threads")
private String file = null;
private AmazonS3Client s3;
@Override
public void execute(Configuration conf, String[] args) throws Exception {
CmdLineParser parser = new CmdLineParser(this);
String keyId = conf.get("fs.s3n.awsAccessKeyId");
String keySecret = conf.get("fs.s3n.awsSecretAccessKey");
s3 = new AmazonS3Client(new BasicAWSCredentials(keyId, keySecret));
try {
parser.parseArgument(args);
ExecutorService executor = Executors.newFixedThreadPool(threads);
List<Future> futures = new ArrayList<Future>();
BufferedReader fin = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
try {
for(String line = fin.readLine(); line != null; line = fin.readLine()) {
futures.add(executor.submit(new FileCheckTask(new Path(line.trim()))));
}
} finally {
fin.close();
}
for(Future f : futures) {
f.get();
}
executor.shutdown();
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("s3mper fs verify [options]");
// print the list of available options
parser.printUsage(System.err);
System.err.println();
System.err.println(" Example: s3mper fs verify "+parser.printExample(OptionHandlerFilter.ALL));
}
}
private class FileCheckTask implements Callable<Boolean> {
private Path path;
public FileCheckTask(Path path) {
this.path = path;
}
@Override
public Boolean call() throws Exception {
boolean exists = false;
FileSystem fs = FileSystem.get(path.toUri(), new Configuration());
try {
exists = fs.exists(path);
} catch (Exception e) { }
System.out.println((exists?"[EXISTS ] ":"[MISSING] ") + path.toUri());
return exists;
}
}
}
| 294 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/cli/MetastoreTimeseriesDeleteCommand.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.cli;
import com.netflix.bdp.s3mper.common.PathUtil;
import com.netflix.bdp.s3mper.metastore.impl.MetastoreJanitor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.conf.Configuration;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.OptionHandlerFilter;
/**
* Deletes entries from the Metastore using the timeseries index.
*
* @author dweeks
*/
public class MetastoreTimeseriesDeleteCommand extends Command {
@Option(name="-ru",usage="Max read units to consume")
private int readUnits = 100;
@Option(name="-wu",usage="Max write units to consume")
private int writeUnits = 200;
@Option(name="-s",usage="Numer of scan threads")
private int scanThreads = 1;
@Option(name="-d",usage="Number of delete threads")
private int deleteThreads = 10;
@Option(name="-u",usage="Time unit (days, hours, minutes)")
private String unitType = "Days";
@Option(name="-n",usage="Number of specified units")
private int unitCount = 1;
@Argument
private List<String> args = new ArrayList<String>();
@Override
public void execute(Configuration conf, String[] args) throws Exception {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("s3mper meta delete_ts [options]");
// print the list of available options
parser.printUsage(System.err);
System.err.println();
System.err.println(" Example: s3mper meta delete_ts "+parser.printExample(OptionHandlerFilter.ALL));
return;
}
MetastoreJanitor janitor = new MetastoreJanitor();
janitor.initalize(PathUtil.S3N, conf);
janitor.setScanLimit(readUnits);
janitor.setDeleteLimit(writeUnits);
janitor.setScanThreads(scanThreads);
janitor.setDeleteThreads(deleteThreads);
janitor.deleteTimeseries(TimeUnit.valueOf(unitType.toUpperCase()), unitCount);
}
}
| 295 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/cli/MetastoreResolveCommand.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.cli;
import com.netflix.bdp.s3mper.metastore.FileInfo;
import com.netflix.bdp.s3mper.metastore.impl.DynamoDBMetastore;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
* Removes any entries from the Metastore that do not currently list in the
* file system.
*
* @author dweeks
*/
public class MetastoreResolveCommand extends Command {
@Override
public void execute(Configuration conf, String[] args) throws Exception {
try {
Path path = new Path(args[0]);
conf.set("s3mper.metastore.deleteMarker.enabled", "true");
DynamoDBMetastore meta = new DynamoDBMetastore();
meta.initalize(path.toUri(), conf);
FileSystem fs = FileSystem.get(path.toUri(), conf);
Set<String> s3files = new HashSet<String>();
FileStatus[] s3listing = fs.listStatus(path);
if (s3listing != null) {
for (FileStatus f : s3listing) {
s3files.add(f.getPath().toUri().toString());
}
}
List<FileInfo> files = meta.list(Collections.singletonList(path));
for (FileInfo f : files) {
if (!s3files.contains(f.getPath().toUri().toString())) {
meta.delete(f.getPath());
}
}
} catch (Exception e) {
System.out.println("Usage: s3mper metastore resolve <path>\n");
e.printStackTrace();
}
}
}
| 296 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/cli/Command.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.cli;
import org.apache.hadoop.conf.Configuration;
/**
*
* @author dweeks
*/
public abstract class Command {
public abstract void execute(Configuration conf, String [] args) throws Exception;
}
| 297 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/cli/S3mper.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.cli;
import com.google.common.collect.Maps;
import com.netflix.bdp.s3mper.alert.impl.AlertJanitor;
import com.netflix.bdp.s3mper.common.PathUtil;
import java.net.URI;
import java.util.Arrays;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
*
* @author dweeks
*/
public class S3mper extends Configured implements Tool {
@Override
public int run(String[] args) throws Exception {
try {
CMD cmd = CMD.valueOf(args[0].toUpperCase());
switch (cmd) {
case FS:
case FILESYSTEM:
processFileSystem(popArg(args));
break;
case META:
case METASTORE:
processMetastore(popArg(args));
break;
case SQS:
processSQS(popArg(args));
break;
default:
usage();
}
} catch (Exception exception) {
usage();
}
return 0;
}
enum CMD { FS, FILESYSTEM, META, METASTORE, SQS };
enum SQS_CMD { LOG, PURGE };
enum META_CMD { LIST, RESOLVE, DELETE_PATH, DELETE_TS };
public static void main(String[] args) throws Exception {
ToolRunner.run(new Configuration(), new S3mper(), args);
}
private void processFileSystem(String [] args) throws Exception {
Map<String, Command> commands = Maps.newHashMap();
commands.put("verify", new FileSystemVerifyCommand());
Command command = commands.get(args[0]);
command.execute(getConf(), popArg(args));
}
private void processMetastore(String [] args) throws Exception {
Map<META_CMD, Command> commands = Maps.newHashMap();
commands.put(META_CMD.LIST, new MetastoreListCommand());
commands.put(META_CMD.RESOLVE, new MetastoreResolveCommand());
commands.put(META_CMD.DELETE_PATH, new MetastorePathDeleteCommand());
commands.put(META_CMD.DELETE_TS, new MetastoreTimeseriesDeleteCommand());
try {
META_CMD cmd = META_CMD.valueOf(args[0].toUpperCase());
Command command = commands.get(cmd);
command.execute(getConf(), popArg(args));
} catch (Exception e) {
System.out.println("Command options are: list, resolve, delete_path, delete_ts\n");
e.printStackTrace();
}
}
private void processSQS(String [] args) throws Exception {
GnuParser parser = new GnuParser();
Options options = new Options();
CommandLine cmdline = parser.parse(options, args);
SQS_CMD cmd = SQS_CMD.valueOf(cmdline.getArgs()[0].toUpperCase());
AlertJanitor janitor = new AlertJanitor();
janitor.initalize(PathUtil.S3N, new Configuration());
String queue = janitor.resolveQueueUrl(cmdline.getArgs()[1]);
switch(cmd) {
case LOG:
janitor.writeLogs(queue, new Path(cmdline.getArgs()[2]));
break;
case PURGE:
janitor.clearAll(queue);
break;
default:
usage();
}
}
private String [] popArg(String [] args) {
if(args.length == 1) {
return new String[0];
}
return Arrays.copyOfRange(args, 1, args.length);
}
private void usage() {
System.out.println("Command options are: filesystem, metastore, sqs.\n");
}
}
| 298 |
0 | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper | Create_ds/s3mper/src/main/java/com/netflix/bdp/s3mper/cli/MetastoreListCommand.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.bdp.s3mper.cli;
import com.netflix.bdp.s3mper.metastore.FileInfo;
import com.netflix.bdp.s3mper.metastore.impl.DynamoDBMetastore;
import java.util.Collections;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
/**
*
* @author dweeks
*/
public class MetastoreListCommand extends Command {
@Override
public void execute(Configuration conf, String[] args) throws Exception {
try {
Path path = new Path(args[0]);
conf.set("s3mper.metastore.deleteMarker.enabled", "true");
DynamoDBMetastore meta = new DynamoDBMetastore();
meta.initalize(path.toUri(), conf);
List<FileInfo> files = meta.list(Collections.singletonList(path));
for (FileInfo f : files) {
System.out.println(f.getPath() + (f.isDeleted() ? " [Deleted]" : ""));
}
} catch (Exception e) {
System.out.println("Usage: s3mper metastore list <path>\n");
e.printStackTrace();
}
}
}
| 299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.