index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/Der.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.util.Iterator;
import swim.codec.Binary;
import swim.codec.Encoder;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Builder;
final class Der {
private Der() {
// stub
}
private static DerDecoder<Value> structureDecoder;
private static DerEncoder<Value> structureEncoder;
public static DerDecoder<Value> structureDecoder() {
if (structureDecoder == null) {
structureDecoder = new DerStructureDecoder();
}
return structureDecoder;
}
public static DerEncoder<Value> structureEncoder() {
if (structureEncoder == null) {
structureEncoder = new DerStructureEncoder();
}
return structureEncoder;
}
}
class DerStructureDecoder extends DerDecoder<Value> {
@Override
public Value integer(byte[] data) {
return Num.from(new BigInteger(data));
}
@SuppressWarnings("unchecked")
@Override
public Builder<Value, Value> sequenceBuilder() {
return (Builder<Value, Value>) (Builder<?, ?>) Record.builder();
}
}
class DerStructureEncoder extends DerEncoder<Value> {
@Override
public boolean isSequence(Value value) {
if (value instanceof Record) {
final Record record = (Record) value;
return record.isArray();
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public Iterator<Value> iterator(Value value) {
if (value instanceof Record) {
final Record record = (Record) value;
if (record.isArray()) {
return (Iterator<Value>) (Iterator<?>) record.iterator();
}
}
return null;
}
@Override
public int tagOf(Value value) {
if (value instanceof Num) {
return 0x02;
} else if (value instanceof Record) {
final Record record = (Record) value;
if (record.isArray()) {
return 0x30;
}
}
throw new IllegalArgumentException(value.toString());
}
@Override
public int sizeOfPrimitive(Value value) {
if (value instanceof Num) {
final BigInteger integer = value.integerValue();
return (int) Math.ceil((double) (integer.bitLength() + 1) / 8.0);
}
throw new IllegalArgumentException(value.toString());
}
@SuppressWarnings("unchecked")
@Override
public Encoder<?, ?> primitiveEncoder(int length, Value value) {
if (value instanceof Num) {
final BigInteger integer = value.integerValue();
return Binary.byteArrayWriter(integer.toByteArray());
}
throw new IllegalArgumentException(value.toString());
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/DerDecoder.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import swim.codec.Binary;
import swim.codec.Decoder;
import swim.codec.DecoderException;
import swim.codec.InputBuffer;
import swim.util.Builder;
abstract class DerDecoder<V> {
public abstract V integer(byte[] data);
public abstract Builder<V, V> sequenceBuilder();
public Decoder<V> valueDecoder() {
return new DerValueDecoder<V>(this);
}
public Decoder<V> decodeValue(InputBuffer input) {
return DerValueDecoder.decode(input, this);
}
public Decoder<V> decodeInteger(InputBuffer input) {
return DerIntegerDecoder.decode(input, this);
}
public Decoder<V> decodeSequence(InputBuffer input) {
return DerSequenceDecoder.decode(input, this);
}
}
final class DerValueDecoder<V> extends Decoder<V> {
final DerDecoder<V> der;
DerValueDecoder(DerDecoder<V> der) {
this.der = der;
}
@Override
public Decoder<V> feed(InputBuffer input) {
return decode(input, this.der);
}
static <V> Decoder<V> decode(InputBuffer input, DerDecoder<V> der) {
if (input.isCont()) {
final int tag = input.head();
input = input.step();
switch (tag) {
case 0x02: return der.decodeInteger(input);
case 0x30: return der.decodeSequence(input);
default: return error(new DecoderException("Unsupported DER tag: 0x" + Integer.toHexString(tag)));
}
}
if (input.isDone()) {
return error(new DecoderException("incomplete"));
} else if (input.isError()) {
return error(input.trap());
}
return new DerValueDecoder<V>(der);
}
}
final class DerIntegerDecoder<V> extends Decoder<V> {
final DerDecoder<V> der;
final Decoder<byte[]> data;
final int remaining;
final int step;
DerIntegerDecoder(DerDecoder<V> der, Decoder<byte[]> data, int remaining, int step) {
this.der = der;
this.data = data;
this.remaining = remaining;
this.step = step;
}
@Override
public Decoder<V> feed(InputBuffer input) {
return decode(input, this.der, this.data, this.remaining, this.step);
}
static <V> Decoder<V> decode(InputBuffer input, DerDecoder<V> der,
Decoder<byte[]> data, int remaining, int step) {
int b;
if (step == 1 && input.isCont()) {
b = input.head();
input = input.step();
if (b < 128) {
remaining = b;
step = 5;
} else {
step = 5 - (b & 0x7f);
if (step < 2) {
return error(new DecoderException("length overflow"));
} else if (step > 4) {
return error(new DecoderException("length underflow"));
}
}
}
while (step >= 2 && step <= 4 && input.isCont()) {
b = input.head();
input = input.step();
remaining = remaining << 8 | b;
step += 1;
}
if (step == 5) {
final int inputStart = input.index();
final int inputLimit = input.limit();
final int inputRemaining = inputLimit - inputStart;
if (remaining < inputRemaining) {
input = input.limit(inputStart + remaining);
}
final boolean inputPart = input.isPart();
input = input.isPart(remaining > inputRemaining);
if (data == null) {
data = Binary.parseOutput(Binary.byteArrayOutput(remaining), input);
} else {
data = data.feed(input);
}
input = input.limit(inputLimit).isPart(inputPart);
remaining -= input.index() - inputStart;
if (data.isDone()) {
return done(der.integer(data.bind()));
} else if (data.isError()) {
return data.asError();
}
}
if (input.isDone()) {
return error(new DecoderException("incomplete"));
} else if (input.isError()) {
return error(input.trap());
}
return new DerIntegerDecoder<V>(der, data, remaining, step);
}
static <V> Decoder<V> decode(InputBuffer input, DerDecoder<V> der) {
return decode(input, der, null, 0, 1);
}
}
final class DerSequenceDecoder<V> extends Decoder<V> {
final DerDecoder<V> der;
final Builder<V, V> sequence;
final Decoder<V> element;
final int remaining;
final int step;
DerSequenceDecoder(DerDecoder<V> der, Builder<V, V> sequence,
Decoder<V> element, int remaining, int step) {
this.der = der;
this.sequence = sequence;
this.element = element;
this.remaining = remaining;
this.step = step;
}
@Override
public Decoder<V> feed(InputBuffer input) {
return decode(input, this.der, this.sequence, this.element, this.remaining, this.step);
}
static <V> Decoder<V> decode(InputBuffer input, DerDecoder<V> der, Builder<V, V> sequence,
Decoder<V> element, int remaining, int step) {
int b;
if (step == 1 && input.isCont()) {
b = input.head();
input = input.step();
if (b < 128) {
remaining = b;
step = 5;
} else {
step = 5 - (b & 0x7f);
if (step < 2) {
return error(new DecoderException("length overflow"));
} else if (step > 4) {
return error(new DecoderException("length underflow"));
}
}
}
while (step >= 2 && step <= 4 && input.isCont()) {
b = input.head();
input = input.step();
remaining = remaining << 8 | b;
step += 1;
}
while (step == 5 && remaining > 0 && input.isCont()) {
final int inputStart = input.index();
final int inputLimit = input.limit();
final int inputRemaining = inputLimit - inputStart;
if (remaining < inputRemaining) {
input = input.limit(inputStart + remaining);
}
final boolean inputPart = input.isPart();
input = input.isPart(remaining > inputRemaining);
if (element == null) {
element = der.decodeValue(input);
} else {
element = element.feed(input);
}
input = input.limit(inputLimit).isPart(inputPart);
remaining -= input.index() - inputStart;
if (element.isDone()) {
if (sequence == null) {
sequence = der.sequenceBuilder();
}
sequence.add(element.bind());
element = null;
if (remaining == 0) {
step = 6;
break;
}
} else if (element.isError()) {
return element.asError();
}
}
if (step == 6 && remaining == 0) {
return done(sequence.bind());
}
if (remaining < 0) {
return error(new DecoderException("length too short"));
} else if (input.isDone()) {
return error(new DecoderException("incomplete"));
} else if (input.isError()) {
return error(input.trap());
}
return new DerSequenceDecoder<V>(der, sequence, element, remaining, step);
}
static <V> Decoder<V> decode(InputBuffer input, DerDecoder<V> der) {
return decode(input, der, null, null, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/DerEncoder.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.util.Iterator;
import swim.codec.Encoder;
import swim.codec.EncoderException;
import swim.codec.OutputBuffer;
abstract class DerEncoder<V> {
public abstract boolean isSequence(V value);
public abstract Iterator<V> iterator(V value);
public abstract int tagOf(V value);
public abstract int sizeOfPrimitive(V value);
public abstract Encoder<?, ?> primitiveEncoder(int length, V value);
public int sizeOf(V value) {
final int length;
if (isSequence(value)) {
length = sizeOfSequence(iterator(value));
} else {
length = sizeOfPrimitive(value);
}
return sizeOfValue(length);
}
public Encoder<?, ?> encoder(V value) {
final int tag = tagOf(value);
if (isSequence(value)) {
final int length = sizeOfSequence(iterator(value));
return sequenceEncoder(tag, length, iterator(value));
} else {
final int length = sizeOfPrimitive(value);
final Encoder<?, ?> data = primitiveEncoder(length, value);
return valueEncoder(tag, length, data);
}
}
public Encoder<?, ?> encode(V value, OutputBuffer<?> output) {
final int tag = tagOf(value);
if (isSequence(value)) {
final int length = sizeOfSequence(iterator(value));
return encodeSequence(tag, length, iterator(value), output);
} else {
final int length = sizeOfPrimitive(value);
final Encoder<?, ?> data = primitiveEncoder(length, value);
return encodeValue(tag, length, data, output);
}
}
public int sizeOfValue(int length) {
return 1 + sizeOfLength(length) + length;
}
public Encoder<?, ?> valueEncoder(int tag, int length, Encoder<?, ?> data) {
return new DerValueEncoder<V>(this, tag, length, data);
}
public Encoder<?, ?> encodeValue(int tag, int length, Encoder<?, ?> data, OutputBuffer<?> output) {
return DerValueEncoder.encode(output, this, tag, length, data);
}
public int sizeOfSequence(Iterator<V> elements) {
int size = 0;
while (elements.hasNext()) {
size += sizeOf(elements.next());
}
return size;
}
public Encoder<?, ?> sequenceEncoder(int tag, int length, Iterator<V> elements) {
return new DerSequenceEncoder<V>(this, tag, length, elements);
}
public Encoder<?, ?> encodeSequence(int tag, int length, Iterator<V> elements, OutputBuffer<?> output) {
return DerSequenceEncoder.encode(output, this, tag, length, elements);
}
static int sizeOfLength(int length) {
if (length < 128) {
return 1;
} else if (length < (1 << 8)) {
return 2;
} else if (length < (1 << 16)) {
return 3;
} else if (length < (1 << 24)) {
return 4;
} else {
return 5;
}
}
}
final class DerValueEncoder<V> extends Encoder<Object, Object> {
DerEncoder<V> der;
final int tag;
final int length;
final Encoder<?, ?> data;
final int offset;
final int step;
DerValueEncoder(DerEncoder<V> der, int tag, int length, Encoder<?, ?> data, int offset, int step) {
this.der = der;
this.tag = tag;
this.length = length;
this.data = data;
this.offset = offset;
this.step = step;
}
DerValueEncoder(DerEncoder<V> der, int tag, int length, Encoder<?, ?> data) {
this(der, tag, length, data, 0, 1);
}
@Override
public Encoder<Object, Object> pull(OutputBuffer<?> output) {
return encode(output, this.der, this.tag, this.length, this.data, this.offset, this.step);
}
static <V> Encoder<Object, Object> encode(OutputBuffer<?> output, DerEncoder<V> der,
int tag, int length, Encoder<?, ?> data,
int offset, int step) {
if (step == 1 && output.isCont()) {
output = output.write(tag);
step = 2;
}
if (step == 2 && output.isCont()) {
if (length < 128) {
output = output.write(length);
step = 7;
} else if (length < (1 << 8)) {
output = output.write(0x81);
step = 6;
} else if (length < (1 << 16)) {
output = output.write(0x82);
step = 5;
} else if (length < (1 << 24)) {
output = output.write(0x83);
step = 4;
} else {
output = output.write(0x84);
step = 3;
}
}
if (step == 3 && output.isCont()) {
output = output.write(length >> 24);
step = 4;
}
if (step == 4 && output.isCont()) {
output = output.write(length >> 16);
step = 5;
}
if (step == 5 && output.isCont()) {
output = output.write(length >> 8);
step = 6;
}
if (step == 6 && output.isCont()) {
output = output.write(length);
step = 7;
}
if (step == 7) {
final int outputStart = output.index();
final int outputLimit = output.limit();
final int outputRemaining = outputLimit - outputStart;
final int inputRemaining = length - offset;
final boolean outputPart = output.isPart();
if (inputRemaining <= outputRemaining) {
output = output.limit(outputStart + inputRemaining).isPart(false);
data = data.pull(output);
output = output.limit(outputLimit);
} else {
output = output.isPart(true);
data = data.pull(output);
}
output = output.isPart(outputPart);
offset += output.index() - outputStart;
if (data.isDone()) {
if (offset < length) {
return error(new EncoderException("buffer underflow"));
} else if (offset > length) {
return error(new EncoderException("buffer overflow"));
} else {
return done();
}
} else if (data.isError()) {
return data.asError();
}
}
if (output.isDone()) {
return error(new EncoderException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new DerValueEncoder<V>(der, tag, length, data, offset, step);
}
static <V> Encoder<Object, Object> encode(OutputBuffer<?> output, DerEncoder<V> der,
int tag, int length, Encoder<?, ?> data) {
return encode(output, der, tag, length, data, 0, 1);
}
}
final class DerSequenceEncoder<V> extends Encoder<Object, Object> {
DerEncoder<V> der;
final int tag;
final int length;
final Iterator<V> elements;
final Encoder<?, ?> element;
final int offset;
final int step;
DerSequenceEncoder(DerEncoder<V> der, int tag, int length, Iterator<V> elements,
Encoder<?, ?> element, int offset, int step) {
this.der = der;
this.tag = tag;
this.length = length;
this.elements = elements;
this.element = element;
this.offset = offset;
this.step = step;
}
DerSequenceEncoder(DerEncoder<V> der, int tag, int length, Iterator<V> elements) {
this(der, tag, length, elements, null, 0, 1);
}
@Override
public Encoder<Object, Object> pull(OutputBuffer<?> output) {
return encode(output, this.der, this.tag, this.length, this.elements,
this.element, this.offset, this.step);
}
static <V> Encoder<Object, Object> encode(OutputBuffer<?> output, DerEncoder<V> der, int tag, int length,
Iterator<V> elements, Encoder<?, ?> element, int offset, int step) {
if (step == 1 && output.isCont()) {
output = output.write(tag);
step = 2;
}
if (step == 2 && output.isCont()) {
if (length < 128) {
output = output.write(length);
step = 7;
} else if (length < (1 << 8)) {
output = output.write(0x81);
step = 6;
} else if (length < (1 << 16)) {
output = output.write(0x82);
step = 5;
} else if (length < (1 << 24)) {
output = output.write(0x83);
step = 4;
} else {
output = output.write(0x84);
step = 3;
}
}
if (step == 3 && output.isCont()) {
output = output.write(length >> 24);
step = 4;
}
if (step == 4 && output.isCont()) {
output = output.write(length >> 16);
step = 5;
}
if (step == 5 && output.isCont()) {
output = output.write(length >> 8);
step = 6;
}
if (step == 6 && output.isCont()) {
output = output.write(length);
step = 7;
}
while (step == 7) {
final int outputStart = output.index();
final int outputLimit = output.limit();
final int outputRemaining = outputLimit - outputStart;
final int inputRemaining = length - offset;
final boolean outputPart = output.isPart();
output = output.limit(outputStart + inputRemaining).isPart(inputRemaining > outputRemaining);
if (element != null) {
element = element.pull(output);
} else if (elements.hasNext()) {
element = der.encode(elements.next(), output);
}
output = output.limit(outputLimit).isPart(outputPart);
offset += output.index() - outputStart;
if (element.isDone()) {
if (offset < length) {
if (elements.hasNext()) {
element = null;
continue;
} else {
return error(new EncoderException("buffer underflow"));
}
} else if (offset > length) {
return error(new EncoderException("buffer overflow"));
} else {
return done();
}
} else if (element.isError()) {
return element.asError();
}
break;
}
if (output.isDone()) {
return error(new EncoderException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new DerSequenceEncoder<V>(der, tag, length, elements, element, offset, step);
}
static <V> Encoder<Object, Object> encode(OutputBuffer<?> output, DerEncoder<V> der,
int tag, int length, Iterator<V> elements) {
return encode(output, der, tag, length, elements, null, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcCharacteristic2FieldDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.spec.ECFieldF2m;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class EcCharacteristic2FieldDef extends EcFieldDef {
protected final int size;
protected final BigInteger basis;
public EcCharacteristic2FieldDef(int size, BigInteger basis) {
this.size = size;
this.basis = basis;
}
public final int size() {
return this.size;
}
public final BigInteger basis() {
return this.basis;
}
@Override
public ECFieldF2m toECField() {
if (this.basis != null) {
return new ECFieldF2m(this.size, this.basis);
} else {
return new ECFieldF2m(this.size);
}
}
@Override
public Value toValue() {
return Record.create(2)
.attr("ECField", Record.create(1).slot("size", this.size))
.slot("basis", Num.from(this.basis));
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof EcCharacteristic2FieldDef) {
final EcCharacteristic2FieldDef that = (EcCharacteristic2FieldDef) other;
return this.size == that.size && this.basis.equals(that.basis);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(EcCharacteristic2FieldDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.size), this.basis.hashCode()));
}
private static int hashSeed;
public static EcCharacteristic2FieldDef from(ECFieldF2m field) {
return new EcCharacteristic2FieldDef(field.getM(), field.getReductionPolynomial());
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.spec.EllipticCurve;
import swim.structure.Data;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class EcDef {
protected final String name;
protected final EcFieldDef field;
protected final BigInteger a;
protected final BigInteger b;
protected final byte[] seed;
public EcDef(String name, EcFieldDef field, BigInteger a, BigInteger b, byte[] seed) {
this.name = name;
this.field = field;
this.a = a;
this.b = b;
this.seed = seed;
}
public EcDef(EcFieldDef field, BigInteger a, BigInteger b, byte[] seed) {
this(null, field, a, b, seed);
}
public EcDef(EcFieldDef field, BigInteger a, BigInteger b) {
this(null, field, a, b, null);
}
public final String name() {
return this.name;
}
public final EcFieldDef field() {
return this.field;
}
public final BigInteger a() {
return this.a;
}
public final BigInteger b() {
return this.b;
}
public EllipticCurve toEllipticCurve() {
return new EllipticCurve(this.field.toECField(), this.a, this.b, this.seed);
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof EcDef) {
final EcDef that = (EcDef) other;
return this.field.equals(that.field) && this.a.equals(that.a) && this.b.equals(that.b);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(EcDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
this.field.hashCode()), this.a.hashCode()), this.b.hashCode()));
}
private static int hashSeed;
private static Form<EcDef> form;
public static EcDef from(EllipticCurve curve) {
return new EcDef(EcFieldDef.from(curve.getField()), curve.getA(),
curve.getB(), curve.getSeed());
}
@Kind
public static Form<EcDef> form() {
if (form == null) {
form = new EcForm();
}
return form;
}
}
final class EcForm extends Form<EcDef> {
@Override
public String tag() {
return "EC";
}
@Override
public Class<?> type() {
return EcDef.class;
}
@Override
public Item mold(EcDef curveDef) {
final Record header = Record.create(curveDef.seed != null ? 4 : 3)
.slot("field", curveDef.field.toValue())
.slot("a", Num.from(curveDef.a))
.slot("b", Num.from(curveDef.b));
if (curveDef.seed != null) {
header.slot("seed", Data.wrap(curveDef.seed));
}
return Record.create(1).attr(tag(), header);
}
@Override
public EcDef cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final EcFieldDef field = EcFieldDef.form().cast(header.get("field"));
final BigInteger a = header.get("a").integerValue(null);
final BigInteger b = header.get("b").integerValue(null);
final Value seedValue = header.get("seed");
final byte[] data = seedValue instanceof Data ? ((Data) seedValue).toByteArray() : null;
if (field != null && a != null && b != null) {
return new EcDef(field, a, b, data);
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcDomainDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Text;
import swim.structure.Value;
public class EcDomainDef {
protected final String name;
protected final EcDef curve;
protected final EcPointDef base;
protected final BigInteger order;
protected final int cofactor;
protected ECParameterSpec params;
EcDomainDef(String name, EcDef curve, EcPointDef base, BigInteger order, int cofactor, ECParameterSpec params) {
this.name = name;
this.curve = curve;
this.base = base;
this.order = order;
this.cofactor = cofactor;
this.params = params;
}
public EcDomainDef(String name, EcDef curve, EcPointDef base, BigInteger order, int cofactor) {
this(name, curve, base, order, cofactor, null);
}
public EcDomainDef(EcDef curve, EcPointDef base, BigInteger order, int cofactor) {
this(null, curve, base, order, cofactor, null);
}
public final String name() {
return this.name;
}
public final EcDef curve() {
return this.curve;
}
public final EcPointDef base() {
return this.base;
}
public final BigInteger order() {
return this.order;
}
public final int cofactor() {
return this.cofactor;
}
public ECParameterSpec toECParameterSpec() {
ECParameterSpec params = this.params;
if (params == null) {
params = new ECParameterSpec(this.curve.toEllipticCurve(), this.base.toECPoint(), this.order, this.cofactor);
this.params = params;
}
return params;
}
public Value toValue() {
if (this.name != null) {
return Text.from(this.name);
} else {
return form().mold(this).toValue();
}
}
private static Form<EcDomainDef> form;
public static EcDomainDef from(String name, ECParameterSpec params) {
return new EcDomainDef(name, EcDef.from(params.getCurve()), EcPointDef.from(params.getGenerator()),
params.getOrder(), params.getCofactor(), params);
}
public static EcDomainDef from(ECParameterSpec params) {
return from(null, params);
}
public static EcDomainDef forName(String name) {
try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
final ECGenParameterSpec parameterSpec = new ECGenParameterSpec(name);
keyPairGenerator.initialize(parameterSpec);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
return from(name, publicKey.getParams());
} catch (GeneralSecurityException cause) {
return null;
}
}
@Kind
public static Form<EcDomainDef> form() {
if (form == null) {
form = new EcDomainForm();
}
return form;
}
}
final class EcDomainForm extends Form<EcDomainDef> {
@Override
public String tag() {
return "ECDomain";
}
@Override
public Class<?> type() {
return EcDomainDef.class;
}
@Override
public Item mold(EcDomainDef domainDef) {
final Value header;
if (domainDef.name != null) {
header = Record.create(1).slot("name", domainDef.name);
} else {
header = Value.extant();
}
return Record.create(5)
.attr(tag(), header)
.slot("curve", domainDef.curve.toValue())
.slot("base", domainDef.base.toValue())
.slot("order", Num.from(domainDef.order))
.slot("cofactor", domainDef.cofactor);
}
@Override
public EcDomainDef cast(Item item) {
final Value value = item.toValue();
final Value header = value.getAttr(tag());
if (header.isDefined()) {
final String name = header.get("name").stringValue(null);
final EcDef curve = EcDef.form().cast(value.get("curve"));
final EcPointDef base = EcPointDef.form().cast(value.get("base"));
final BigInteger order = value.get("order").integerValue(null);
final int cofactor = value.get("cofactor").intValue(0);
if (curve != null && base != null && order != null) {
return new EcDomainDef(name, curve, base, order, cofactor);
} else if (name != null) {
return EcDomainDef.forName(name);
}
} else if (value instanceof Text) {
return EcDomainDef.forName(value.stringValue());
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcFieldDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.spec.ECField;
import java.security.spec.ECFieldF2m;
import java.security.spec.ECFieldFp;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Value;
public abstract class EcFieldDef {
public abstract ECField toECField();
public abstract Value toValue();
private static Form<EcFieldDef> form;
public static EcFieldDef from(ECField field) {
if (field instanceof ECFieldFp) {
return EcPrimeFieldDef.from((ECFieldFp) field);
} else if (field instanceof ECFieldF2m) {
return EcCharacteristic2FieldDef.from((ECFieldF2m) field);
} else {
throw new IllegalArgumentException(field.toString());
}
}
@Kind
public static Form<EcFieldDef> form() {
if (form == null) {
form = new EcFieldForm();
}
return form;
}
}
final class EcFieldForm extends Form<EcFieldDef> {
@Override
public String tag() {
return "ECField";
}
@Override
public Class<?> type() {
return EcFieldDef.class;
}
@Override
public Item mold(EcFieldDef fieldDef) {
return fieldDef.toValue();
}
@Override
public EcFieldDef cast(Item item) {
final Value value = item.toValue();
final Value header = value.getAttr(tag());
if (header.isDefined()) {
final BigInteger prime = value.get("prime").integerValue(null);
if (prime != null) {
return new EcPrimeFieldDef(prime);
}
final int size = header.get("size").intValue(0);
final BigInteger basis = value.get("basis").integerValue(null);
if (size > 0 && basis != null) {
return new EcCharacteristic2FieldDef(size, basis);
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcKeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.security.Key;
import swim.structure.Value;
public interface EcKeyDef {
EcDomainDef domain();
Key key();
Value toValue();
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcPointDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.spec.ECPoint;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class EcPointDef {
protected final BigInteger x;
protected final BigInteger y;
public EcPointDef(BigInteger x, BigInteger y) {
this.x = x;
this.y = y;
}
public final BigInteger x() {
return this.x;
}
public final BigInteger y() {
return this.y;
}
public final ECPoint toECPoint() {
return new ECPoint(this.x, this.y);
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof EcPointDef) {
final EcPointDef that = (EcPointDef) other;
return this.x.equals(that.x) && this.y.equals(that.y);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(EcPointDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.x.hashCode()), this.y.hashCode()));
}
private static int hashSeed;
private static Form<EcPointDef> form;
public static EcPointDef from(ECPoint point) {
return new EcPointDef(point.getAffineX(), point.getAffineY());
}
@Kind
public static Form<EcPointDef> form() {
if (form == null) {
form = new EcPointForm();
}
return form;
}
}
final class EcPointForm extends Form<EcPointDef> {
@Override
public String tag() {
return "ECPoint";
}
@Override
public Class<?> type() {
return EcPointDef.class;
}
@Override
public Item mold(EcPointDef pointDef) {
final Record header = Record.create(2)
.slot("x", Num.from(pointDef.x))
.slot("y", Num.from(pointDef.y));
return Record.create(1).attr(tag(), header);
}
@Override
public EcPointDef cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final BigInteger x = header.get("x").integerValue(null);
final BigInteger y = header.get("y").integerValue(null);
if (x != null && y != null) {
return new EcPointDef(x, y);
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcPrimeFieldDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.spec.ECFieldFp;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class EcPrimeFieldDef extends EcFieldDef {
protected final BigInteger prime;
public EcPrimeFieldDef(BigInteger prime) {
this.prime = prime;
}
public final BigInteger prime() {
return this.prime;
}
@Override
public ECFieldFp toECField() {
return new ECFieldFp(this.prime);
}
@Override
public Value toValue() {
return Record.create(2)
.attr("ECField")
.slot("prime", Num.from(prime));
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof EcPrimeFieldDef) {
final EcPrimeFieldDef that = (EcPrimeFieldDef) other;
return this.prime.equals(that.prime);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(EcPrimeFieldDef.class);
}
return Murmur3.mash(Murmur3.mix(hashSeed, this.prime.hashCode()));
}
private static int hashSeed;
public static EcPrimeFieldDef from(ECFieldFp field) {
return new EcPrimeFieldDef(field.getP());
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcPrivateKeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.interfaces.ECPrivateKey;
import java.security.spec.ECPrivateKeySpec;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class EcPrivateKeyDef extends PrivateKeyDef implements EcKeyDef {
protected final EcDomainDef domain;
protected final BigInteger secret;
protected ECPrivateKey privateKey;
EcPrivateKeyDef(EcDomainDef domain, BigInteger secret, ECPrivateKey privateKey) {
this.domain = domain;
this.secret = secret;
this.privateKey = privateKey;
}
public EcPrivateKeyDef(EcDomainDef domain, BigInteger secret) {
this(domain, secret, null);
}
@Override
public final EcDomainDef domain() {
return this.domain;
}
public final BigInteger secret() {
return this.secret;
}
@Override
public ECPrivateKey privateKey() {
ECPrivateKey privateKey = this.privateKey;
if (privateKey == null) {
try {
final ECPrivateKeySpec keySpec = new ECPrivateKeySpec(this.secret, this.domain.toECParameterSpec());
final KeyFactory keyFactory = KeyFactory.getInstance("EC");
privateKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec);
this.privateKey = privateKey;
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
return privateKey;
}
@Override
public Key key() {
return privateKey();
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof EcPrivateKeyDef) {
final EcPrivateKeyDef that = (EcPrivateKeyDef) other;
return this.domain.equals(that.domain) && this.secret.equals(that.secret);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(EcPrivateKeyDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.domain.hashCode()), this.secret.hashCode()));
}
private static int hashSeed;
private static Form<EcPrivateKeyDef> form;
public static EcPrivateKeyDef from(ECPrivateKey key) {
return new EcPrivateKeyDef(EcDomainDef.from(key.getParams()), key.getS(), key);
}
@Kind
public static Form<EcPrivateKeyDef> form() {
if (form == null) {
form = new EcPrivateKeyForm();
}
return form;
}
}
final class EcPrivateKeyForm extends Form<EcPrivateKeyDef> {
@Override
public String tag() {
return "ECPrivateKey";
}
@Override
public Class<?> type() {
return EcPrivateKeyDef.class;
}
@Override
public Item mold(EcPrivateKeyDef keyDef) {
return Record.create(3)
.attr(tag())
.slot("domain", keyDef.domain.toValue())
.slot("secret", Num.from(keyDef.secret));
}
@Override
public EcPrivateKeyDef cast(Item item) {
final Value value = item.toValue();
if (value.getAttr(tag()).isDefined()) {
final EcDomainDef domain = EcDomainDef.form().cast(value.get("domain"));
final BigInteger secret = value.get("secret").integerValue(null);
if (domain != null && secret != null) {
return new EcPrivateKeyDef(domain, secret);
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/EcPublicKeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECPublicKeySpec;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class EcPublicKeyDef extends PublicKeyDef implements EcKeyDef {
protected final EcDomainDef domain;
protected final EcPointDef point;
protected ECPublicKey publicKey;
EcPublicKeyDef(EcDomainDef domain, EcPointDef point, ECPublicKey publicKey) {
this.domain = domain;
this.point = point;
this.publicKey = publicKey;
}
public EcPublicKeyDef(EcDomainDef domain, EcPointDef point) {
this(domain, point, null);
}
@Override
public final EcDomainDef domain() {
return this.domain;
}
public final EcPointDef point() {
return this.point;
}
@Override
public ECPublicKey publicKey() {
ECPublicKey publicKey = this.publicKey;
if (publicKey == null) {
try {
final ECPublicKeySpec keySpec = new ECPublicKeySpec(this.point.toECPoint(),
this.domain.toECParameterSpec());
final KeyFactory keyFactory = KeyFactory.getInstance("EC");
publicKey = (ECPublicKey) keyFactory.generatePublic(keySpec);
this.publicKey = publicKey;
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
return publicKey;
}
@Override
public Key key() {
return publicKey();
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof EcPublicKeyDef) {
final EcPublicKeyDef that = (EcPublicKeyDef) other;
return this.domain.equals(that.domain) && this.point.equals(that.point);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(EcPublicKeyDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.domain.hashCode()), this.point.hashCode()));
}
private static int hashSeed;
private static Form<EcPublicKeyDef> form;
public static EcPublicKeyDef from(ECPublicKey key) {
return new EcPublicKeyDef(EcDomainDef.from(key.getParams()),
EcPointDef.from(key.getW()), key);
}
@Kind
public static Form<EcPublicKeyDef> form() {
if (form == null) {
form = new EcPublicKeyForm();
}
return form;
}
}
final class EcPublicKeyForm extends Form<EcPublicKeyDef> {
@Override
public String tag() {
return "ECPublicKey";
}
@Override
public Class<?> type() {
return EcPublicKeyDef.class;
}
@Override
public Item mold(EcPublicKeyDef keyDef) {
return Record.create(3)
.attr(tag())
.slot("domain", keyDef.domain.toValue())
.slot("point", keyDef.point.toValue());
}
@Override
public EcPublicKeyDef cast(Item item) {
final Value value = item.toValue();
if (value.getAttr(tag()).isDefined()) {
final EcDomainDef domain = EcDomainDef.form().cast(value.get("domain"));
final EcPointDef point = EcPointDef.form().cast(value.get("point"));
if (domain != null && point != null) {
return new EcPublicKeyDef(domain, point);
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/GoogleIdToken.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import swim.json.Json;
import swim.structure.Data;
import swim.structure.Value;
public class GoogleIdToken extends OpenIdToken {
public GoogleIdToken(Value value) {
super(value);
}
public GoogleIdToken() {
super();
}
@Override
public GoogleIdToken issuer(String issuer) {
return (GoogleIdToken) super.issuer(issuer);
}
@Override
public GoogleIdToken subject(String subject) {
return (GoogleIdToken) super.subject(subject);
}
@Override
public GoogleIdToken audience(String audience) {
return (GoogleIdToken) super.audience(audience);
}
@Override
public GoogleIdToken audiences(String... audiences) {
return (GoogleIdToken) super.audiences(audiences);
}
@Override
public GoogleIdToken expiration(long expiration) {
return (GoogleIdToken) super.expiration(expiration);
}
@Override
public GoogleIdToken notBefore(long notBefore) {
return (GoogleIdToken) super.notBefore(notBefore);
}
@Override
public GoogleIdToken issuedAt(long issuedAt) {
return (GoogleIdToken) super.issuedAt(issuedAt);
}
@Override
public GoogleIdToken jwtId(String jwtId) {
return (GoogleIdToken) super.jwtId(jwtId);
}
public GoogleIdToken authTime(long authTime) {
return (GoogleIdToken) super.authTime(authTime);
}
public GoogleIdToken nonce(String nonce) {
return (GoogleIdToken) super.nonce(nonce);
}
public GoogleIdToken accessTokenHash(Data accessTokenHash) {
return (GoogleIdToken) super.accessTokenHash(accessTokenHash);
}
public GoogleIdToken authenticationContextClass(String authenticationContextClass) {
return (GoogleIdToken) super.authenticationContextClass(authenticationContextClass);
}
public GoogleIdToken authenticationMethods(String... authenticationMethods) {
return (GoogleIdToken) super.authenticationMethods(authenticationMethods);
}
public GoogleIdToken authorizedParty(String authorizedParty) {
return (GoogleIdToken) super.authorizedParty(authorizedParty);
}
public String hostedDomain() {
return this.value.get("hd").stringValue(null);
}
public GoogleIdToken hostedDomain(String hostedDomain) {
return copy(this.value.updatedSlot("hd", hostedDomain));
}
public String email() {
return this.value.get("email").stringValue(null);
}
public GoogleIdToken email(String email) {
return copy(this.value.updatedSlot("email", email));
}
public boolean emailVerified() {
return this.value.get("email_verified").booleanValue(false);
}
public GoogleIdToken emailVerified(boolean emailVerified) {
return copy(this.value.updatedSlot("email_verified", emailVerified));
}
public String name() {
return this.value.get("name").stringValue(null);
}
public GoogleIdToken name(String name) {
return copy(this.value.updatedSlot("name", name));
}
public String picture() {
return this.value.get("picture").stringValue(null);
}
public GoogleIdToken picture(String picture) {
return copy(this.value.updatedSlot("picture", picture));
}
public String givenName() {
return this.value.get("given_name").stringValue(null);
}
public GoogleIdToken givenName(String givenName) {
return copy(this.value.updatedSlot("given_name", givenName));
}
public String familyName() {
return this.value.get("family_name").stringValue(null);
}
public GoogleIdToken familyName(String familyName) {
return copy(this.value.updatedSlot("family_name", familyName));
}
public String locale() {
return this.value.get("locale").stringValue(null);
}
public GoogleIdToken locale(String locale) {
return copy(this.value.updatedSlot("locale", locale));
}
@Override
protected GoogleIdToken copy(Value value) {
return new GoogleIdToken(value);
}
public static GoogleIdToken from(Value value) {
return new GoogleIdToken(value);
}
public static GoogleIdToken parse(String json) {
return new GoogleIdToken(Json.parse(json));
}
public static GoogleIdToken verify(JsonWebSignature jws, Iterable<PublicKeyDef> publicKeyDefs) {
final Value payload = jws.payload();
final GoogleIdToken idToken = new GoogleIdToken(payload);
// TODO: check payload
for (PublicKeyDef publicKeyDef : publicKeyDefs) {
if (jws.verifySignature(publicKeyDef.publicKey())) {
return idToken;
}
}
return null;
}
public static GoogleIdToken verify(String compactJws, Iterable<PublicKeyDef> publicKeyDefs) {
final JsonWebSignature jws = JsonWebSignature.parse(compactJws);
if (jws != null) {
return verify(jws, publicKeyDefs);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/JsonWebKey.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.ECKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.KeySpec;
import java.security.spec.RSAMultiPrimePrivateCrtKeySpec;
import java.security.spec.RSAOtherPrimeInfo;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.spec.SecretKeySpec;
import swim.codec.Base64;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.codec.Unicode;
import swim.collections.FingerTrieSeq;
import swim.collections.HashTrieSet;
import swim.json.Json;
import swim.structure.Item;
import swim.structure.Value;
import swim.util.Murmur3;
public class JsonWebKey implements Debug {
protected final Value value;
public JsonWebKey(Value value) {
this.value = value.commit();
}
public Value get(String name) {
return this.value.get(name);
}
public String keyType() {
return this.value.get("kty").stringValue(null);
}
public String publicKeyUse() {
return this.value.get("use").stringValue(null);
}
public HashTrieSet<String> keyOperations() {
HashTrieSet<String> keyOperations = HashTrieSet.empty();
for (Item member : this.value.get("key_ops")) {
final String keyOperation = member.stringValue(null);
if (keyOperation != null) {
keyOperations = keyOperations.added(keyOperation);
}
}
return keyOperations;
}
public String algorithm() {
return this.value.get("alg").stringValue(null);
}
public String keyId() {
return this.value.get("kid").stringValue(null);
}
public String x509Url() {
return this.value.get("x5u").stringValue(null);
}
public FingerTrieSeq<String> x509CertificateChain() {
FingerTrieSeq<String> x509CertificateChain = FingerTrieSeq.empty();
for (Item member : this.value.get("x5c")) {
final String x509Certificate = member.stringValue(null);
if (x509Certificate != null) {
x509CertificateChain = x509CertificateChain.appended(x509Certificate);
}
}
return x509CertificateChain;
}
public String x509Sha1Thumbprint() {
return this.value.get("x5t").stringValue(null);
}
public String x509Sha256Thumbprint() {
return this.value.get("x5t#S256").stringValue(null);
}
public Key key() {
final String keyType = keyType();
if ("EC".equals(keyType)) {
return (Key) ecKey();
} else if ("RSA".equals(keyType)) {
return (Key) rsaKey();
} else if ("oct".equals(keyType)) {
return symmetricKey();
}
return null;
}
public KeyDef keyDef() {
final Key key = key();
if (key != null) {
return KeyDef.from(key);
}
return null;
}
public PublicKey publicKey() {
final String keyType = keyType();
if ("EC".equals(keyType)) {
return (PublicKey) ecPublicKey();
} else if ("RSA".equals(keyType)) {
return (PublicKey) rsaPublicKey();
} else {
return null;
}
}
public PublicKeyDef publicKeyDef() {
final PublicKey publicKey = publicKey();
if (publicKey != null) {
return PublicKeyDef.from(publicKey);
}
return null;
}
public PrivateKey privateKey() {
final String keyType = keyType();
if ("EC".equals(keyType)) {
return (PrivateKey) ecPrivateKey();
} else if ("RSA".equals(keyType)) {
return (PrivateKey) rsaPrivateKey();
} else {
return null;
}
}
public PrivateKeyDef privateKeyDef() {
final PrivateKey privateKey = privateKey();
if (privateKey != null) {
return PrivateKeyDef.from(privateKey);
}
return null;
}
public ECKey ecKey() {
if (this.value.containsKey("d")) {
return ecPrivateKey();
} else {
return ecPublicKey();
}
}
public ECPublicKey ecPublicKey() {
final ECParameterSpec params = ecParameterSpec(this.value.get("crv").stringValue());
final BigInteger x = parseBase64UrlUInt(this.value.get("x").stringValue());
final BigInteger y = parseBase64UrlUInt(this.value.get("y").stringValue());
try {
final ECPublicKeySpec keySpec = new ECPublicKeySpec(new ECPoint(x, y), params);
final KeyFactory keyFactory = KeyFactory.getInstance("EC");
return (ECPublicKey) keyFactory.generatePublic(keySpec);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public ECPrivateKey ecPrivateKey() {
final ECParameterSpec params = ecParameterSpec(this.value.get("crv").stringValue());
final BigInteger d = parseBase64UrlUInt(this.value.get("d").stringValue());
try {
final ECPrivateKeySpec keySpec = new ECPrivateKeySpec(d, params);
final KeyFactory keyFactory = KeyFactory.getInstance("EC");
return (ECPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public RSAKey rsaKey() {
if (this.value.containsKey("d")) {
return rsaPrivateKey();
} else {
return rsaPublicKey();
}
}
public RSAPublicKey rsaPublicKey() {
final BigInteger modulus = parseBase64UrlUInt(this.value.get("n").stringValue());
final BigInteger publicExponent = parseBase64UrlUInt(this.value.get("e").stringValue());
try {
final RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent);
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public RSAPrivateKey rsaPrivateKey() {
final BigInteger modulus = parseBase64UrlUInt(this.value.get("n").stringValue());
final BigInteger privateExponent = parseBase64UrlUInt(this.value.get("d").stringValue());
try {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final KeySpec keySpec;
final Value p = this.value.get("p");
if (!p.isDefined()) {
keySpec = new RSAPrivateKeySpec(modulus, privateExponent);
} else {
final BigInteger publicExponent = parseBase64UrlUInt(this.value.get("e").stringValue());
final BigInteger primeP = parseBase64UrlUInt(p.stringValue());
final BigInteger primeQ = parseBase64UrlUInt(this.value.get("q").stringValue());
final BigInteger primeExponentP = parseBase64UrlUInt(this.value.get("dp").stringValue());
final BigInteger primeExponentQ = parseBase64UrlUInt(this.value.get("dq").stringValue());
final BigInteger crtCoefficient = parseBase64UrlUInt(this.value.get("qi").stringValue());
final Value oth = this.value.get("oth");
if (!oth.isDefined()) {
keySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ,
primeExponentP, primeExponentQ, crtCoefficient);
} else {
final RSAOtherPrimeInfo[] otherPrimeInfo = new RSAOtherPrimeInfo[oth.length()];
for (int i = 0; i < otherPrimeInfo.length; i += 1) {
final Item item = oth.getItem(i);
final BigInteger prime = parseBase64UrlUInt(oth.get("r").stringValue());
final BigInteger primeExponent = parseBase64UrlUInt(oth.get("d").stringValue());
final BigInteger coefficient = parseBase64UrlUInt(oth.get("t").stringValue());
otherPrimeInfo[i] = new RSAOtherPrimeInfo(prime, primeExponent, coefficient);
}
keySpec = new RSAMultiPrimePrivateCrtKeySpec(modulus, publicExponent, privateExponent,
primeP, primeQ, primeExponentP, primeExponentQ,
crtCoefficient, otherPrimeInfo);
}
}
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public Key symmetricKey(String algorithm) {
return new SecretKeySpec(parseBase64Url(this.value.get("k").stringValue()), algorithm);
}
public Key symmetricKey() {
final String algorithm = algorithm();
if ("HS256".equals(algorithm)) {
return symmetricKey("HmacSHA256");
} else if ("HS384".equals(algorithm)) {
return symmetricKey("HmacSHA384");
} else if ("HS512".equals(algorithm)) {
return symmetricKey("HmacSHA512");
} else {
return symmetricKey("");
}
}
public final Value toValue() {
return this.value;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof JsonWebKey) {
final JsonWebKey that = (JsonWebKey) other;
return this.value.equals(that.value);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(JsonWebKey.class);
}
return Murmur3.mash(Murmur3.mix(hashSeed, this.value.hashCode()));
}
@Override
public void debug(Output<?> output) {
output.write("JsonWebKey").write('.').write("from").write('(')
.debug(this.value).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
static ECParameterSpec p256;
static ECParameterSpec p384;
static ECParameterSpec p521;
public static JsonWebKey from(Value value) {
// TODO: validate
return new JsonWebKey(value);
}
public static JsonWebKey parse(String jwk) {
return from(Json.parse(jwk));
}
private static byte[] parseBase64Url(String value) {
return Base64.urlUnpadded().parseByteArray(Unicode.stringInput(value)).bind();
}
private static BigInteger parseBase64UrlUInt(String value) {
return new BigInteger(1, parseBase64Url(value));
}
private static ECParameterSpec ecParameterSpec(String crv) {
if ("P-256".equals(crv)) {
if (p256 == null) {
p256 = createECParameterSpec("secp256r1");
}
return p256;
} else if ("P-384".equals(crv)) {
if (p384 == null) {
p384 = createECParameterSpec("secp384r1");
}
return p384;
} else if ("P-521".equals(crv)) {
if (p521 == null) {
p521 = createECParameterSpec("secp521r1");
}
return p521;
} else {
return null;
}
}
private static ECParameterSpec createECParameterSpec(String stdName) {
try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
final ECGenParameterSpec parameterSpec = new ECGenParameterSpec(stdName);
keyPairGenerator.initialize(parameterSpec);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
return publicKey.getParams();
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/JsonWebSignature.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.ECKey;
import java.security.interfaces.RSAKey;
import javax.crypto.Mac;
import swim.codec.Base64;
import swim.codec.Binary;
import swim.codec.Debug;
import swim.codec.Decoder;
import swim.codec.Diagnostic;
import swim.codec.Format;
import swim.codec.Input;
import swim.codec.Output;
import swim.codec.Parser;
import swim.codec.Unicode;
import swim.codec.Utf8;
import swim.codec.Writer;
import swim.collections.FingerTrieSeq;
import swim.collections.HashTrieSet;
import swim.json.Json;
import swim.structure.Data;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class JsonWebSignature implements Debug {
protected final Value unprotectedHeader;
protected final Value protectedHeader;
protected final Data signingInput;
protected final Data payloadData;
protected final Data signatureData;
public JsonWebSignature(Value unprotectedHeader, Value protectedHeader,
Data signingInput, Data payloadData, Data signatureData) {
this.unprotectedHeader = unprotectedHeader.commit();
this.protectedHeader = protectedHeader.commit();
this.signingInput = signingInput;
this.payloadData = payloadData;
this.signatureData = signatureData;
}
public final Value unprotectedHeader() {
return this.unprotectedHeader;
}
public JsonWebSignature unprotectedHeader(Value unprotectedHeader) {
return new JsonWebSignature(unprotectedHeader, this.protectedHeader, this.signingInput,
this.payloadData, this.signatureData);
}
public final Value protectedHeader() {
return this.protectedHeader;
}
public final Data signingInput() {
return this.signingInput;
}
public final Data payloadData() {
return this.payloadData;
}
public final <T> T payload(Decoder<T> decoder) {
decoder = decoder.feed(payloadData.toInputBuffer());
if (decoder.isDone()) {
return decoder.bind();
} else {
final Throwable trap = decoder.trap();
if (trap instanceof RuntimeException) {
throw (RuntimeException) trap;
} else {
throw new RuntimeException(trap);
}
}
}
public final <T> T payload(Form<T> form) {
return payload(Json.formDecoder(form));
}
public final Value payload() {
return payload(Form.forValue());
}
public final Data signatureData() {
return this.signatureData;
}
public Value get(String name) {
Value value = this.protectedHeader.get(name);
if (!value.isDefined()) {
value = this.unprotectedHeader.get(name);
}
return value;
}
public String algorithm() {
return get("alg").stringValue(null);
}
public String jsonWebKeySetUrl() {
return get("jku").stringValue(null);
}
public JsonWebKey jsonWebKey() {
return JsonWebKey.from(get("jwk"));
}
public String keyId() {
return get("kid").stringValue(null);
}
public String x509Url() {
return get("x5u").stringValue(null);
}
public FingerTrieSeq<String> x509CertificateChain() {
FingerTrieSeq<String> x509CertificateChain = FingerTrieSeq.empty();
for (Item member : get("x5c")) {
final String x509Certificate = member.stringValue(null);
if (x509Certificate != null) {
x509CertificateChain = x509CertificateChain.appended(x509Certificate);
}
}
return x509CertificateChain;
}
public String x509Sha1Thumbprint() {
return get("x5t").stringValue(null);
}
public String x509Sha256Thumbprint() {
return get("x5t#S256").stringValue(null);
}
public String type() {
return get("typ").stringValue(null);
}
public String contentType() {
return get("cty").stringValue(null);
}
public HashTrieSet<String> critical() {
HashTrieSet<String> critical = HashTrieSet.empty();
for (Item member : get("crit")) {
final String name = member.stringValue(null);
if (name != null) {
critical = critical.added(name);
}
}
return critical;
}
public boolean verifyMac(Key symmetricKey) {
final String algorithm = algorithm();
try {
if ("HS256".equals(algorithm)) {
return verifyMac(Mac.getInstance("HmacSHA256"), symmetricKey);
} else if ("HS384".equals(algorithm)) {
return verifyMac(Mac.getInstance("HmacSHA384"), symmetricKey);
} else if ("HS512".equals(algorithm)) {
return verifyMac(Mac.getInstance("HmacSHA512"), symmetricKey);
} else {
return false;
}
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public boolean verifyMac(Mac mac, Key symmetricKey) {
try {
mac.init(symmetricKey);
mac.update(signingInput.asByteBuffer());
final Data signatureData = Data.wrap(mac.doFinal());
return compareSignatureData(signatureData, this.signatureData);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public boolean verifySignature(PublicKey publicKey) {
final String algorithm = algorithm();
try {
if ("ES256".equals(algorithm)) {
return verifyECDSASignature(Signature.getInstance("SHA256withECDSA"), publicKey);
} else if ("ES384".equals(algorithm)) {
return verifyECDSASignature(Signature.getInstance("SHA384withECDSA"), publicKey);
} else if ("ES512".equals(algorithm)) {
return verifyECDSASignature(Signature.getInstance("SHA512withECDSA"), publicKey);
} else if ("RS256".equals(algorithm)) {
return verifyRSASignature(Signature.getInstance("SHA256withRSA"), publicKey);
} else if ("RS384".equals(algorithm)) {
return verifyRSASignature(Signature.getInstance("SHA384withRSA"), publicKey);
} else if ("RS512".equals(algorithm)) {
return verifyRSASignature(Signature.getInstance("SHA512withRSA"), publicKey);
} else {
return false;
}
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public boolean verifyRSASignature(Signature signature, PublicKey publicKey) {
try {
signature.initVerify(publicKey);
signature.update(signingInput.asByteBuffer());
return signature.verify(signatureData.asByteArray(), 0, signatureData.size());
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public boolean verifyECDSASignature(Signature signature, PublicKey publicKey) {
final Data signatureData = derEncodeECDSASignature(this.signatureData);
try {
signature.initVerify(publicKey);
signature.update(signingInput.asByteBuffer());
return signature.verify(signatureData.asByteArray(), 0, signatureData.size());
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public Writer<?, JsonWebSignature> writeJws(Output<?> output) {
return JsonWebSignatureWriter.write(output, this);
}
public String toJws() {
final Output<String> output = Unicode.stringOutput();
writeJws(output);
return output.bind();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof JsonWebSignature) {
final JsonWebSignature that = (JsonWebSignature) other;
return this.unprotectedHeader.equals(that.unprotectedHeader)
&& this.protectedHeader.equals(that.protectedHeader)
&& this.signingInput.equals(that.signingInput)
&& this.payloadData.equals(that.payloadData)
&& this.signatureData.equals(that.signatureData);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(JsonWebSignature.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(
hashSeed, this.unprotectedHeader.hashCode()), this.protectedHeader.hashCode()),
this.signingInput.hashCode()), this.payloadData.hashCode()),
this.signatureData.hashCode()));
}
@Override
public void debug(Output<?> output) {
output.write("JsonWebSignature").write('.').write("from").write('(')
.debug(unprotectedHeader).write(", ").debug(protectedHeader).write(", ")
.debug(signingInput).write(", ").debug(payloadData).write(", ")
.debug(signatureData).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static JsonWebSignature from(Value unprotectedHeader, Data signingInput, Data protectedHeaderData,
Data payloadData, Data signatureData) {
final Value protectedHeader = Json.structureParser().parseObject(Utf8.decodedInput(protectedHeaderData.toInputBuffer())).bind();
return new JsonWebSignature(unprotectedHeader, protectedHeader, signingInput, payloadData, signatureData);
}
public static JsonWebSignature from(Data signingInput, Data protectedHeaderData,
Data payloadData, Data signatureData) {
return from(Value.absent(), signingInput, protectedHeaderData, payloadData, signatureData);
}
public static JsonWebSignature from(Value unprotectedHeader, Data protectedHeaderData,
Data payloadData, Data signatureData) {
final Output<Data> signingInput = Data.output();
Base64.urlUnpadded().writeByteBuffer(protectedHeaderData.asByteBuffer(), signingInput);
signingInput.write('.');
Base64.urlUnpadded().writeByteBuffer(payloadData.asByteBuffer(), signingInput);
return from(unprotectedHeader, signingInput.bind(), protectedHeaderData, payloadData, signatureData);
}
public static JsonWebSignature from(Data protectedHeaderData, Data payloadData, Data signatureData) {
return from(Value.absent(), protectedHeaderData, payloadData, signatureData);
}
public static JsonWebSignature hmacSHA(Mac mac, Key symmetricKey, Value unprotectedHeader,
Value protectedHeader, Data signingInput, Data payloadData) {
try {
mac.init(symmetricKey);
mac.update(signingInput.asByteBuffer());
final Data signatureData = Data.wrap(mac.doFinal());
return new JsonWebSignature(unprotectedHeader, protectedHeader, signingInput,
payloadData, signatureData);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static JsonWebSignature hmacSHA(Mac mac, Key symmetricKey, Value unprotectedHeader,
Value protectedHeader, Data payloadData) {
final Data protectedHeaderData = Json.toData(protectedHeader);
final Output<Data> signingInput = Data.output();
Base64.urlUnpadded().writeByteBuffer(protectedHeaderData.asByteBuffer(), signingInput);
signingInput.write('.');
Base64.urlUnpadded().writeByteBuffer(payloadData.asByteBuffer(), signingInput);
return hmacSHA(mac, symmetricKey, unprotectedHeader, protectedHeader,
signingInput.bind(), payloadData);
}
public static JsonWebSignature hmacSHA(Key symmetricKey, Value unprotectedHeader,
Value protectedHeader, Data payloadData) {
final String algorithm = symmetricKey.getAlgorithm();
final Mac mac;
try {
if ("HmacSHA256".equals(algorithm)) {
protectedHeader = protectedHeader.updatedSlot("alg", "HS256");
mac = Mac.getInstance("HmacSHA256");
} else if ("HmacSHA384".equals(algorithm)) {
protectedHeader = protectedHeader.updatedSlot("alg", "HS384");
mac = Mac.getInstance("HmacSHA384");
} else if ("HmacSHA512".equals(algorithm)) {
protectedHeader = protectedHeader.updatedSlot("alg", "HS512");
mac = Mac.getInstance("HmacSHA512");
} else {
throw new IllegalArgumentException("unsupported key size");
}
return hmacSHA(mac, symmetricKey, unprotectedHeader, protectedHeader, payloadData);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static JsonWebSignature mac(Key symmetricKey, Value unprotectedHeader,
Value protectedHeader, Data payloadData) {
return hmacSHA(symmetricKey, unprotectedHeader, protectedHeader, payloadData);
}
public static JsonWebSignature mac(Key symmetricKey, Value protectedHeader, Data payloadData) {
return mac(symmetricKey, Value.absent(), protectedHeader, payloadData);
}
public static JsonWebSignature mac(Key symmetricKey, Data payloadData) {
return mac(symmetricKey, Value.absent(), Value.absent(), payloadData);
}
public static JsonWebSignature signRSA(Signature signature, PrivateKey privateKey, int keyLength,
Value unprotectedHeader, Value protectedHeader,
Data signingInput, Data payloadData) {
try {
signature.initSign(privateKey);
signature.update(signingInput.asByteBuffer());
final Data signatureData = Data.wrap(signature.sign());
return new JsonWebSignature(unprotectedHeader, protectedHeader, signingInput,
payloadData, signatureData);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static JsonWebSignature signRSA(Signature signature, PrivateKey privateKey, int keyLength,
Value unprotectedHeader, Value protectedHeader, Data payloadData) {
final Data protectedHeaderData = Json.toData(protectedHeader);
final Output<Data> signingInput = Data.output();
Base64.urlUnpadded().writeByteBuffer(protectedHeaderData.asByteBuffer(), signingInput);
signingInput.write('.');
Base64.urlUnpadded().writeByteBuffer(payloadData.asByteBuffer(), signingInput);
return signRSA(signature, privateKey, keyLength, unprotectedHeader, protectedHeader,
signingInput.bind(), payloadData);
}
public static JsonWebSignature signRSA(PrivateKey privateKey, Value unprotectedHeader,
Value protectedHeader, Data payloadData) {
final int keyLength = rsaKeyLength(privateKey);
final Signature signature;
try {
if (keyLength == 32) {
protectedHeader = protectedHeader.updatedSlot("alg", "RS256");
signature = Signature.getInstance("SHA256withRSA");
} else if (keyLength == 48) {
protectedHeader = protectedHeader.updatedSlot("alg", "RS384");
signature = Signature.getInstance("SHA384withRSA");
} else if (keyLength == 64) {
protectedHeader = protectedHeader.updatedSlot("alg", "RS512");
signature = Signature.getInstance("SHA512withRSA");
} else {
throw new IllegalArgumentException("unsupported key size");
}
return signRSA(signature, privateKey, keyLength, unprotectedHeader,
protectedHeader, payloadData);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static JsonWebSignature signECDSA(Signature signature, PrivateKey privateKey, int keyLength,
Value unprotectedHeader, Value protectedHeader,
Data signingInput, Data payloadData) {
try {
signature.initSign(privateKey);
signature.update(signingInput.asByteBuffer());
Data signatureData = Data.wrap(signature.sign());
signatureData = derDecodeECDSASignature(signatureData, keyLength);
return new JsonWebSignature(unprotectedHeader, protectedHeader, signingInput,
payloadData, signatureData);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static JsonWebSignature signECDSA(Signature signature, PrivateKey privateKey, int keyLength,
Value unprotectedHeader, Value protectedHeader, Data payloadData) {
final Data protectedHeaderData = Json.toData(protectedHeader);
final Output<Data> signingInput = Data.output();
Base64.urlUnpadded().writeByteBuffer(protectedHeaderData.asByteBuffer(), signingInput);
signingInput.write('.');
Base64.urlUnpadded().writeByteBuffer(payloadData.asByteBuffer(), signingInput);
return signECDSA(signature, privateKey, keyLength, unprotectedHeader, protectedHeader,
signingInput.bind(), payloadData);
}
public static JsonWebSignature signECDSA(PrivateKey privateKey, Value unprotectedHeader,
Value protectedHeader, Data payloadData) {
final int keyLength = ecKeyLength(privateKey);
final Signature signature;
try {
if (keyLength == 32) {
protectedHeader = protectedHeader.updatedSlot("alg", "ES256");
signature = Signature.getInstance("SHA256withECDSA");
} else if (keyLength == 48) {
protectedHeader = protectedHeader.updatedSlot("alg", "ES384");
signature = Signature.getInstance("SHA384withECDSA");
} else if (keyLength == 66) {
protectedHeader = protectedHeader.updatedSlot("alg", "ES512");
signature = Signature.getInstance("SHA512withECDSA");
} else {
throw new IllegalArgumentException("unsupported key size");
}
return signECDSA(signature, privateKey, keyLength, unprotectedHeader,
protectedHeader, payloadData);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static JsonWebSignature sign(PrivateKey privateKey, Value unprotectedHeader,
Value protectedHeader, Data payloadData) {
if (privateKey instanceof ECKey) {
return signECDSA(privateKey, unprotectedHeader, protectedHeader, payloadData);
} else if (privateKey instanceof RSAKey) {
return signRSA(privateKey, unprotectedHeader, protectedHeader, payloadData);
} else {
throw new IllegalArgumentException("unsupported signing key type");
}
}
public static JsonWebSignature sign(PrivateKey privateKey, Value protectedHeader, Data payloadData) {
return sign(privateKey, Value.absent(), protectedHeader, payloadData);
}
public static JsonWebSignature sign(PrivateKey privateKey, Data payloadData) {
return sign(privateKey, Value.absent(), Value.absent(), payloadData);
}
public static Parser<JsonWebSignature> parser() {
return new JsonWebSignatureParser();
}
public static JsonWebSignature parse(String jws) {
final Input input = Unicode.stringInput(jws);
Parser<JsonWebSignature> parser = JsonWebSignatureParser.parse(input);
if (input.isCont() && !parser.isError()) {
parser = Parser.error(Diagnostic.unexpected(input));
} else if (input.isError()) {
parser = Parser.error(input.trap());
}
return parser.bind();
}
static boolean compareSignatureData(Data actual, Data expected) {
// MUST take constant time regardless of match success
boolean matches = true;
for (int i = 0, n = Math.min(actual.size(), expected.size()); i < n; i += 1) {
matches = actual.getByte(i) == expected.getByte(i) && matches;
}
return matches;
}
static int ecKeyLength(Key key) {
final int bitLength = ((ECKey) key).getParams().getOrder().bitLength();
if (bitLength <= 256) {
return 32;
} else if (bitLength <= 384) {
return 48;
} else if (bitLength <= 521) {
return 66;
} else {
throw new IllegalArgumentException("unsupported key size");
}
}
static int rsaKeyLength(Key key) {
final int bitLength = ((RSAKey) key).getModulus().bitLength();
if (bitLength <= 2048) {
return 32;
} else if (bitLength <= 3072) {
return 48;
} else if (bitLength <= 4096) {
return 64;
} else {
throw new IllegalArgumentException("unsupported key size");
}
}
static Data derDecodeECDSASignature(Data derData, int n) {
final Value sequence = Der.structureDecoder().decodeValue(derData.toInputBuffer()).bind();
final byte[] r = ((Num) sequence.getItem(0)).integerValue().toByteArray();
final byte[] s = ((Num) sequence.getItem(1)).integerValue().toByteArray();
final byte[] signatureBytes = new byte[n << 1];
if (r.length <= n) {
System.arraycopy(r, 0, signatureBytes, n - r.length, r.length);
} else {
System.arraycopy(r, r.length - n, signatureBytes, 0, n);
}
if (s.length <= n) {
System.arraycopy(s, 0, signatureBytes, n + (n - s.length), s.length);
} else {
System.arraycopy(s, s.length - n, signatureBytes, n, n);
}
return Data.wrap(signatureBytes);
}
static Data derEncodeECDSASignature(Data signatureData) {
final int n = signatureData.size() >>> 1;
final byte[] signature = signatureData.asByteArray();
final byte[] magnitude = new byte[n];
System.arraycopy(signature, 0, magnitude, 0, n);
final Num r = Num.from(new BigInteger(1, magnitude));
System.arraycopy(signature, n, magnitude, 0, n);
final Num s = Num.from(new BigInteger(1, magnitude));
final Value sequence = Record.of(r, s);
final byte[] derBytes = new byte[Der.structureEncoder().sizeOf(sequence)];
Der.structureEncoder().encode(sequence, Binary.outputBuffer(derBytes));
return Data.wrap(derBytes);
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/JsonWebSignatureParser.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Parser;
import swim.structure.Data;
final class JsonWebSignatureParser extends Parser<JsonWebSignature> {
final Data signingInput;
final Data protectedHeaderData;
final Data payloadData;
final Data signatureData;
final int p;
final int q;
final int r;
final int step;
JsonWebSignatureParser(Data signingInput, Data protectedHeaderData, Data payloadData,
Data signatureData, int p, int q, int r, int step) {
this.signingInput = signingInput;
this.protectedHeaderData = protectedHeaderData;
this.payloadData = payloadData;
this.signatureData = signatureData;
this.p = p;
this.q = q;
this.r = r;
this.step = step;
}
JsonWebSignatureParser() {
this(null, null, null, null, 0, 0, 0, 1);
}
@Override
public Parser<JsonWebSignature> feed(Input input) {
return parse(signingInput, protectedHeaderData, payloadData,
signatureData, p, q, r, step, input);
}
static Parser<JsonWebSignature> parse(Data signingInput, Data protectedHeaderData,
Data payloadData, Data signatureData,
int p, int q, int r, int step, Input input) {
int c;
if (signingInput == null) {
signingInput = Data.create();
}
if (protectedHeaderData == null) {
protectedHeaderData = Data.create();
}
if (payloadData == null) {
payloadData = Data.create();
}
if (signatureData == null) {
signatureData = Data.create();
}
do {
if (step == 1) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
signingInput.addByte((byte) c);
p = c;
step = 2;
} else {
step = 5;
break;
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
if (step == 2) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
signingInput.addByte((byte) c);
q = c;
step = 3;
} else {
return error(Diagnostic.expected("base64 digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
if (step == 3) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
signingInput.addByte((byte) c);
r = c;
step = 4;
} else {
decodeBase64Quantum(p, q, '=', '=', protectedHeaderData);
step = 5;
break;
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
if (step == 4) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
signingInput.addByte((byte) c);
decodeBase64Quantum(p, q, r, c, protectedHeaderData);
step = 1;
continue;
} else {
decodeBase64Quantum(p, q, r, '=', protectedHeaderData);
step = 5;
break;
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
break;
} while (true);
if (step == 5) {
if (input.isCont()) {
c = input.head();
if (c == '.') {
input = input.step();
signingInput.addByte((byte) c);
step = 6;
} else {
return error(Diagnostic.expected('.', input));
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
do {
if (step == 6) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
signingInput.addByte((byte) c);
p = c;
step = 7;
} else {
step = 10;
break;
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
if (step == 7) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
signingInput.addByte((byte) c);
q = c;
step = 8;
} else {
return error(Diagnostic.expected("base64 digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
if (step == 8) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
signingInput.addByte((byte) c);
r = c;
step = 9;
} else {
decodeBase64Quantum(p, q, '=', '=', payloadData);
step = 10;
break;
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
if (step == 9) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
signingInput.addByte((byte) c);
decodeBase64Quantum(p, q, r, c, payloadData);
step = 6;
continue;
} else {
decodeBase64Quantum(p, q, r, '=', payloadData);
step = 10;
break;
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
break;
} while (true);
if (step == 10) {
if (input.isCont()) {
c = input.head();
if (c == '.') {
input = input.step();
step = 11;
} else {
return error(Diagnostic.expected('.', input));
}
} else {
return error(Diagnostic.unexpected(input));
}
}
do {
if (step == 11) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
p = c;
step = 12;
} else {
return done(JsonWebSignature.from(signingInput, protectedHeaderData, payloadData, signatureData));
}
} else if (input.isDone()) {
return done(JsonWebSignature.from(signingInput, protectedHeaderData, payloadData, signatureData));
}
}
if (step == 12) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
q = c;
step = 13;
} else {
return error(Diagnostic.expected("base64 digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
if (step == 13) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
r = c;
step = 14;
} else {
decodeBase64Quantum(p, q, '=', '=', signatureData);
return done(JsonWebSignature.from(signingInput, protectedHeaderData, payloadData, signatureData));
}
} else if (input.isDone()) {
decodeBase64Quantum(p, q, '=', '=', signatureData);
return done(JsonWebSignature.from(signingInput, protectedHeaderData, payloadData, signatureData));
}
}
if (step == 14) {
if (input.isCont()) {
c = input.head();
if (isBase64Char(c)) {
input = input.step();
decodeBase64Quantum(p, q, r, c, signatureData);
step = 11;
continue;
} else {
decodeBase64Quantum(p, q, r, '=', signatureData);
return done(JsonWebSignature.from(signingInput, protectedHeaderData, payloadData, signatureData));
}
} else if (input.isDone()) {
decodeBase64Quantum(p, q, r, '=', signatureData);
return done(JsonWebSignature.from(signingInput, protectedHeaderData, payloadData, signatureData));
}
}
break;
} while (true);
return new JsonWebSignatureParser(signingInput, protectedHeaderData, payloadData,
signatureData, p, q, r, step);
}
static Parser<JsonWebSignature> parse(Input input) {
return parse(null, null, null, null, 0, 0, 0, 1, input);
}
static boolean isBase64Char(int c) {
return c >= '0' && c <= '9'
|| c >= 'A' && c <= 'Z'
|| c >= 'a' && c <= 'z'
|| c == '-' || c == '_';
}
static int decodeBase64Digit(int c) {
if (c >= 'A' && c <= 'Z') {
return c - 'A';
} else if (c >= 'a' && c <= 'z') {
return c + (26 - 'a');
} else if (c >= '0' && c <= '9') {
return c + (52 - '0');
} else if (c == '-') {
return 62;
} else if (c == '_') {
return 63;
} else {
final String message = new StringBuilder("invalid base64 digit: ").appendCodePoint(c).toString();
throw new IllegalArgumentException(message);
}
}
static void decodeBase64Quantum(int p, int q, int r, int s, Data data) {
final int x = decodeBase64Digit(p);
final int y = decodeBase64Digit(q);
if (r != '=') {
final int z = decodeBase64Digit(r);
if (s != '=') {
final int w = decodeBase64Digit(s);
data.addByte((byte) ((x << 2) | (y >>> 4)));
data.addByte((byte) ((y << 4) | (z >>> 2)));
data.addByte((byte) ((z << 6) | w));
} else {
data.addByte((byte) ((x << 2) | (y >>> 4)));
data.addByte((byte) ((y << 4) | (z >>> 2)));
}
} else {
if (s != '=') {
throw new IllegalArgumentException("expected '='");
}
data.addByte((byte) ((x << 2) | (y >>> 4)));
}
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/JsonWebSignatureWriter.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import swim.codec.Base64;
import swim.codec.Binary;
import swim.codec.Output;
import swim.codec.Writer;
import swim.codec.WriterException;
final class JsonWebSignatureWriter extends Writer<Object, JsonWebSignature> {
final JsonWebSignature jws;
final Writer<?, ?> part;
final int step;
JsonWebSignatureWriter(JsonWebSignature jws, Writer<?, ?> part, int step) {
this.jws = jws;
this.part = part;
this.step = step;
}
@Override
public Writer<Object, JsonWebSignature> pull(Output<?> output) {
return write(output, jws, part, step);
}
static Writer<Object, JsonWebSignature> write(Output<?> output, JsonWebSignature jws,
Writer<?, ?> part, int step) {
if (step == 1) {
if (part == null) {
part = Binary.writeByteBuffer(jws.signingInput.asByteBuffer(), output);
} else {
part = part.pull(output);
}
if (part.isDone()) {
part = null;
step = 2;
} else if (part.isError()) {
return part.asError();
}
}
if (step == 2 && output.isCont()) {
output.write('.');
step = 3;
}
if (step == 3) {
if (part == null) {
part = Base64.urlUnpadded().writeByteBuffer(jws.signatureData.asByteBuffer(), output);
} else {
part = part.pull(output);
}
if (part.isDone()) {
return done(jws);
} else if (part.isError()) {
return part.asError();
}
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new JsonWebSignatureWriter(jws, part, step);
}
static Writer<Object, JsonWebSignature> write(Output<?> output, JsonWebSignature jws) {
return write(output, jws, null, 1);
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/JsonWebToken.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.security.Key;
import java.security.PrivateKey;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.collections.FingerTrieSeq;
import swim.json.Json;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Slot;
import swim.structure.Value;
import swim.util.Builder;
import swim.util.Murmur3;
public class JsonWebToken implements Debug {
protected final Value value;
public JsonWebToken(Value value) {
this.value = value.commit();
}
public JsonWebToken() {
this(Value.absent());
}
public Value get(String name) {
return this.value.get(name);
}
public String issuer() {
return this.value.get("iss").stringValue(null);
}
public JsonWebToken issuer(String issuer) {
return copy(this.value.updatedSlot("iss", issuer));
}
public String subject() {
return this.value.get("sub").stringValue(null);
}
public JsonWebToken subject(String subject) {
return copy(this.value.updatedSlot("sub", subject));
}
public String audience() {
return this.value.get("aud").stringValue(null);
}
public JsonWebToken audience(String audience) {
return copy(this.value.updatedSlot("aud", audience));
}
public FingerTrieSeq<String> audiences() {
final Builder<String, FingerTrieSeq<String>> builder = FingerTrieSeq.builder();
for (Item member : this.value.get("aud")) {
final String audience = member.stringValue(null);
if (audience != null) {
builder.add(audience);
}
}
return builder.bind();
}
public JsonWebToken audiences(String... audiences) {
return copy(this.value.updatedSlot("aud", Record.of((Object[]) audiences)));
}
public long expiration() {
return this.value.get("exp").longValue(Long.MAX_VALUE);
}
public JsonWebToken expiration(long expiration) {
return copy(this.value.updatedSlot("exp", expiration));
}
public long notBefore() {
return this.value.get("nbf").longValue(0L);
}
public JsonWebToken notBefore(long notBefore) {
return copy(this.value.updatedSlot("nbf", notBefore));
}
public long issuedAt() {
return this.value.get("iat").longValue(0L);
}
public JsonWebToken issuedAt(long issuedAt) {
return copy(this.value.updatedSlot("iat", issuedAt));
}
public String jwtId() {
return this.value.get("jti").stringValue(null);
}
public JsonWebToken jwtId(String jwtId) {
return copy(this.value.updatedSlot("jti", jwtId));
}
public Record joseHeader() {
return Record.of(Slot.of("typ", "JWT"));
}
public JsonWebSignature mac(Key symmetricKey) {
return JsonWebSignature.mac(symmetricKey, joseHeader(), Json.toData(this.value));
}
public JsonWebSignature sign(PrivateKey privateKey) {
return JsonWebSignature.sign(privateKey, joseHeader(), Json.toData(this.value));
}
public final Value toValue() {
return this.value;
}
protected JsonWebToken copy(Value value) {
return new JsonWebToken(value);
}
protected boolean canEqual(Object other) {
return other instanceof JsonWebToken;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof JsonWebToken) {
final JsonWebToken that = (JsonWebToken) other;
return that.canEqual(this) && this.value.equals(that.value);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(JsonWebToken.class);
}
return Murmur3.mash(Murmur3.mix(hashSeed, this.value.hashCode()));
}
@Override
public void debug(Output<?> output) {
output.write(getClass().getSimpleName()).write('.').write("from").write('(')
.debug(this.value).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static JsonWebToken from(Value value) {
return new JsonWebToken(value);
}
public static JsonWebToken parse(String json) {
return new JsonWebToken(Json.parse(json));
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/KeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Value;
public abstract class KeyDef {
public abstract Key key();
public abstract Value toValue();
private static Form<KeyDef> keyForm;
public static KeyDef from(Key key) {
if (key instanceof PublicKey) {
return PublicKeyDef.from((PublicKey) key);
} else if (key instanceof PrivateKey) {
return PrivateKeyDef.from((PrivateKey) key);
}
throw new IllegalArgumentException(key.toString());
}
@Kind
public static Form<KeyDef> keyForm() {
if (keyForm == null) {
keyForm = new KeyForm();
}
return keyForm;
}
}
final class KeyForm extends Form<KeyDef> {
@Override
public Class<?> type() {
return KeyDef.class;
}
@Override
public Item mold(KeyDef keyDef) {
return keyDef.toValue();
}
@Override
public KeyDef cast(Item item) {
KeyDef keyDef = PublicKeyDef.publicKeyForm().cast(item);
if (keyDef != null) {
return keyDef;
}
keyDef = PrivateKeyDef.privateKeyForm().cast(item);
if (keyDef != null) {
return keyDef;
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/OpenIdToken.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import swim.codec.Base64;
import swim.codec.Output;
import swim.codec.Parser;
import swim.codec.Unicode;
import swim.collections.FingerTrieSeq;
import swim.json.Json;
import swim.structure.Data;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Builder;
// http://openid.net/specs/openid-connect-basic-1_0-27.html#id_token
public class OpenIdToken extends JsonWebToken {
public OpenIdToken(Value value) {
super(value);
}
public OpenIdToken() {
super();
}
@Override
public OpenIdToken issuer(String issuer) {
return (OpenIdToken) super.issuer(issuer);
}
@Override
public OpenIdToken subject(String subject) {
return (OpenIdToken) super.subject(subject);
}
@Override
public OpenIdToken audience(String audience) {
return (OpenIdToken) super.audience(audience);
}
@Override
public OpenIdToken audiences(String... audiences) {
return (OpenIdToken) super.audiences(audiences);
}
@Override
public OpenIdToken expiration(long expiration) {
return (OpenIdToken) super.expiration(expiration);
}
@Override
public OpenIdToken notBefore(long notBefore) {
return (OpenIdToken) super.notBefore(notBefore);
}
@Override
public OpenIdToken issuedAt(long issuedAt) {
return (OpenIdToken) super.issuedAt(issuedAt);
}
@Override
public OpenIdToken jwtId(String jwtId) {
return (OpenIdToken) super.jwtId(jwtId);
}
public long authTime() {
return this.value.get("auth_time").longValue(0L);
}
public OpenIdToken authTime(long authTime) {
return copy(this.value.updatedSlot("auth_time", authTime));
}
public String nonce() {
return this.value.get("nonce").stringValue(null);
}
public OpenIdToken nonce(String nonce) {
return copy(this.value.updatedSlot("nonce", nonce));
}
public Data accessTokenHash() {
final String atHash = this.value.get("at_hash").stringValue(null);
if (atHash != null) {
final Parser<Data> parser = Base64.urlUnpadded().parse(Unicode.stringInput(atHash), Data.output());
if (parser.isDone()) {
return parser.bind();
} else {
final Throwable trap = parser.trap();
if (trap instanceof RuntimeException) {
throw (RuntimeException) trap;
} else {
throw new RuntimeException(trap);
}
}
}
return null;
}
public OpenIdToken accessTokenHash(Data accessTokenHash) {
final Output<String> atHash = Unicode.stringOutput();
Base64.urlUnpadded().writeByteBuffer(accessTokenHash.asByteBuffer(), atHash);
return copy(this.value.updatedSlot("at_hash", atHash.bind()));
}
public String authenticationContextClass() {
return this.value.get("acr").stringValue(null);
}
public OpenIdToken authenticationContextClass(String authenticationContextClass) {
return copy(this.value.updatedSlot("acr", authenticationContextClass));
}
public FingerTrieSeq<String> authenticationMethods() {
final Builder<String, FingerTrieSeq<String>> builder = FingerTrieSeq.builder();
for (Item member : this.value.get("amr")) {
final String authenticationMethod = member.stringValue(null);
if (authenticationMethod != null) {
builder.add(authenticationMethod);
}
}
return builder.bind();
}
public OpenIdToken authenticationMethods(String... authenticationMethods) {
return copy(this.value.updatedSlot("amr", Record.of((Object[]) authenticationMethods)));
}
public String authorizedParty() {
return this.value.get("azp").stringValue(null);
}
public OpenIdToken authorizedParty(String authorizedParty) {
return copy(this.value.updatedSlot("azp", authorizedParty));
}
@Override
protected OpenIdToken copy(Value value) {
return new OpenIdToken(value);
}
public static OpenIdToken from(Value value) {
return new OpenIdToken(value);
}
public static OpenIdToken parse(String json) {
return new OpenIdToken(Json.parse(json));
}
public static OpenIdToken verify(JsonWebSignature jws, Iterable<PublicKeyDef> publicKeyDefs) {
final Value payload = jws.payload();
final OpenIdToken idToken = new OpenIdToken(payload);
// TODO: check payload
for (PublicKeyDef publicKeyDef : publicKeyDefs) {
if (jws.verifySignature(publicKeyDef.publicKey())) {
return idToken;
}
}
return null;
}
public static OpenIdToken verify(String compactJws, Iterable<PublicKeyDef> publicKeyDefs) {
final JsonWebSignature jws = JsonWebSignature.parse(compactJws);
if (jws != null) {
return verify(jws, publicKeyDefs);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/PrivateKeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.security.PrivateKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.RSAPrivateKey;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
public abstract class PrivateKeyDef extends KeyDef {
public abstract PrivateKey privateKey();
private static Form<PrivateKeyDef> privateKeyForm;
public static PrivateKeyDef from(PrivateKey key) {
if (key instanceof ECPrivateKey) {
return EcPrivateKeyDef.from((ECPrivateKey) key);
} else if (key instanceof RSAPrivateKey) {
return RsaPrivateKeyDef.from((RSAPrivateKey) key);
}
throw new IllegalArgumentException(key.toString());
}
@Kind
public static Form<PrivateKeyDef> privateKeyForm() {
if (privateKeyForm == null) {
privateKeyForm = new PrivateKeyForm();
}
return privateKeyForm;
}
}
final class PrivateKeyForm extends Form<PrivateKeyDef> {
@Override
public Class<?> type() {
return PrivateKeyDef.class;
}
@Override
public Item mold(PrivateKeyDef keyDef) {
return keyDef.toValue();
}
@Override
public PrivateKeyDef cast(Item item) {
PrivateKeyDef keyDef = EcPrivateKeyDef.form().cast(item);
if (keyDef != null) {
return keyDef;
}
keyDef = RsaPrivateKeyDef.form().cast(item);
if (keyDef != null) {
return keyDef;
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/PublicKeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.security.PublicKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
public abstract class PublicKeyDef extends KeyDef {
public abstract PublicKey publicKey();
private static Form<PublicKeyDef> publicKeyForm;
public static PublicKeyDef from(PublicKey key) {
if (key instanceof ECPublicKey) {
return EcPublicKeyDef.from((ECPublicKey) key);
} else if (key instanceof RSAPublicKey) {
return RsaPublicKeyDef.from((RSAPublicKey) key);
}
throw new IllegalArgumentException(key.toString());
}
@Kind
public static Form<PublicKeyDef> publicKeyForm() {
if (publicKeyForm == null) {
publicKeyForm = new PublicKeyForm();
}
return publicKeyForm;
}
}
final class PublicKeyForm extends Form<PublicKeyDef> {
@Override
public Class<?> type() {
return PublicKeyDef.class;
}
@Override
public Item mold(PublicKeyDef keyDef) {
return keyDef.toValue();
}
@Override
public PublicKeyDef cast(Item item) {
PublicKeyDef keyDef = EcPublicKeyDef.form().cast(item);
if (keyDef != null) {
return keyDef;
}
keyDef = RsaPublicKeyDef.form().cast(item);
if (keyDef != null) {
return keyDef;
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/ReconSignature.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAKey;
import swim.codec.Output;
import swim.recon.Recon;
import swim.structure.Attr;
import swim.structure.Data;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Slot;
import swim.structure.Text;
import swim.structure.Value;
public class ReconSignature {
protected final Value payload;
protected final Value protectedHeader;
protected final Value signatureHeader;
public ReconSignature(Value payload, Value protectedHeader, Value signatureHeader) {
this.payload = payload;
this.protectedHeader = protectedHeader;
this.signatureHeader = signatureHeader;
}
public final Value payload() {
return this.payload;
}
public final Value protectedHeader() {
return this.protectedHeader;
}
public final Value signatureHeader() {
return this.signatureHeader;
}
public Data hash() {
final Value hash = this.signatureHeader.get("hash");
if (hash instanceof Data) {
return (Data) hash;
}
return null;
}
protected Data signingInput() {
final Output<Data> output = Data.output();
Recon.structureWriter().writeValue(this.payload, output);
Recon.structureWriter().writeAttr(Text.from("protected"), this.protectedHeader, output);
return output.bind();
}
public boolean verifySignature(PublicKey publicKey) {
final String algorithm = algorithm(publicKey);
try {
return verifyRsaSignature(Signature.getInstance(algorithm), publicKey);
} catch (GeneralSecurityException cause) {
// TODO: return reason
}
return false;
}
public boolean verifyRsaSignature(Signature signature, PublicKey publicKey) {
try {
signature.initVerify(publicKey);
signature.update(signingInput().asByteBuffer());
final Data signatureData = hash();
return signature.verify(signatureData.asByteArray(), 0, signatureData.size());
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public Value toValue() {
Value value = this.payload;
if (this.protectedHeader.isDefined()) {
value = value.concat(Attr.of("protected", this.protectedHeader));
}
value = value.concat(Attr.of("signature", this.signatureHeader));
return value;
}
public static ReconSignature from(Value value) {
if (value instanceof Record) {
final Record payload = (Record) value;
final Item signatureHeader = payload.get(payload.length() - 1);
if ("signature".equals(signatureHeader.key().stringValue())) {
payload.remove(payload.length() - 1);
Item protectedHeader = payload.get(payload.length() - 1);
if ("protected".equals(protectedHeader.key().stringValue())) {
payload.remove(payload.length() - 1);
} else {
protectedHeader = Value.absent();
}
return new ReconSignature(payload, protectedHeader.toValue(), signatureHeader.toValue());
}
}
return null;
}
public static ReconSignature parse(String recon) {
return from(Recon.parse(recon));
}
public static ReconSignature signRsa(Signature signature, PrivateKey privateKey,
Value payload, Value protectedHeader,
Value unprotectedHeader) {
final Output<Data> output = Data.output();
Recon.structureWriter().writeValue(payload, output);
Recon.structureWriter().writeAttr(Text.from("protected"), protectedHeader, output);
final Data signingInput = output.bind();
try {
signature.initSign(privateKey);
signature.update(signingInput.asByteBuffer());
final Data hash = Data.wrap(signature.sign());
final Value signatureHeader;
if (unprotectedHeader.isDefined()) {
signatureHeader = unprotectedHeader.concat(Slot.of("hash", hash));
} else {
signatureHeader = Record.of(Slot.of("hash", hash));
}
return new ReconSignature(payload, protectedHeader, signatureHeader);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static ReconSignature signRsa(PrivateKey privateKey, Value payload,
Value protectedHeader, Value unprotectedHeader) {
final Signature signature;
final String algorithm = algorithm(privateKey);
try {
signature = Signature.getInstance(algorithm);
return signRsa(signature, privateKey, payload, protectedHeader, unprotectedHeader);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
public static ReconSignature sign(PrivateKey privateKey, Value payload,
Value protectedHeader, Value unprotectedHeader) {
if (privateKey instanceof RSAKey) {
return signRsa(privateKey, payload, protectedHeader, unprotectedHeader);
} else {
throw new IllegalArgumentException("unsupported signing key type");
}
}
private static String rsaAlgorithm(RSAKey key) {
return "SHA256withRSA";
}
private static String algorithm(Key key) {
if (key instanceof RSAKey) {
return rsaAlgorithm((RSAKey) key);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/RsaKeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.Key;
import swim.structure.Value;
public interface RsaKeyDef {
BigInteger modulus();
Key key();
Value toValue();
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/RsaPrimeDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.spec.RSAOtherPrimeInfo;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class RsaPrimeDef {
protected final BigInteger factor;
protected final BigInteger exponent;
protected final BigInteger coefficient;
public RsaPrimeDef(BigInteger factor, BigInteger exponent, BigInteger coefficient) {
this.factor = factor;
this.exponent = exponent;
this.coefficient = coefficient;
}
public RsaPrimeDef(BigInteger factor, BigInteger exponent) {
this(factor, exponent, null);
}
public final BigInteger factor() {
return this.factor;
}
public final BigInteger exponent() {
return this.exponent;
}
public final BigInteger coefficient() {
return this.coefficient;
}
public final RSAOtherPrimeInfo toRSAOtherPrimeInfo() {
return new RSAOtherPrimeInfo(this.factor, this.exponent, this.coefficient);
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof RsaPrimeDef) {
final RsaPrimeDef that = (RsaPrimeDef) other;
return this.factor.equals(that.factor) && this.exponent.equals(that.exponent)
&& (this.coefficient == null ? that.coefficient == null : this.coefficient.equals(that.coefficient));
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(RsaPrimeDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
this.factor.hashCode()), this.exponent.hashCode()), Murmur3.hash(this.coefficient)));
}
private static int hashSeed;
private static Form<RsaPrimeDef> form;
public static RsaPrimeDef from(RSAOtherPrimeInfo info) {
return new RsaPrimeDef(info.getPrime(), info.getExponent(), info.getCrtCoefficient());
}
@Kind
public static Form<RsaPrimeDef> form() {
if (form == null) {
form = new RsaPrimeForm();
}
return form;
}
}
final class RsaPrimeForm extends Form<RsaPrimeDef> {
@Override
public String tag() {
return "prime";
}
@Override
public Class<?> type() {
return RsaPrimeDef.class;
}
@Override
public Item mold(RsaPrimeDef primeDef) {
final Record header = Record.create(primeDef.coefficient != null ? 3 : 2)
.slot("factor", Num.from(primeDef.factor))
.slot("exponent", Num.from(primeDef.exponent));
if (primeDef.coefficient != null) {
header.slot("coefficient", Num.from(primeDef.coefficient));
}
return Record.create(1).attr(tag(), header);
}
@Override
public RsaPrimeDef cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final BigInteger factor = header.get("factor").integerValue(null);
final BigInteger exponent = header.get("exponent").integerValue(null);
final BigInteger coefficient = header.get("coefficient").integerValue(null);
if (factor != null && exponent != null) {
return new RsaPrimeDef(factor, exponent, coefficient);
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/RsaPrivateKeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.interfaces.RSAMultiPrimePrivateCrtKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.RSAMultiPrimePrivateCrtKeySpec;
import java.security.spec.RSAOtherPrimeInfo;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import swim.collections.FingerTrieSeq;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Builder;
import swim.util.Murmur3;
public class RsaPrivateKeyDef extends PrivateKeyDef implements RsaKeyDef {
protected final BigInteger modulus;
protected final BigInteger publicExponent;
protected final BigInteger privateExponent;
protected final FingerTrieSeq<RsaPrimeDef> primeDefs;
protected RSAPrivateKey privateKey;
RsaPrivateKeyDef(BigInteger modulus, BigInteger publicExponent, BigInteger privateExponent,
FingerTrieSeq<RsaPrimeDef> primeDefs, RSAPrivateKey privateKey) {
this.modulus = modulus;
this.publicExponent = publicExponent;
this.privateExponent = privateExponent;
this.primeDefs = primeDefs;
this.privateKey = privateKey;
}
public RsaPrivateKeyDef(BigInteger modulus, BigInteger publicExponent, BigInteger privateExponent,
FingerTrieSeq<RsaPrimeDef> primeDefs) {
this(modulus, publicExponent, privateExponent, primeDefs, null);
}
public RsaPrivateKeyDef(BigInteger modulus, BigInteger publicExponent, BigInteger privateExponent,
RsaPrimeDef... primeDefs) {
this(modulus, publicExponent, privateExponent, FingerTrieSeq.of(primeDefs));
}
RsaPrivateKeyDef(BigInteger modulus, BigInteger privateExponent, RSAPrivateKey privateKey) {
this(modulus, null, privateExponent, FingerTrieSeq.<RsaPrimeDef>empty(), privateKey);
}
public RsaPrivateKeyDef(BigInteger modulus, BigInteger privateExponent) {
this(modulus, null, privateExponent, FingerTrieSeq.<RsaPrimeDef>empty());
}
@Override
public final BigInteger modulus() {
return this.modulus;
}
public final BigInteger publicExponent() {
return this.publicExponent;
}
public final BigInteger privateExponent() {
return this.privateExponent;
}
public final FingerTrieSeq<RsaPrimeDef> primeDefs() {
return this.primeDefs;
}
@Override
public RSAPrivateKey privateKey() {
RSAPrivateKey privateKey = this.privateKey;
if (privateKey == null) {
try {
final int primeCount = this.primeDefs.size();
final RSAPrivateKeySpec keySpec;
if (primeCount < 2 || this.publicExponent == null) {
keySpec = new RSAPrivateKeySpec(this.modulus, this.privateExponent);
} else {
final RsaPrimeDef p = this.primeDefs.get(0);
final RsaPrimeDef q = this.primeDefs.get(1);
if (primeCount == 2) {
keySpec = new RSAPrivateCrtKeySpec(this.modulus, this.publicExponent, this.privateExponent,
p.factor, q.factor, p.exponent, q.exponent, q.coefficient);
} else {
final RSAOtherPrimeInfo[] otherPrimes = new RSAOtherPrimeInfo[primeCount - 2];
for (int i = 2; i < primeCount; i += 1) {
otherPrimes[i - 2] = this.primeDefs.get(i).toRSAOtherPrimeInfo();
}
keySpec = new RSAMultiPrimePrivateCrtKeySpec(this.modulus, this.publicExponent, this.privateExponent,
p.factor, q.factor, p.exponent, q.exponent, q.coefficient,
otherPrimes);
}
}
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
this.privateKey = privateKey;
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
return privateKey;
}
@Override
public Key key() {
return privateKey();
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof RsaPrivateKeyDef) {
final RsaPrivateKeyDef that = (RsaPrivateKeyDef) other;
return this.modulus.equals(that.modulus)
&& (this.publicExponent == null ? that.publicExponent == null : this.publicExponent.equals(that.publicExponent))
&& this.privateExponent.equals(that.privateExponent)
&& this.primeDefs.equals(that.primeDefs);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(RsaPrivateKeyDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.modulus.hashCode()), this.privateExponent.hashCode()));
}
private static int hashSeed;
private static Form<RsaPrivateKeyDef> form;
public static RsaPrivateKeyDef from(RSAPrivateKey key) {
if (key instanceof RSAMultiPrimePrivateCrtKey) {
return from((RSAMultiPrimePrivateCrtKey) key);
} else if (key instanceof RSAPrivateCrtKey) {
return from((RSAPrivateCrtKey) key);
} else {
return new RsaPrivateKeyDef(key.getModulus(), key.getPrivateExponent(), key);
}
}
private static RsaPrivateKeyDef from(RSAMultiPrimePrivateCrtKey key) {
FingerTrieSeq<RsaPrimeDef> primeDefs = FingerTrieSeq.empty();
primeDefs = primeDefs.appended(new RsaPrimeDef(key.getPrimeP(), key.getPrimeExponentP()));
primeDefs = primeDefs.appended(new RsaPrimeDef(key.getPrimeQ(), key.getPrimeExponentQ(), key.getCrtCoefficient()));
final RSAOtherPrimeInfo[] otherPrimes = key.getOtherPrimeInfo();
for (int i = 0, n = otherPrimes.length; i < n; i += 1) {
primeDefs = primeDefs.appended(RsaPrimeDef.from(otherPrimes[i]));
}
return new RsaPrivateKeyDef(key.getModulus(), key.getPublicExponent(), key.getPrivateExponent(), primeDefs, key);
}
private static RsaPrivateKeyDef from(RSAPrivateCrtKey key) {
FingerTrieSeq<RsaPrimeDef> primeDefs = FingerTrieSeq.empty();
primeDefs = primeDefs.appended(new RsaPrimeDef(key.getPrimeP(), key.getPrimeExponentP()));
primeDefs = primeDefs.appended(new RsaPrimeDef(key.getPrimeQ(), key.getPrimeExponentQ(), key.getCrtCoefficient()));
return new RsaPrivateKeyDef(key.getModulus(), key.getPublicExponent(), key.getPrivateExponent(), primeDefs, key);
}
@Kind
public static Form<RsaPrivateKeyDef> form() {
if (form == null) {
form = new RsaPrivateKeyForm();
}
return form;
}
}
final class RsaPrivateKeyForm extends Form<RsaPrivateKeyDef> {
@Override
public String tag() {
return "RSAPrivateKey";
}
@Override
public Class<?> type() {
return RsaPrivateKeyDef.class;
}
@Override
public Item mold(RsaPrivateKeyDef keyDef) {
final FingerTrieSeq<RsaPrimeDef> primeDefs = keyDef.primeDefs;
final int n = primeDefs.size();
final Record record = Record.create((keyDef.publicExponent != null ? 4 : 3) + n)
.attr(tag())
.slot("modulus", Num.from(keyDef.modulus));
if (keyDef.publicExponent != null) {
record.slot("publicExponent", Num.from(keyDef.publicExponent));
}
record.slot("privateExponent", Num.from(keyDef.privateExponent));
for (int i = 0; i < n; i += 1) {
record.add(primeDefs.get(i).toValue());
}
return record;
}
@Override
public RsaPrivateKeyDef cast(Item item) {
final Value value = item.toValue();
if (value.getAttr(tag()).isDefined()) {
BigInteger modulus = null;
BigInteger publicExponent = null;
BigInteger privateExponent = null;
Builder<RsaPrimeDef, FingerTrieSeq<RsaPrimeDef>> primeDefs = null;
for (int i = 0, n = value.length(); i < n; i += 1) {
final Item member = value.getItem(i);
final String name = member.key().stringValue();
if ("modulus".equals(name)) {
modulus = member.toValue().integerValue(null);
} else if ("publicExponent".equals(name)) {
publicExponent = member.toValue().integerValue(null);
} else if ("privateExponent".equals(name)) {
privateExponent = member.toValue().integerValue(null);
} else {
final RsaPrimeDef primeDef = RsaPrimeDef.form().cast(member.toValue());
if (primeDef != null) {
if (primeDefs == null) {
primeDefs = FingerTrieSeq.builder();
}
primeDefs.add(primeDef);
}
}
}
if (modulus != null && privateExponent != null) {
return new RsaPrivateKeyDef(modulus, publicExponent, privateExponent,
primeDefs != null ? primeDefs.bind() : FingerTrieSeq.<RsaPrimeDef>empty());
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/RsaPublicKeyDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.security;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class RsaPublicKeyDef extends PublicKeyDef implements RsaKeyDef {
protected final BigInteger modulus;
protected final BigInteger publicExponent;
protected RSAPublicKey publicKey;
RsaPublicKeyDef(BigInteger modulus, BigInteger publicExponent, RSAPublicKey publicKey) {
this.modulus = modulus;
this.publicExponent = publicExponent;
this.publicKey = publicKey;
}
public RsaPublicKeyDef(BigInteger modulus, BigInteger publicExponent) {
this(modulus, publicExponent, null);
}
@Override
public final BigInteger modulus() {
return this.modulus;
}
public final BigInteger publicExponent() {
return this.publicExponent;
}
@Override
public RSAPublicKey publicKey() {
RSAPublicKey publicKey = this.publicKey;
if (publicKey == null) {
try {
final RSAPublicKeySpec keySpec = new RSAPublicKeySpec(this.modulus, this.publicExponent);
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
this.publicKey = publicKey;
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
return publicKey;
}
@Override
public Key key() {
return publicKey();
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof RsaPublicKeyDef) {
final RsaPublicKeyDef that = (RsaPublicKeyDef) other;
return this.modulus.equals(that.modulus) && this.publicExponent.equals(that.publicExponent);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(RsaPublicKeyDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.modulus.hashCode()), this.publicExponent.hashCode()));
}
private static int hashSeed;
private static Form<RsaPublicKeyDef> form;
public static RsaPublicKeyDef from(RSAPublicKey key) {
return new RsaPublicKeyDef(key.getModulus(), key.getPublicExponent(), key);
}
@Kind
public static Form<RsaPublicKeyDef> form() {
if (form == null) {
form = new RsaPublicKeyForm();
}
return form;
}
}
final class RsaPublicKeyForm extends Form<RsaPublicKeyDef> {
@Override
public String tag() {
return "RSAPublicKey";
}
@Override
public Class<?> type() {
return RsaPublicKeyDef.class;
}
@Override
public Item mold(RsaPublicKeyDef keyDef) {
return Record.create(3)
.attr(tag())
.slot("modulus", Num.from(keyDef.modulus))
.slot("publicExponent", Num.from(keyDef.publicExponent));
}
@Override
public RsaPublicKeyDef cast(Item item) {
final Value value = item.toValue();
if (value.getAttr(tag()).isDefined()) {
final BigInteger modulus = value.get("modulus").integerValue(null);
final BigInteger publicExponent = value.get("publicExponent").integerValue(null);
if (modulus != null && publicExponent != null) {
return new RsaPublicKeyDef(modulus, publicExponent);
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-security/3.10.0/swim | java-sources/ai/swim/swim-security/3.10.0/swim/security/package-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Cryptographic security model.
*/
package swim.security;
|
0 | java-sources/ai/swim/swim-server | java-sources/ai/swim/swim-server/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Swim server loader.
*/
module swim.server {
requires transitive swim.kernel;
requires transitive swim.store.mem;
requires transitive swim.remote;
requires transitive swim.service;
requires transitive swim.service.web;
requires transitive swim.auth;
requires transitive swim.fabric;
requires transitive swim.java;
exports swim.server;
}
|
0 | java-sources/ai/swim/swim-server/3.10.0/swim | java-sources/ai/swim/swim-server/3.10.0/swim/server/ServerLoader.java | // Copyright 2015-2019 SWIM.AI 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 swim.server;
import java.io.IOException;
import swim.api.service.ServiceDef;
import swim.api.service.ServiceFactory;
import swim.api.space.SpaceDef;
import swim.auth.AuthenticatorKernel;
import swim.fabric.FabricKernel;
import swim.java.JavaKernel;
import swim.kernel.BootKernel;
import swim.kernel.Kernel;
import swim.kernel.KernelException;
import swim.kernel.KernelLoader;
import swim.remote.RemoteKernel;
import swim.service.ServiceKernel;
import swim.service.web.WebServiceKernel;
import swim.store.mem.MemStoreKernel;
import swim.structure.Item;
import swim.structure.Value;
public final class ServerLoader {
private ServerLoader() {
// static
}
public static Kernel loadServer() {
return loadServer(KernelLoader.class.getClassLoader());
}
public static Kernel loadServer(ClassLoader classLoader) {
try {
Value kernelConfig = KernelLoader.loadConfig(classLoader);
if (kernelConfig == null) {
kernelConfig = KernelLoader.loadConfigResource(classLoader, "server.recon");
}
if (kernelConfig == null) {
kernelConfig = Value.absent();
}
final Kernel kernel = loadServerStack(classLoader, kernelConfig);
loadSpaces(kernel, kernelConfig, classLoader);
loadServices(kernel, kernelConfig, classLoader);
return kernel;
} catch (IOException cause) {
throw new KernelException(cause);
}
}
public static Kernel loadServerStack() {
return loadServerStack(KernelLoader.class.getClassLoader());
}
public static Kernel loadServerStack(ClassLoader classLoader) {
return injectServerStack(classLoader, null);
}
public static Kernel loadServerStack(ClassLoader classLoader, Value kernelConfig) {
Kernel kernel = KernelLoader.loadKernelStack(classLoader, kernelConfig);
kernel = injectServerStack(classLoader, kernel);
return kernel;
}
public static Kernel injectServerStack(ClassLoader classLoader, Kernel kernel) {
if (kernel == null) {
kernel = new BootKernel();
} else if (kernel.unwrapKernel(BootKernel.class) == null) {
kernel = kernel.injectKernel(new BootKernel());
}
if (kernel.unwrapKernel(MemStoreKernel.class) == null) {
kernel = kernel.injectKernel(new MemStoreKernel());
}
if (kernel.unwrapKernel(RemoteKernel.class) == null) {
kernel = kernel.injectKernel(new RemoteKernel());
}
if (kernel.unwrapKernel(ServiceKernel.class) == null) {
kernel = kernel.injectKernel(new ServiceKernel());
}
if (kernel.unwrapKernel(WebServiceKernel.class) == null) {
kernel = kernel.injectKernel(new WebServiceKernel());
}
if (kernel.unwrapKernel(AuthenticatorKernel.class) == null) {
kernel = kernel.injectKernel(new AuthenticatorKernel());
}
if (kernel.unwrapKernel(FabricKernel.class) == null) {
kernel = kernel.injectKernel(new FabricKernel());
}
if (kernel.unwrapKernel(JavaKernel.class) == null) {
kernel = kernel.injectKernel(new JavaKernel());
}
return kernel;
}
public static void loadSpaces(Kernel kernel, Value kernelConfig, ClassLoader classLoader) {
for (int i = 0, n = kernelConfig.length(); i < n; i += 1) {
final Item item = kernelConfig.getItem(i);
final SpaceDef spaceDef = kernel.defineSpace(item);
if (spaceDef != null) {
kernel.openSpace(spaceDef);
}
}
}
public static void loadServices(Kernel kernel, Value kernelConfig, ClassLoader classLoader) {
for (int i = 0, n = kernelConfig.length(); i < n; i += 1) {
final Item item = kernelConfig.getItem(i);
final ServiceDef serviceDef = kernel.defineService(item);
if (serviceDef != null) {
final ServiceFactory<?> serviceFactory = kernel.createServiceFactory(serviceDef, classLoader);
kernel.openService(serviceDef.serviceName(), serviceFactory);
}
}
}
}
|
0 | java-sources/ai/swim/swim-server/3.10.0/swim | java-sources/ai/swim/swim-server/3.10.0/swim/server/package-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Swim server loader.
*/
package swim.server;
|
0 | java-sources/ai/swim/swim-service | java-sources/ai/swim/swim-service/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Swim network service runtime.
*/
module swim.service {
requires transitive swim.kernel;
exports swim.service;
provides swim.kernel.Kernel with swim.service.ServiceKernel;
}
|
0 | java-sources/ai/swim/swim-service/3.10.0/swim | java-sources/ai/swim/swim-service/3.10.0/swim/service/ServiceKernel.java | // Copyright 2015-2019 SWIM.AI 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 swim.service;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.SwimContext;
import swim.api.service.Service;
import swim.api.service.ServiceContext;
import swim.api.service.ServiceFactory;
import swim.collections.HashTrieMap;
import swim.kernel.KernelContext;
import swim.kernel.KernelProxy;
import swim.structure.Value;
public class ServiceKernel extends KernelProxy {
final double kernelPriority;
volatile HashTrieMap<String, Service> services;
public ServiceKernel(double kernelPriority) {
this.kernelPriority = kernelPriority;
this.services = HashTrieMap.empty();
}
public ServiceKernel() {
this(KERNEL_PRIORITY);
}
@Override
public final double kernelPriority() {
return this.kernelPriority;
}
protected ServiceContext createServiceContext(String serviceName) {
final KernelContext kernel = kernelWrapper().unwrapKernel(KernelContext.class);
return new ServicePort(serviceName, kernel);
}
protected <S extends Service> S createService(ServiceContext serviceContext, ServiceFactory<S> serviceFactory) {
try {
SwimContext.setServiceContext(serviceContext);
return serviceFactory.createService(serviceContext);
} finally {
SwimContext.clear();
}
}
@SuppressWarnings("unchecked")
@Override
public <S extends Service> S openService(String serviceName, ServiceFactory<S> serviceFactory) {
ServiceContext serviceContext = null;
S service = null;
do {
final HashTrieMap<String, Service> oldServices = this.services;
final Service oldService = oldServices.get(serviceName);
if (oldService == null) {
if (service == null) {
serviceContext = createServiceContext(serviceName);
service = createService(serviceContext, serviceFactory);
service = (S) kernelWrapper().unwrapKernel(KernelContext.class).injectService(service);
if (serviceContext instanceof ServicePort) {
((ServicePort) serviceContext).setService(service);
}
}
final HashTrieMap<String, Service> newServices = oldServices.updated(serviceName, service);
if (SERVICES.compareAndSet(this, oldServices, newServices)) {
if (serviceContext instanceof ServicePort && isStarted()) {
((ServicePort) serviceContext).start();
}
break;
}
} else {
serviceContext = null;
service = (S) oldService;
break;
}
} while (true);
return service;
}
@Override
public Service getService(String serviceName) {
return this.services.get(serviceName);
}
@Override
public void didStart() {
for (Service service : this.services.values()) {
final ServiceContext serviceContext = service.serviceContext();
if (serviceContext instanceof ServicePort) {
((ServicePort) serviceContext).start();
}
}
}
@Override
public void willStop() {
for (Service service : this.services.values()) {
final ServiceContext serviceContext = service.serviceContext();
if (serviceContext instanceof ServicePort) {
((ServicePort) serviceContext).stop();
}
}
}
private static final double KERNEL_PRIORITY = 0.5;
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<ServiceKernel, HashTrieMap<String, Service>> SERVICES =
AtomicReferenceFieldUpdater.newUpdater(ServiceKernel.class, (Class<HashTrieMap<String, Service>>) (Class<?>) HashTrieMap.class, "services");
public static ServiceKernel fromValue(Value moduleConfig) {
final Value header = moduleConfig.getAttr("kernel");
final String kernelClassName = header.get("class").stringValue(null);
if (kernelClassName == null || ServiceKernel.class.getName().equals(kernelClassName)) {
final double kernelPriority = header.get("priority").doubleValue(KERNEL_PRIORITY);
return new ServiceKernel(kernelPriority);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-service/3.10.0/swim | java-sources/ai/swim/swim-service/3.10.0/swim/service/ServicePort.java | // Copyright 2015-2019 SWIM.AI 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 swim.service;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import swim.api.policy.Policy;
import swim.api.service.Service;
import swim.api.service.ServiceContext;
import swim.concurrent.MainStage;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.io.IpService;
import swim.io.IpServiceRef;
import swim.io.IpSettings;
import swim.io.IpSocket;
import swim.io.IpSocketRef;
import swim.kernel.KernelContext;
import swim.util.Log;
public class ServicePort implements ServiceContext {
protected final String serviceName;
protected final KernelContext kernel;
protected Service service;
protected volatile int status;
protected Log log;
protected Policy policy;
protected Stage stage;
public ServicePort(String serviceName, KernelContext kernel) {
this.serviceName = serviceName;
this.kernel = kernel;
}
public final String serviceName() {
return this.serviceName;
}
@Override
public Schedule schedule() {
return this.stage;
}
@Override
public final Stage stage() {
return this.stage;
}
public final KernelContext kernel() {
return this.kernel;
}
public final Service service() {
return this.service;
}
public void setService(Service service) {
this.service = service;
}
@Override
public IpSettings ipSettings() {
return this.kernel.ipSettings();
}
@Override
public IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
return this.kernel.bindTcp(localAddress, service, ipSettings);
}
@Override
public IpServiceRef bindTls(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
return this.kernel.bindTls(localAddress, service, ipSettings);
}
@Override
public IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
return this.kernel.connectTcp(remoteAddress, socket, ipSettings);
}
@Override
public IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
return this.kernel.connectTls(remoteAddress, socket, ipSettings);
}
protected Log openLog() {
return this.kernel.openServiceLog(this.serviceName);
}
protected void closeLog() {
this.log = null;
}
protected Policy openPolicy() {
return this.kernel.openServicePolicy(this.serviceName);
}
protected void closePolicy() {
this.policy = null;
}
protected Stage openStage() {
return this.kernel.openServiceStage(this.serviceName);
}
protected void closeStage() {
final Stage stage = this.stage;
if (stage instanceof MainStage) {
((MainStage) stage).stop();
}
this.stage = null;
}
public void start() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | STARTED;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & STARTED) == 0) {
willStart();
didStart();
}
}
public void stop() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~STARTED;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & STARTED) != 0) {
willStop();
didStop();
}
}
@Override
public void close() {
// TODO
}
protected void willStart() {
this.log = openLog();
this.policy = openPolicy();
this.stage = openStage();
this.service.willStart();
}
protected void didStart() {
this.service.didStart();
}
protected void willStop() {
this.service.willStop();
}
protected void didStop() {
this.service.didStop();
closeStage();
closePolicy();
closeLog();
}
@Override
public void trace(Object message) {
final Log log = this.log;
if (log != null) {
log.trace(message);
} else {
this.kernel.trace(message);
}
}
@Override
public void debug(Object message) {
final Log log = this.log;
if (log != null) {
log.debug(message);
} else {
this.kernel.debug(message);
}
}
@Override
public void info(Object message) {
final Log log = this.log;
if (log != null) {
log.info(message);
} else {
this.kernel.info(message);
}
}
@Override
public void warn(Object message) {
final Log log = this.log;
if (log != null) {
log.warn(message);
} else {
this.kernel.warn(message);
}
}
@Override
public void error(Object message) {
final Log log = this.log;
if (log != null) {
log.error(message);
} else {
this.kernel.error(message);
}
}
protected static final int STARTED = 0x01;
protected static final AtomicIntegerFieldUpdater<ServicePort> STATUS =
AtomicIntegerFieldUpdater.newUpdater(ServicePort.class, "status");
}
|
0 | java-sources/ai/swim/swim-service/3.10.0/swim | java-sources/ai/swim/swim-service/3.10.0/swim/service/package-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Swim network service runtime.
*/
package swim.service;
|
0 | java-sources/ai/swim/swim-service-web | java-sources/ai/swim/swim-service-web/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Web service runtime.
*/
module swim.service.web {
requires transitive swim.web;
requires transitive swim.service;
requires transitive swim.remote;
exports swim.service.web;
provides swim.kernel.Kernel with swim.service.web.WebServiceKernel;
}
|
0 | java-sources/ai/swim/swim-service-web/3.10.0/swim/service | java-sources/ai/swim/swim-service-web/3.10.0/swim/service/web/HttpLaneResponder.java | // Copyright 2015-2019 SWIM.AI 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 swim.service.web;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.api.auth.Identity;
import swim.codec.Decoder;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpSocket;
import swim.io.http.HttpResponder;
import swim.io.http.HttpResponderContext;
import swim.runtime.CellContext;
import swim.runtime.HttpBinding;
import swim.runtime.HttpContext;
import swim.runtime.LinkContext;
import swim.structure.Value;
import swim.uri.Uri;
public class HttpLaneResponder implements HttpBinding, HttpResponder<Object> {
final Uri meshUri;
final Uri hostUri;
final Uri nodeUri;
final Uri laneUri;
final HttpRequest<?> request;
HttpContext linkContext;
HttpResponderContext httpResponderContext;
HttpLaneResponder(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri, HttpRequest<?> request) {
this.meshUri = meshUri;
this.hostUri = hostUri;
this.nodeUri = nodeUri;
this.laneUri = laneUri;
this.request = request;
}
@Override
public HttpBinding linkWrapper() {
return this;
}
@Override
public HttpContext linkContext() {
return this.linkContext;
}
@Override
public void setLinkContext(LinkContext linkContext) {
this.linkContext = (HttpContext) linkContext;
}
@Override
public CellContext cellContext() {
return null;
}
@Override
public void setCellContext(CellContext cellContext) {
// nop
}
@Override
public HttpResponderContext httpResponderContext() {
return this.httpResponderContext;
}
@Override
public void setHttpResponderContext(HttpResponderContext httpResponderContext) {
this.httpResponderContext = httpResponderContext;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapLink(Class<T> linkClass) {
if (linkClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.linkContext.unwrapLink(linkClass);
}
}
@Override
public Uri meshUri() {
return this.meshUri;
}
@Override
public Uri hostUri() {
return this.hostUri;
}
@Override
public Uri nodeUri() {
return this.nodeUri;
}
@Override
public Uri laneUri() {
return this.laneUri;
}
@Override
public Value linkKey() {
return this.linkContext.linkKey();
}
@Override
public Uri requestUri() {
return this.request.uri();
}
@Override
public HttpRequest<?> request() {
return this.request;
}
@Override
public boolean isConnectedDown() {
return this.httpResponderContext.isConnected();
}
@Override
public boolean isRemoteDown() {
return true;
}
@Override
public boolean isSecureDown() {
return this.httpResponderContext.isSecure();
}
@Override
public String securityProtocolDown() {
return this.httpResponderContext.securityProtocol();
}
@Override
public String cipherSuiteDown() {
return this.httpResponderContext.cipherSuite();
}
@Override
public InetSocketAddress localAddressDown() {
return this.httpResponderContext.localAddress();
}
@Override
public Identity localIdentityDown() {
return null; // TODO
}
@Override
public Principal localPrincipalDown() {
return this.httpResponderContext.localPrincipal();
}
@Override
public Collection<Certificate> localCertificatesDown() {
return this.httpResponderContext.localCertificates();
}
@Override
public InetSocketAddress remoteAddressDown() {
return this.httpResponderContext.remoteAddress();
}
@Override
public Identity remoteIdentityDown() {
return null; // TODO
}
@Override
public Principal remotePrincipalDown() {
return this.httpResponderContext.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificatesDown() {
return this.httpResponderContext.remoteCertificates();
}
@Override
public HttpRequest<?> doRequest() {
return this.request;
}
@SuppressWarnings("unchecked")
@Override
public Decoder<Object> contentDecoder(HttpRequest<?> request) {
return this.linkContext.decodeRequest(request);
}
@Override
public void willRequest(HttpRequest<?> request) {
this.linkContext.willRequest(request);
}
@Override
public void didRequest(HttpRequest<Object> request) {
this.linkContext.didRequest(request);
}
@Override
public void doRespond(HttpRequest<Object> request) {
this.linkContext.doRespond(request);
}
@Override
public void writeResponse(HttpResponse<?> response) {
this.httpResponderContext.writeResponse(response);
}
@Override
public void willRespond(HttpResponse<?> response) {
this.linkContext.willRespond(response);
}
@Override
public void didRespond(HttpResponse<?> response) {
this.linkContext.didRespond(response);
}
@Override
public void willBecome(IpSocket socket) {
// nop
}
@Override
public void didBecome(IpSocket socket) {
// nop
}
@Override
public void didTimeout() {
// nop
}
@Override
public void didConnect() {
// nop
}
@Override
public void didDisconnect() {
// nop
}
@Override
public void reopen() {
// nop
}
@Override
public void openDown() {
// nop
}
@Override
public void closeDown() {
this.httpResponderContext.close();
}
@Override
public void didCloseUp() {
// nop
}
@Override
public void didFail(Throwable error) {
this.linkContext.closeUp();
closeDown();
}
@Override
public void traceDown(Object message) {
// nop
}
@Override
public void debugDown(Object message) {
// nop
}
@Override
public void infoDown(Object message) {
// nop
}
@Override
public void warnDown(Object message) {
// nop
}
@Override
public void errorDown(Object message) {
// nop
}
}
|
0 | java-sources/ai/swim/swim-service-web/3.10.0/swim/service | java-sources/ai/swim/swim-service-web/3.10.0/swim/service/web/WebServer.java | // Copyright 2015-2019 SWIM.AI 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 swim.service.web;
import java.io.File;
import swim.api.policy.PlanePolicy;
import swim.api.policy.PolicyDirective;
import swim.api.service.ServiceException;
import swim.api.space.Space;
import swim.http.HttpBody;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.http.HttpStatus;
import swim.io.http.HttpResponder;
import swim.io.http.StaticHttpResponder;
import swim.io.warp.AbstractWarpServer;
import swim.kernel.KernelContext;
import swim.remote.RemoteHost;
import swim.runtime.EdgeBinding;
import swim.runtime.EdgeContext;
import swim.runtime.MeshBinding;
import swim.runtime.PartBinding;
import swim.uri.Uri;
import swim.uri.UriAuthority;
import swim.uri.UriHost;
import swim.uri.UriPath;
import swim.uri.UriPort;
import swim.uri.UriScheme;
import swim.web.WebRequest;
import swim.web.WebResponse;
import swim.web.WebRoute;
import swim.web.WebServerRequest;
import swim.web.route.DirectoryRoute;
import swim.web.route.RejectRoute;
import swim.web.route.ResourceDirectoryRoute;
import swim.ws.WsRequest;
import swim.ws.WsResponse;
public class WebServer extends AbstractWarpServer {
final KernelContext kernel;
final WebServiceDef serviceDef;
WebRoute router;
public WebServer(KernelContext kernel, WebServiceDef serviceDef) {
this.kernel = kernel;
this.serviceDef = serviceDef;
UriPath documentRoot = serviceDef.documentRoot();
if (documentRoot != null && documentRoot.isRelative()) {
final UriPath cwd = UriPath.parse(new File("").getAbsolutePath().replace('\\', '/'));
documentRoot = cwd.appended(documentRoot).removeDotSegments();
}
final UriPath resourceRoot = serviceDef.resourceRoot();
WebRoute router = new RejectRoute();
if (documentRoot != null) {
router = router.orElse(new DirectoryRoute(documentRoot, "index.html"));
}
if (resourceRoot != null) {
final ClassLoader classLoader = ClassLoader.getSystemClassLoader();
router = router.orElse(new ResourceDirectoryRoute(classLoader, resourceRoot, "index.html"));
}
this.router = router;
}
public final KernelContext kernel() {
return this.kernel;
}
public final WebServiceDef serviceDef() {
return this.serviceDef;
}
@Override
public HttpResponder<?> doRequest(HttpRequest<?> httpRequest) {
final Space space = this.kernel.getSpace(this.serviceDef.spaceName);
final PlanePolicy policy = space != null ? space.policy() : null;
final Uri requestUri = httpRequest.uri();
// Verify request permission.
if (policy != null) {
final PolicyDirective<?> directive = policy.canConnect(requestUri);
if (directive.isDenied()) {
return new StaticHttpResponder<Object>(HttpResponse.from(HttpStatus.UNAUTHORIZED)
.content(HttpBody.empty()));
}
}
// Check for WARP upgrade.
// TODO: WarpSpaceRoute
final WsRequest wsRequest = WsRequest.from(httpRequest);
if (wsRequest != null) {
final WsResponse wsResponse = wsRequest.accept(this.wsSettings);
if (wsResponse != null) {
return warpWebSocketResponder(wsRequest, wsResponse);
}
}
// Try routing HTTP lane.
// TODO: HttpLaneRoute
try {
final Uri laneUri = Uri.parse(requestUri.query().get("lane"));
final Uri nodeUri = Uri.from(requestUri.path());
final HttpLaneResponder httpBinding = new HttpLaneResponder(
Uri.empty(), Uri.empty(), nodeUri, laneUri, httpRequest);
final EdgeBinding edge = ((EdgeContext) space).edgeWrapper();
edge.openUplink(httpBinding);
return httpBinding;
} catch (Exception swallow) {
// nop
}
// Route request.
final WebRequest webRequest = new WebServerRequest(httpRequest);
final WebResponse webResponse = this.router.routeRequest(webRequest);
return webResponse.httpResponder();
}
protected HttpResponder<?> warpWebSocketResponder(WsRequest wsRequest, WsResponse wsResponse) {
final RemoteHost host = openHost(wsRequest.httpRequest().uri());
return upgrade(host, wsResponse);
}
protected RemoteHost openHost(Uri requestUri) {
final Uri baseUri = Uri.from(UriScheme.from("warp"),
UriAuthority.from(UriHost.inetAddress(context.localAddress().getAddress()),
UriPort.from(context.localAddress().getPort())),
requestUri.path(), requestUri.query(), requestUri.fragment());
final Uri remoteUri = Uri.from(UriScheme.from("warp"),
UriAuthority.from(UriHost.inetAddress(context.remoteAddress().getAddress()),
UriPort.from(context.remoteAddress().getPort())), UriPath.slash());
final String spaceName = this.serviceDef.spaceName;
final Space space = this.kernel.getSpace(spaceName);
if (space != null) {
final EdgeBinding edge = ((EdgeContext) space).edgeWrapper();
final MeshBinding mesh = edge.openMesh(remoteUri);
final PartBinding gateway = mesh.openGateway();
final RemoteHost host = new RemoteHost(requestUri, baseUri);
gateway.openHost(remoteUri, host);
return host;
} else {
throw new ServiceException("unknown space: " + spaceName);
}
}
}
|
0 | java-sources/ai/swim/swim-service-web/3.10.0/swim/service | java-sources/ai/swim/swim-service-web/3.10.0/swim/service/web/WebService.java | // Copyright 2015-2019 SWIM.AI 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 swim.service.web;
import java.net.InetSocketAddress;
import swim.api.service.Service;
import swim.api.service.ServiceContext;
import swim.io.IpService;
import swim.io.IpServiceRef;
import swim.io.IpSettings;
import swim.io.IpSocket;
import swim.io.IpSocketRef;
import swim.io.http.HttpInterface;
import swim.io.http.HttpServer;
import swim.io.http.HttpService;
import swim.io.http.HttpServiceContext;
import swim.io.http.HttpSettings;
import swim.io.warp.WarpSettings;
import swim.kernel.KernelContext;
public class WebService implements Service, HttpService, HttpInterface {
final KernelContext kernel;
final ServiceContext serviceContext;
final WebServiceDef serviceDef;
HttpServiceContext httpServiceContext;
public WebService(KernelContext kernel, ServiceContext serviceContext, WebServiceDef serviceDef) {
this.kernel = kernel;
this.serviceContext = serviceContext;
this.serviceDef = serviceDef;
}
public final KernelContext kernel() {
return this.kernel;
}
@Override
public final ServiceContext serviceContext() {
return this.serviceContext;
}
@Override
public final HttpServiceContext httpServiceContext() {
return this.httpServiceContext;
}
@Override
public void setHttpServiceContext(HttpServiceContext httpServiceContext) {
this.httpServiceContext = httpServiceContext;
}
public final WebServiceDef serviceDef() {
return this.serviceDef;
}
@Override
public final IpSettings ipSettings() {
return this.serviceDef.warpSettings.ipSettings();
}
@Override
public final HttpSettings httpSettings() {
return this.serviceDef.warpSettings.httpSettings();
}
public final WarpSettings warpSettings() {
return this.serviceDef.warpSettings;
}
@Override
public IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
return this.serviceContext.bindTcp(localAddress, service, ipSettings);
}
@Override
public IpServiceRef bindTls(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
return this.serviceContext.bindTls(localAddress, service, ipSettings);
}
@Override
public IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
return this.serviceContext.connectTcp(remoteAddress, socket, ipSettings);
}
@Override
public IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
return this.serviceContext.connectTls(remoteAddress, socket, ipSettings);
}
@Override
public HttpServer createServer() {
return new WebServer(this.kernel, this.serviceDef);
}
@Override
public void willStart() {
// stub
}
@Override
public void didStart() {
final WebServiceDef serviceDef = this.serviceDef;
if (serviceDef.isSecure) {
bindHttps(serviceDef.address, serviceDef.port, this, serviceDef.warpSettings.httpSettings());
} else {
bindHttp(serviceDef.address, serviceDef.port, this, serviceDef.warpSettings.httpSettings());
}
}
@Override
public void didBind() {
// stub
}
@Override
public void didAccept(HttpServer server) {
// stub
}
@Override
public void didUnbind() {
// stub
}
@Override
public void willStop() {
final HttpServiceContext httpServiceContext = this.httpServiceContext;
if (httpServiceContext != null) {
httpServiceContext.unbind();
this.httpServiceContext = null;
}
}
@Override
public void didStop() {
// stub
}
@Override
public void willClose() {
// stub
}
@Override
public void didClose() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
}
|
0 | java-sources/ai/swim/swim-service-web/3.10.0/swim/service | java-sources/ai/swim/swim-service-web/3.10.0/swim/service/web/WebServiceDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.service.web;
import swim.api.service.ServiceDef;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.io.warp.WarpSettings;
import swim.uri.UriPath;
import swim.util.Murmur3;
public class WebServiceDef implements ServiceDef, Debug {
final String serviceName;
final String address;
final int port;
final boolean isSecure;
final String spaceName;
final UriPath documentRoot;
final UriPath resourceRoot;
final WarpSettings warpSettings;
public WebServiceDef(String serviceName, String address, int port, boolean isSecure,
String spaceName, UriPath documentRoot, UriPath resourceRoot,
WarpSettings warpSettings) {
this.serviceName = serviceName;
this.address = address;
this.port = port;
this.isSecure = isSecure;
this.spaceName = spaceName;
this.documentRoot = documentRoot;
this.resourceRoot = resourceRoot;
this.warpSettings = warpSettings;
}
@Override
public final String serviceName() {
return this.serviceName;
}
public WebServiceDef serviceName(String serviceName) {
return copy(serviceName, this.address, this.port, this.isSecure,
this.spaceName, this.documentRoot, this.resourceRoot, this.warpSettings);
}
public final String address() {
return this.address;
}
public WebServiceDef address(String address) {
return copy(this.serviceName, address, this.port, this.isSecure,
this.spaceName, this.documentRoot, this.resourceRoot, this.warpSettings);
}
public final int port() {
return this.port;
}
public WebServiceDef port(int port) {
return copy(this.serviceName, this.address, port, this.isSecure,
this.spaceName, this.documentRoot, this.resourceRoot, this.warpSettings);
}
public final String spaceName() {
return this.spaceName;
}
public WebServiceDef spaceName(String spaceName) {
return copy(this.serviceName, this.address, this.port, this.isSecure,
spaceName, this.documentRoot, this.resourceRoot, this.warpSettings);
}
public final UriPath documentRoot() {
return this.documentRoot;
}
public WebServiceDef documentRoot(UriPath documentRoot) {
return copy(this.serviceName, this.address, this.port, this.isSecure,
this.spaceName, documentRoot, this.resourceRoot, this.warpSettings);
}
public final UriPath resourceRoot() {
return this.resourceRoot;
}
public WebServiceDef resourceRoot(UriPath resourceRoot) {
return copy(this.serviceName, this.address, this.port, this.isSecure,
this.spaceName, this.documentRoot, resourceRoot, this.warpSettings);
}
public final WarpSettings warpSettings() {
return this.warpSettings;
}
public WebServiceDef warpSettings(WarpSettings warpSettings) {
return copy(this.serviceName, this.address, this.port, this.isSecure,
this.spaceName, this.documentRoot, this.resourceRoot, warpSettings);
}
protected WebServiceDef copy(String serviceName, String address, int port, boolean isSecure,
String spaceName, UriPath documentRoot, UriPath resourceRoot,
WarpSettings warpSettings) {
return new WebServiceDef(serviceName, address, port, isSecure, spaceName,
documentRoot, resourceRoot, warpSettings);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof WebServiceDef) {
final WebServiceDef that = (WebServiceDef) other;
return (this.serviceName == null ? that.serviceName == null : this.serviceName.equals(that.serviceName))
&& this.address.equals(that.address) && this.port == that.port && this.isSecure == that.isSecure
&& (this.spaceName == null ? that.spaceName == null : this.spaceName.equals(that.spaceName))
&& (this.documentRoot == null ? that.documentRoot == null : this.documentRoot.equals(that.documentRoot))
&& (this.resourceRoot == null ? that.resourceRoot == null : this.resourceRoot.equals(that.resourceRoot))
&& this.warpSettings.equals(that.warpSettings);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(WebServiceDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(
Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, Murmur3.hash(this.serviceName)),
this.address.hashCode()), this.port), Murmur3.hash(this.isSecure)),
Murmur3.hash(this.spaceName)), Murmur3.hash(this.documentRoot)),
Murmur3.hash(this.resourceRoot)), this.warpSettings.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("WebServiceDef").write('.')
.write(this.isSecure ? "secure" : "standard").write('(').write(')');
if (!"web".equals(this.serviceName)) {
output = output.write('.').write("serviceName").write('(').debug(this.serviceName).write(')');
}
if (!"0.0.0.0".equals(this.address)) {
output = output.write('.').write("address").write('(').debug(this.address).write(')');
}
if (this.isSecure && this.port != 443 || !this.isSecure && port != 80) {
output = output.write('.').write("port").write('(').debug(this.port).write(')');
}
if (this.spaceName != null) {
output = output.write('.').write("spaceName").write('(').debug(this.spaceName).write(')');
}
if (this.documentRoot != null) {
output = output.write('.').write("documentRoot").write('(').debug(this.documentRoot).write(')');
}
if (this.resourceRoot != null) {
output = output.write('.').write("resourceRoot").write('(').debug(this.resourceRoot).write(')');
}
if (this.warpSettings != WarpSettings.standard()) {
output = output.write('.').write("warpSettings").write('(').debug(this.warpSettings).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static WebServiceDef standard() {
return new WebServiceDef("web", "0.0.0.0", 80, false, null, null, null, WarpSettings.standard());
}
public static WebServiceDef secure() {
return new WebServiceDef("web", "0.0.0.0", 443, true, null, null, null, WarpSettings.standard());
}
}
|
0 | java-sources/ai/swim/swim-service-web/3.10.0/swim/service | java-sources/ai/swim/swim-service-web/3.10.0/swim/service/web/WebServiceFactory.java | // Copyright 2015-2019 SWIM.AI 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 swim.service.web;
import swim.api.service.ServiceContext;
import swim.api.service.ServiceFactory;
import swim.kernel.KernelContext;
public class WebServiceFactory implements ServiceFactory<WebService> {
final KernelContext kernel;
final WebServiceDef serviceDef;
WebServiceFactory(KernelContext kernel, WebServiceDef serviceDef) {
this.kernel = kernel;
this.serviceDef = serviceDef;
}
public final KernelContext kernel() {
return this.kernel;
}
public final WebServiceDef serviceDef() {
return this.serviceDef;
}
@Override
public WebService createService(ServiceContext context) {
return new WebService(this.kernel, context, this.serviceDef);
}
}
|
0 | java-sources/ai/swim/swim-service-web/3.10.0/swim/service | java-sources/ai/swim/swim-service-web/3.10.0/swim/service/web/WebServiceKernel.java | // Copyright 2015-2019 SWIM.AI 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 swim.service.web;
import swim.api.service.ServiceDef;
import swim.api.service.ServiceFactory;
import swim.io.warp.WarpSettings;
import swim.kernel.KernelContext;
import swim.kernel.KernelProxy;
import swim.structure.Item;
import swim.structure.Value;
import swim.uri.UriPath;
public class WebServiceKernel extends KernelProxy {
final double kernelPriority;
public WebServiceKernel(double kernelPriority) {
this.kernelPriority = kernelPriority;
}
public WebServiceKernel() {
this(KERNEL_PRIORITY);
}
@Override
public final double kernelPriority() {
return this.kernelPriority;
}
@Override
public ServiceDef defineService(Item serviceConfig) {
final ServiceDef serviceDef = defineWebService(serviceConfig);
return serviceDef != null ? serviceDef : super.defineService(serviceConfig);
}
public WebServiceDef defineWebService(Item serviceConfig) {
final Value value = serviceConfig.toValue();
Value header = value.getAttr("web");
boolean isSecure = false;
if (!header.isDefined()) {
header = value.getAttr("warp"); // deprecated
}
if (!header.isDefined()) {
header = value.getAttr("warps"); // deprecated
isSecure = true;
}
if (header.isDefined()) {
final String webProvider = header.get("provider").stringValue(null);
if (webProvider == null || WebServiceKernel.class.getName().equals(webProvider)) {
final String serviceName = serviceConfig.key().stringValue("web");
final String address = header.get("address").stringValue("0.0.0.0");
final int port = header.get("port").intValue(443);
isSecure = header.get("secure").booleanValue(isSecure);
String spaceName = value.get("space").stringValue(null);
if (spaceName == null) {
spaceName = value.get("plane").stringValue(null); // deprecated
}
final UriPath documentRoot = value.get("documentRoot").cast(UriPath.pathForm());
final UriPath resourceRoot = value.get("resourceRoot").cast(UriPath.pathForm());
final WarpSettings warpSettings = WarpSettings.form().cast(value);
return new WebServiceDef(serviceName, address, port, isSecure, spaceName,
documentRoot, resourceRoot, warpSettings);
}
}
return null;
}
@Override
public ServiceFactory<?> createServiceFactory(ServiceDef serviceDef, ClassLoader classLoader) {
if (serviceDef instanceof WebServiceDef) {
return createWarpServiceFactory((WebServiceDef) serviceDef);
} else {
return super.createServiceFactory(serviceDef, classLoader);
}
}
public WebServiceFactory createWarpServiceFactory(WebServiceDef serviceDef) {
final KernelContext kernel = kernelWrapper().unwrapKernel(KernelContext.class);
return new WebServiceFactory(kernel, serviceDef);
}
private static final double KERNEL_PRIORITY = 0.75;
public static WebServiceKernel fromValue(Value moduleConfig) {
final Value header = moduleConfig.getAttr("kernel");
final String kernelClassName = header.get("class").stringValue(null);
if (kernelClassName == null || WebServiceKernel.class.getName().equals(kernelClassName)) {
final double kernelPriority = header.get("priority").doubleValue(KERNEL_PRIORITY);
return new WebServiceKernel(kernelPriority);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-service-web/3.10.0/swim/service | java-sources/ai/swim/swim-service-web/3.10.0/swim/service/web/package-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Web service runtime.
*/
package swim.service.web;
|
0 | java-sources/ai/swim/swim-spatial | java-sources/ai/swim/swim-spatial/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Spatial collections and geospatial projections.
*/
module swim.spatial {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.structure;
requires transitive swim.math;
exports swim.spatial;
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/BitInterval.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
/**
* Significant bit interval encoding. Represents power-of-2 sized integer
* intervals as a (64 - k) bit prefix with a k bit suffix.
* <p>
* Leading one bits replace trailing variable suffix bits. For an integer x
* with k variable suffix bits, shift k high prefix 1 bits into x.
* <p>
* The rank of a bit interval is the number of trailing variable bits.
* The base of a bit interval is the lower bound of the interval.
* <p>
* Examples for constant prefix bits x, and variable suffix bits y:
* <p>
* range 2^0:<br>
* significant: 0xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx<br>
* bit interval: 0xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
* <p>
* range 2^1:<br>
* significand: 0xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxy<br>
* bit interval: 10xxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
* <p>
* range 2^2:<br>
* significand: 0xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxyy<br>
* bit interval: 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
* <p>
* range 2^3:<br>
* significand: 0xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxyyy<br>
* bit interval: 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
* <p>
* range 2^4:<br>
* significand: 0xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxyyyy<br>
* bit interval: 11110xxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
* <p>
* range 2^63<br>
* significand: 0yyyyyyy yyyyyyyy yyyyyyyy yyyyyyyy yyyyyyyy yyyyyyyy yyyyyyyy yyyyyyyy<br>
* bit interval: 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111110
*/
public final class BitInterval {
private BitInterval() {
// stub
}
public static long from(int rank, long base) {
return rank < 64 ? ((1L << rank) - 1L) << (64 - rank) | base >>> rank : -1L;
}
public static long span(long x0, long x1) {
x0 &= 0x7fffffffffffffffL; // truncate to 63 bits
x1 &= 0x7fffffffffffffffL; // truncate to 63 bits
final int rank = 64 - Long.numberOfLeadingZeros(-1L & x0 & x1 ^ (x0 | x1));
final long mask = ~((1L << rank) - 1L);
final long base = (x0 | x1) & mask;
return from(rank, base);
}
public static long union(long a, long b) {
final int aRank = Long.numberOfLeadingZeros(~a);
final int bRank = Long.numberOfLeadingZeros(~b);
final long aBase = aRank < 64 ? a << aRank : 0L;
final long bBase = bRank < 64 ? b << bRank : 0L;
final long base = aBase | bBase;
final long mask = -1L & aBase & bBase ^ base;
final int rank = Math.max(64 - Long.numberOfLeadingZeros(mask), Math.max(aRank, bRank));
return from(rank, base);
}
public static int rank(long bitInterval) {
return Long.numberOfLeadingZeros(~bitInterval);
}
public static long base(long bitInterval) {
final int rank = rank(bitInterval);
return rank < 64 ? bitInterval << rank : 0L;
}
public static long mask(long bitInterval) {
final int rank = rank(bitInterval);
return rank < 64 ? ~((1L << rank) - 1L) : 0L;
}
public static int compare(long a, long b) {
final int aRank = Long.numberOfLeadingZeros(~a);
final int bRank = Long.numberOfLeadingZeros(~b);
long aNorm = aRank < 64 ? a << aRank : 0L;
long bNorm = bRank < 64 ? b << bRank : 0L;
if (aRank < bRank) {
// Clear low bRank bits of aNorm.
aNorm &= ~((1L << bRank) - 1L);
} else if (aRank > bRank) {
// Clear low aRank bits of bNorm.
bNorm &= ~((1L << aRank) - 1L);
}
return aNorm < bNorm ? -1 : aNorm > bNorm ? 1 : 0;
}
public static int compare(long xa, long ya, long xb, long yb) {
int order = compare(xa, xb);
if (order == 0) {
order = compare(ya, yb);
}
return order;
}
public static boolean contains(long q, long a) {
final int qRank = Long.numberOfLeadingZeros(~q);
final int aRank = Long.numberOfLeadingZeros(~a);
final long qBase = qRank < 64 ? q << qRank : 0L;
final long aBase = aRank < 64 ? a << aRank : 0L;
final long qMask = qRank < 64 ? ~((1L << qRank) - 1L) : 0L;
return aRank <= qRank && (aBase & qMask) == qBase;
}
public static boolean contains(long xq, long yq, long xa, long ya) {
return contains(xq, xa) && contains(yq, ya);
}
public static boolean intersects(long q, long a) {
final int qRank = Long.numberOfLeadingZeros(~q);
final int aRank = Long.numberOfLeadingZeros(~a);
final long qBase = qRank < 64 ? q << qRank : 0L;
final long aBase = aRank < 64 ? a << aRank : 0L;
final long qMask = qRank < 64 ? ~((1L << qRank) - 1L) : 0L;
final long aMask = aRank < 64 ? ~((1L << aRank) - 1L) : 0L;
return aRank <= qRank && (aBase & qMask) == qBase
|| qRank <= aRank && (qBase & aMask) == aBase;
}
public static boolean intersects(long xq, long yq, long xa, long ya) {
return intersects(xq, xa) && intersects(yq, ya);
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/GeoProjection.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import swim.math.R2Shape;
import swim.math.R2ToZ2Operator;
import swim.math.Z2Form;
import swim.math.Z2ToR2Operator;
public final class GeoProjection {
private GeoProjection() {
// stub
}
private static WGS84 wgs84;
private static WGS84Inverse wgs84Inverse;
private static SphericalMercator sphericalMercator;
private static SphericalMercatorInverse sphericalMercatorInverse;
public static R2ToZ2Operator wgs84() {
if (wgs84 == null) {
wgs84 = new WGS84();
}
return wgs84;
}
public static Z2ToR2Operator wgs84Inverse() {
if (wgs84Inverse == null) {
wgs84Inverse = new WGS84Inverse();
}
return wgs84Inverse;
}
public static Z2Form<R2Shape> wgs84Form() {
if (wgs84 == null) {
wgs84 = new WGS84();
}
return wgs84;
}
public static R2ToZ2Operator sphericalMercator() {
if (sphericalMercator == null) {
sphericalMercator = new SphericalMercator();
}
return sphericalMercator;
}
public static Z2ToR2Operator sphericalMercatorInverse() {
if (sphericalMercatorInverse == null) {
sphericalMercatorInverse = new SphericalMercatorInverse();
}
return sphericalMercatorInverse;
}
public static Z2Form<R2Shape> sphericalMercatorForm() {
if (sphericalMercator == null) {
sphericalMercator = new SphericalMercator();
}
return sphericalMercator;
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTree.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Comparator;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.math.Z2Form;
import swim.util.Cursor;
import swim.util.Murmur3;
public class QTree<K, S, V> extends QTreeContext<K, S, V> implements SpatialMap<K, S, V>, Comparator<QTreeEntry<K, S, V>>, Cloneable, Debug {
final Z2Form<S> shapeForm;
QTreePage<K, S, V> root;
protected QTree(Z2Form<S> shapeForm, QTreePage<K, S, V> root) {
this.shapeForm = shapeForm;
this.root = root;
}
public QTree(Z2Form<S> shapeForm) {
this(shapeForm, QTreePage.<K, S, V>empty());
}
@Override
public boolean isEmpty() {
return this.root.isEmpty();
}
@Override
public int size() {
return (int) this.root.span();
}
@Override
public boolean containsKey(K key, S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
return this.root.containsKey(key, x, y, this);
}
@Override
public boolean containsKey(Object key) {
final Cursor<QTreeEntry<K, S, V>> cursor = this.root.cursor();
while (cursor.hasNext()) {
if (key.equals(cursor.next().key)) {
return true;
}
}
return false;
}
@Override
public boolean containsValue(Object value) {
final Cursor<QTreeEntry<K, S, V>> cursor = this.root.cursor();
while (cursor.hasNext()) {
if (value.equals(cursor.next().value)) {
return true;
}
}
return false;
}
@Override
public V get(K key, S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
return this.root.get(key, x, y, this);
}
@Override
public V get(Object key) {
final Cursor<QTreeEntry<K, S, V>> cursor = this.root.cursor();
while (cursor.hasNext()) {
final QTreeEntry<K, S, V> slot = cursor.next();
if (key.equals(slot.key)) {
return slot.value;
}
}
return null;
}
@Override
public V put(K key, S shape, V newValue) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
final QTreePage<K, S, V> oldRoot = this.root;
final QTreePage<K, S, V> newRoot = oldRoot.updated(key, shape, x, y, newValue, this)
.balanced(this);
if (oldRoot != newRoot) {
this.root = newRoot;
return oldRoot.get(key, x, y, this);
} else {
return null;
}
}
@Override
public V move(K key, S oldShape, S newShape, V newValue) {
final Z2Form<S> shapeForm = this.shapeForm;
final long oldX = BitInterval.span(shapeForm.getXMin(oldShape), shapeForm.getXMax(oldShape));
final long oldY = BitInterval.span(shapeForm.getYMin(oldShape), shapeForm.getYMax(oldShape));
final long newX = BitInterval.span(shapeForm.getXMin(newShape), shapeForm.getXMax(newShape));
final long newY = BitInterval.span(shapeForm.getYMin(newShape), shapeForm.getYMax(newShape));
final QTreePage<K, S, V> oldRoot = this.root;
final QTreePage<K, S, V> newRoot = oldRoot.removed(key, oldX, oldY, this)
.balanced(this)
.updated(key, newShape, newX, newY, newValue, this)
.balanced(this);
if (oldRoot != newRoot) {
this.root = newRoot;
return oldRoot.get(key, oldX, oldY, this);
} else {
return null;
}
}
@Override
public V remove(K key, S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
final QTreePage<K, S, V> oldRoot = this.root;
final QTreePage<K, S, V> newRoot = oldRoot.removed(key, x, y, this)
.balanced(this);
if (oldRoot != newRoot) {
this.root = newRoot;
return oldRoot.get(key, x, y, this);
} else {
return null;
}
}
@Override
public void clear() {
this.root = QTreePage.empty();
}
public QTree<K, S, V> updated(K key, S shape, V newValue) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
final QTreePage<K, S, V> oldRoot = this.root;
QTreePage<K, S, V> newRoot = oldRoot.updated(key, shape, x, y, newValue, this);
if (oldRoot != newRoot) {
if (newRoot.span() > oldRoot.span()) {
newRoot = newRoot.balanced(this);
}
return copy(newRoot);
} else {
return this;
}
}
public QTree<K, S, V> removed(K key, S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
final QTreePage<K, S, V> oldRoot = this.root;
QTreePage<K, S, V> newRoot = oldRoot.removed(key, x, y, this);
if (oldRoot != newRoot) {
newRoot = newRoot.balanced(this);
return copy(newRoot);
} else {
return this;
}
}
@Override
public Cursor<Entry<K, S, V>> iterator(S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
return new QTreeShapeCursor<K, S, V>(this.root.cursor(x, y), shapeForm, shape);
}
@SuppressWarnings("unchecked")
@Override
public Cursor<Entry<K, S, V>> iterator() {
return (Cursor<Entry<K, S, V>>) (Cursor<?>) this.root.cursor();
}
@Override
public Cursor<K> keyIterator() {
return Cursor.keys(this.root.cursor());
}
@Override
public Cursor<V> valueIterator() {
return Cursor.values(this.root.cursor());
}
@Override
public QTree<K, S, V> clone() {
return copy(this.root);
}
protected QTree<K, S, V> copy(QTreePage<K, S, V> root) {
return new QTree<K, S, V>(this.shapeForm, root);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof QTree<?, ?, ?>) {
final QTree<K, S, V> that = (QTree<K, S, V>) other;
if (size() == that.size()) {
final Cursor<Entry<K, S, V>> those = that.iterator();
while (those.hasNext()) {
final Entry<K, S, V> entry = those.next();
final V value = get(entry.getKey());
final V v = entry.getValue();
if (value == null ? v != null : !value.equals(v)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(QTree.class);
}
int a = 0;
int b = 0;
int c = 1;
final Cursor<Entry<K, S, V>> these = iterator();
while (these.hasNext()) {
final Entry<K, S, V> entry = these.next();
final int h = Murmur3.mix(Murmur3.hash(entry.getKey()), Murmur3.hash(entry.getValue()));
a ^= h;
b += h;
if (h != 0) {
c *= h;
}
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, a), b), c));
}
@Override
public void debug(Output<?> output) {
output = output.write("QTree").write('.').write("empty").write('(')
.debug(this.shapeForm).write(')');
for (Entry<K, S, V> entry : this) {
output = output.write('.').write("updated").write('(')
.debug(entry.getKey()).write(", ")
.debug(entry.getShape()).write(", ")
.debug(entry.getValue()).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static <K, S, V> QTree<K, S, V> empty(Z2Form<S> shapeForm) {
return new QTree<K, S, V>(shapeForm);
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreeContext.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Comparator;
public abstract class QTreeContext<K, S, V> implements Comparator<QTreeEntry<K, S, V>> {
@Override
public int compare(QTreeEntry<K, S, V> x, QTreeEntry<K, S, V> y) {
return compareKey(x.key, y.key);
}
@SuppressWarnings("unchecked")
protected int compareKey(K x, K y) {
return ((Comparable<Object>) x).compareTo(y);
}
protected int pageSplitSize() {
return 32;
}
protected boolean pageShouldSplit(QTreePage<K, S, V> page) {
return page.arity() > pageSplitSize();
}
protected boolean pageShouldMerge(QTreePage<K, S, V> page) {
return page.arity() < pageSplitSize() >>> 1;
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreeEntry.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Map;
public class QTreeEntry<K, S, V> implements SpatialMap.Entry<K, S, V> {
final K key;
final S shape;
final long x;
final long y;
final V value;
public QTreeEntry(K key, S shape, long x, long y, V value) {
this.key = key;
this.shape = shape;
this.x = x;
this.y = y;
this.value = value;
}
@Override
public final K getKey() {
return this.key;
}
@Override
public final S getShape() {
return this.shape;
}
public final long x() {
return this.x;
}
public final int xRank() {
return Long.numberOfLeadingZeros(~this.x);
}
public final long xBase() {
return this.x << xRank();
}
public final long y() {
return this.y;
}
public final int yRank() {
return Long.numberOfLeadingZeros(~this.y);
}
public final long yBase() {
return this.y << yRank();
}
@Override
public final V getValue() {
return this.value;
}
@Override
public V setValue(V newValue) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Map.Entry<?, ?>) {
final Map.Entry<?, ?> that = (Map.Entry<?, ?>) other;
if (this.key == null ? that.getKey() != null : !this.key.equals(that.getKey())) {
return false;
}
if (this.value == null ? that.getValue() != null : !this.value.equals(that.getValue())) {
return false;
}
return true;
}
return false;
}
@Override
public int hashCode() {
return (this.key == null ? 0 : this.key.hashCode())
^ (this.value == null ? 0 : this.value.hashCode());
}
@Override
public String toString() {
return new StringBuilder().append(this.key).append('=').append(this.value).toString();
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreeLeaf.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Arrays;
import swim.util.Cursor;
final class QTreeLeaf<K, S, V> extends QTreePage<K, S, V> {
final QTreeEntry<K, S, V>[] slots;
final long x;
final long y;
QTreeLeaf(QTreeEntry<K, S, V>[] slots, long x, long y) {
this.slots = slots;
this.x = x;
this.y = y;
}
@Override
public boolean isEmpty() {
return this.slots.length == 0;
}
@Override
public long span() {
return (long) this.slots.length;
}
@Override
public int arity() {
return this.slots.length;
}
@Override
public QTreePage<K, S, V> getPage(int index) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
@Override
public int slotCount() {
return this.slots.length;
}
@Override
public QTreeEntry<K, S, V> getSlot(int index) {
return this.slots[index];
}
@Override
public long x() {
return this.x;
}
@Override
public int xRank() {
return Long.numberOfLeadingZeros(~this.x);
}
@Override
public long xBase() {
return this.x << xRank();
}
@Override
public long xMask() {
return ~((1L << xRank()) - 1L);
}
@Override
public long xSplit() {
return this.x << 1 & 1L;
}
@Override
public long y() {
return this.y;
}
@Override
public int yRank() {
return Long.numberOfLeadingZeros(~this.y);
}
@Override
public long yBase() {
return this.y << yRank();
}
@Override
public long yMask() {
return ~((1L << yRank()) - 1L);
}
@Override
public long ySplit() {
return this.y << 1 & 1L;
}
boolean containsKey(K key, QTreeContext<K, S, V> tree) {
return lookup(key, tree) >= 0;
}
@Override
public boolean containsKey(K key, long xk, long yk, QTreeContext<K, S, V> tree) {
return containsKey(key, tree);
}
V get(K key, QTreeContext<K, S, V> tree) {
final int i = lookup(key, tree);
if (i >= 0) {
return this.slots[i].value;
} else {
return null;
}
}
@Override
public V get(K key, long xk, long yk, QTreeContext<K, S, V> tree) {
return get(key, tree);
}
@Override
public QTreeLeaf<K, S, V> updated(K key, S shape, long xk, long yk, V newValue,
QTreeContext<K, S, V> tree, boolean canSplit) {
int i = lookup(key, tree);
if (i >= 0) {
return updatedSlot(i, key, shape, xk, yk, newValue);
} else {
i = -(i + 1);
return insertedSlot(i, key, shape, xk, yk, newValue);
}
}
@Override
QTreeLeaf<K, S, V> updatedSlot(QTreeEntry<K, S, V> newSlot, QTreeContext<K, S, V> tree) {
int i = lookup(newSlot.key, tree);
if (i >= 0) {
return updatedSlot(i, newSlot);
} else {
i = -(i + 1);
return insertedSlot(i, newSlot);
}
}
@SuppressWarnings("unchecked")
QTreeLeaf<K, S, V> updatedSlot(int i, QTreeEntry<K, S, V> newSlot) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final QTreeEntry<K, S, V> oldSlot = oldSlots[i];
if (!newSlot.equals(oldSlot)) {
final int n = oldSlots.length;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, n);
newSlots[i] = newSlot;
return QTreeLeaf.create(newSlots);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
QTreeLeaf<K, S, V> updatedSlot(int i, K key, S shape, long xk, long yk, V newValue) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final QTreeEntry<K, S, V> oldSlot = oldSlots[i];
final long oldX = oldSlot.x;
final long oldY = oldSlot.y;
if (!newValue.equals(oldSlot.value) || oldX != xk || oldY != yk) {
final int n = oldSlots.length;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, n);
newSlots[i] = new QTreeEntry<K, S, V>(key, shape, xk, yk, newValue);
return QTreeLeaf.create(newSlots);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
QTreeLeaf<K, S, V> insertedSlot(int i, QTreeEntry<K, S, V> newSlot) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final int n = oldSlots.length + 1;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, i);
newSlots[i] = newSlot;
System.arraycopy(oldSlots, i, newSlots, i + 1, n - (i + 1));
return QTreeLeaf.create(newSlots);
}
@SuppressWarnings("unchecked")
QTreeLeaf<K, S, V> insertedSlot(int i, K key, S shape, long xk, long yk, V newValue) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final int n = oldSlots.length + 1;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, i);
newSlots[i] = new QTreeEntry<K, S, V>(key, shape, xk, yk, newValue);
System.arraycopy(oldSlots, i, newSlots, i + 1, n - (i + 1));
return QTreeLeaf.create(newSlots);
}
@Override
QTreeLeaf<K, S, V> insertedPage(QTreePage<K, S, V> newPage, QTreeContext<K, S, V> tree) {
return mergedPage(newPage, tree);
}
@Override
QTreeLeaf<K, S, V> mergedPage(QTreePage<K, S, V> newPage, QTreeContext<K, S, V> tree) {
if (newPage instanceof QTreeLeaf<?, ?, ?>) {
return mergedLeaf((QTreeLeaf<K, S, V>) newPage, tree);
} else {
return mergedNode(newPage, tree);
}
}
QTreeLeaf<K, S, V> mergedLeaf(QTreeLeaf<K, S, V> newPage, QTreeContext<K, S, V> tree) {
return mergedSlots(newPage.slots, tree);
}
@SuppressWarnings("unchecked")
QTreeLeaf<K, S, V> mergedNode(QTreePage<K, S, V> newPage, QTreeContext<K, S, V> tree) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
int i = oldSlots.length;
final int n = i + (int) newPage.span();
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, i);
final Cursor<QTreeEntry<K, S, V>> cursor = newPage.cursor();
while (cursor.hasNext()) {
newSlots[i] = cursor.next();
i += 1;
}
Arrays.sort(newSlots, tree);
return QTreeLeaf.create(newSlots);
}
@SuppressWarnings("unchecked")
@Override
QTreeLeaf<K, S, V> mergedSlots(QTreeEntry<K, S, V>[] midSlots, QTreeContext<K, S, V> tree) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[oldSlots.length + midSlots.length];
System.arraycopy(oldSlots, 0, newSlots, 0, oldSlots.length);
System.arraycopy(midSlots, 0, newSlots, oldSlots.length, midSlots.length);
Arrays.sort(newSlots, tree);
return QTreeLeaf.create(newSlots);
}
@Override
public QTreeLeaf<K, S, V> removed(K key, long xk, long yk, QTreeContext<K, S, V> tree) {
final int i = lookup(key, tree);
if (i >= 0) {
if (this.slots.length > 1) {
return removedSlot(i);
} else {
return QTreeLeaf.empty();
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
QTreeLeaf<K, S, V> removedSlot(int i) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final int n = oldSlots.length - 1;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, i);
System.arraycopy(oldSlots, i + 1, newSlots, i, n - i);
return QTreeLeaf.create(newSlots);
}
@Override
public QTreeLeaf<K, S, V> flattened(QTreeContext<K, S, V> tree) {
return this;
}
@Override
public QTreePage<K, S, V> balanced(QTreeContext<K, S, V> tree) {
if (this.slots.length > 1 && tree.pageShouldSplit(this)) {
return split(tree);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public QTreeNode<K, S, V> split(QTreeContext<K, S, V> tree) {
final long x = this.x;
final long y = this.y;
final int xRank = Long.numberOfLeadingZeros(~x);
final int yRank = Long.numberOfLeadingZeros(~y);
final int xnRank = Math.max(0, xRank - 1);
final int ynRank = Math.max(0, yRank - 1);
final long xnMask = ~((1L << xnRank) - 1L);
final long ynMask = ~((1L << ynRank) - 1L);
final long x0Base = x << xRank;
final long y0Base = y << yRank;
final long x1Base = x0Base | (1L << xnRank);
final long y1Base = y0Base | (1L << ynRank);
int x00Rank = 0;
int y00Rank = 0;
int x01Rank = 0;
int y01Rank = 0;
int x10Rank = 0;
int y10Rank = 0;
int x11Rank = 0;
int y11Rank = 0;
int xX0Rank = 0;
int yX0Rank = 0;
int xX1Rank = 0;
int yX1Rank = 0;
long x00Base = 0L;
long y00Base = 0L;
long x01Base = 0L;
long y01Base = 0L;
long x10Base = 0L;
long y10Base = 0L;
long x11Base = 0L;
long y11Base = 0L;
long xX0Base = 0L;
long yX0Base = 0L;
long xX1Base = 0L;
long yX1Base = 0L;
long x00Mask = -1L;
long y00Mask = -1L;
long x01Mask = -1L;
long y01Mask = -1L;
long x10Mask = -1L;
long y10Mask = -1L;
long x11Mask = -1L;
long y11Mask = -1L;
long xX0Mask = -1L;
long yX0Mask = -1L;
long xX1Mask = -1L;
long yX1Mask = -1L;
final QTreeEntry<K, S, V>[] slots = this.slots;
QTreeEntry<K, S, V>[] slots00 = null;
QTreeEntry<K, S, V>[] slots01 = null;
QTreeEntry<K, S, V>[] slots10 = null;
QTreeEntry<K, S, V>[] slots11 = null;
QTreeEntry<K, S, V>[] slotsX0 = null;
QTreeEntry<K, S, V>[] slotsX1 = null;
QTreeEntry<K, S, V>[] slotsXY = null;
final int slotCount = slots.length;
int slotCount00 = 0;
int slotCount01 = 0;
int slotCount10 = 0;
int slotCount11 = 0;
int slotCountX0 = 0;
int slotCountX1 = 0;
int slotCountXY = 0;
for (int i = 0; i < slotCount; i += 1) {
final QTreeEntry<K, S, V> slot = slots[i];
final long xt = slot.x;
final long yt = slot.y;
final int xtRank = Long.numberOfLeadingZeros(~xt);
final int ytRank = Long.numberOfLeadingZeros(~yt);
final long xtBase = xt << xtRank;
final long ytBase = yt << ytRank;
final long xtNorm = xtBase & xnMask;
final long ytNorm = ytBase & ynMask;
if (xnRank > 0 && xtRank > xnRank) {
if (ynRank > 0 && ytRank > ynRank) {
slotsXY[slotCountXY] = slot;
slotCountXY += 1;
} else if (ytNorm == y0Base) {
if (slotsX0 == null) {
slotsX0 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slotsX0[slotCountX0] = slot;
slotCountX0 += 1;
xX0Rank = Math.max(xX0Rank, xtRank);
yX0Rank = Math.max(yX0Rank, ytRank);
xX0Base |= xtBase;
yX0Base |= ytBase;
xX0Mask &= xtBase;
yX0Mask &= ytBase;
} else {
if (slotsX1 == null) {
slotsX1 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slotsX1[slotCountX1] = slot;
slotCountX1 += 1;
xX1Rank = Math.max(xX1Rank, xtRank);
yX1Rank = Math.max(yX1Rank, ytRank);
xX1Base |= xtBase;
yX1Base |= ytBase;
xX1Mask &= xtBase;
yX1Mask &= ytBase;
}
} else if (xtNorm == x0Base) {
if (ytNorm == y0Base) {
if (slots00 == null) {
slots00 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slots00[slotCount00] = slot;
slotCount00 += 1;
x00Rank = Math.max(x00Rank, xtRank);
y00Rank = Math.max(y00Rank, ytRank);
x00Base |= xtBase;
y00Base |= ytBase;
x00Mask &= xtBase;
y00Mask &= ytBase;
} else {
if (slots01 == null) {
slots01 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slots01[slotCount01] = slot;
slotCount01 += 1;
x01Rank = Math.max(x01Rank, xtRank);
y01Rank = Math.max(y01Rank, ytRank);
x01Base |= xtBase;
y01Base |= ytBase;
x01Mask &= xtBase;
y01Mask &= ytBase;
}
} else {
if (ytNorm == y0Base) {
if (slots10 == null) {
slots10 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slots10[slotCount10] = slot;
slotCount10 += 1;
x10Rank = Math.max(x10Rank, xtRank);
y10Rank = Math.max(y10Rank, ytRank);
x10Base |= xtBase;
y10Base |= ytBase;
x10Mask &= xtBase;
y10Mask &= ytBase;
} else {
if (slots11 == null) {
slots11 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slots11[slotCount11] = slot;
slotCount11 += 1;
x11Rank = Math.max(x11Rank, xtRank);
y11Rank = Math.max(y11Rank, ytRank);
x11Base |= xtBase;
y11Base |= ytBase;
x11Mask &= xtBase;
y11Mask &= ytBase;
}
}
}
if (slotCountX1 > 0 && (slotCount01 == 0 || slotCount11 == 0)) {
if (slots01 != null) {
System.arraycopy(slotsX1, 0, slots01, slotCount01, slotCountX1);
} else {
slots01 = slotsX1;
}
slotCount01 += slotCountX1;
x01Rank = Math.max(x01Rank, xX1Rank);
y01Rank = Math.max(y01Rank, yX1Rank);
x01Base |= xX1Base;
y01Base |= yX1Base;
x01Mask &= xX1Mask;
y01Mask &= yX1Mask;
slotsX1 = null;
slotCountX1 = 0;
if (slotCount11 > 0) {
System.arraycopy(slots11, 0, slots01, slotCount01, slotCount11);
slotCount01 += slotCount11;
x01Rank = Math.max(x01Rank, x11Rank);
y01Rank = Math.max(y01Rank, y11Rank);
x01Base |= x11Base;
y01Base |= y11Base;
x01Mask &= x11Mask;
y01Mask &= y11Mask;
slots11 = null;
slotCount11 = 0;
}
}
if (slotCountX0 > 0 && (slotCount00 == 0 || slotCount10 == 0)) {
if (slots00 != null) {
System.arraycopy(slotsX0, 0, slots00, slotCount00, slotCountX0);
} else {
slots00 = slotsX0;
}
slotCount00 += slotCountX0;
x00Rank = Math.max(x00Rank, xX0Rank);
y00Rank = Math.max(y00Rank, yX0Rank);
x00Base |= xX0Base;
y00Base |= yX0Base;
x00Mask &= xX0Mask;
y00Mask &= yX0Mask;
slotsX0 = null;
slotCountX0 = 0;
if (slotCount10 > 0) {
System.arraycopy(slots10, 0, slots00, slotCount00, slotCount10);
slotCount00 += slotCount10;
x00Rank = Math.max(x00Rank, x10Rank);
y00Rank = Math.max(y00Rank, y10Rank);
x00Base |= x10Base;
y00Base |= y10Base;
x00Mask &= x10Mask;
y00Mask &= y10Mask;
slots10 = null;
slotCount10 = 0;
}
}
if (slotsX0 != null) {
if (slotsXY == null) {
slotsXY = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
System.arraycopy(slotsX0, 0, slotsXY, slotCountXY, slotCountX0);
slotCountXY += slotCountX0;
slotsX0 = null;
slotCountX0 = 0;
}
if (slotsX1 != null) {
if (slotsXY == null) {
slotsXY = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
System.arraycopy(slotsX1, 0, slotsXY, slotCountXY, slotCountX1);
slotCountXY += slotCountX1;
slotsX1 = null;
slotCountX1 = 0;
}
x00Mask ^= x00Base;
y00Mask ^= y00Base;
x01Mask ^= x01Base;
y01Mask ^= y01Base;
x10Mask ^= x10Base;
y10Mask ^= y10Base;
x11Mask ^= x11Base;
y11Mask ^= y11Base;
x00Rank = Math.max(x00Rank, 64 - Long.numberOfLeadingZeros(x00Mask));
y00Rank = Math.max(y00Rank, 64 - Long.numberOfLeadingZeros(y00Mask));
x01Rank = Math.max(x01Rank, 64 - Long.numberOfLeadingZeros(x01Mask));
y01Rank = Math.max(y01Rank, 64 - Long.numberOfLeadingZeros(y01Mask));
x10Rank = Math.max(x10Rank, 64 - Long.numberOfLeadingZeros(x10Mask));
y10Rank = Math.max(y10Rank, 64 - Long.numberOfLeadingZeros(y10Mask));
x11Rank = Math.max(x11Rank, 64 - Long.numberOfLeadingZeros(x11Mask));
y11Rank = Math.max(y11Rank, 64 - Long.numberOfLeadingZeros(y11Mask));
long x00 = BitInterval.from(x00Rank, x00Base);
long y00 = BitInterval.from(y00Rank, y00Base);
long x01 = BitInterval.from(x01Rank, x01Base);
long y01 = BitInterval.from(y01Rank, y01Base);
long x10 = BitInterval.from(x10Rank, x10Base);
long y10 = BitInterval.from(y10Rank, y10Base);
final long x11 = BitInterval.from(x11Rank, x11Base);
final long y11 = BitInterval.from(y11Rank, y11Base);
if (slotCount11 > 0 && slotCount01 > 0 && BitInterval.compare(x11, y11, x01, y01) == 0) {
// Merge tile 11 into tile 01
System.arraycopy(slots11, 0, slots01, slotCount01, slotCount11);
slotCount01 += slotCount11;
x01 = BitInterval.union(x01, x11);
y01 = BitInterval.union(y01, y11);
slots11 = null;
slotCount11 = 0;
}
if (slotCount11 > 0 && slotCount10 > 0 && BitInterval.compare(x11, y11, x10, y10) == 0) {
// Merge tile 11 into tile 10
System.arraycopy(slots11, 0, slots10, slotCount10, slotCount11);
slotCount10 += slotCount11;
x10 = BitInterval.union(x10, x11);
y10 = BitInterval.union(y10, y11);
slots11 = null;
slotCount11 = 0;
}
if (slotCount11 > 0 && slotCount00 > 0 && BitInterval.compare(x11, y11, x00, y00) == 0) {
// Merge tile 11 into tile 00
System.arraycopy(slots11, 0, slots00, slotCount00, slotCount11);
slotCount00 += slotCount11;
x00 = BitInterval.union(x00, x11);
y00 = BitInterval.union(y00, y11);
slots11 = null;
slotCount11 = 0;
}
if (slotCount01 > 0 && slotCount00 > 0 && BitInterval.compare(x01, y01, x00, y00) == 0) {
// Merge tile 01 into tile 00
System.arraycopy(slots01, 0, slots00, slotCount00, slotCount01);
slotCount00 += slotCount01;
x00 = BitInterval.union(x00, x01);
y00 = BitInterval.union(y00, y01);
slots01 = null;
slotCount01 = 0;
}
if (slotCount01 > 0 && slotCount10 > 0 && BitInterval.compare(x01, y01, x10, y10) == 0) {
// Merge tile 01 into tile 10
System.arraycopy(slots01, 0, slots10, slotCount10, slotCount01);
slotCount10 += slotCount01;
x10 = BitInterval.union(x10, x01);
y10 = BitInterval.union(y10, y01);
slots01 = null;
slotCount01 = 0;
}
if (slotCount10 > 0 && slotCount00 > 0 && BitInterval.compare(x10, y10, x00, y00) == 0) {
// Merge tile 10 into tile 00
System.arraycopy(slots10, 0, slots00, slotCount00, slotCount10);
slotCount00 += slotCount10;
x00 = BitInterval.union(x00, x10);
y00 = BitInterval.union(y00, y10);
slots10 = null;
slotCount10 = 0;
}
int pageRefCount = 0;
if (slotCount00 > 0) {
pageRefCount += 1;
}
if (slotCount01 > 0) {
pageRefCount += 1;
}
if (slotCount10 > 0) {
pageRefCount += 1;
}
if (slotCount11 > 0) {
pageRefCount += 1;
}
final QTreePage<K, S, V>[] pages = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageRefCount];
int pageRefOffset = 0;
if (slotCount00 > 0) {
if (slotCount00 < slotCount) {
final QTreeEntry<K, S, V>[] newSlots00 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount00];
System.arraycopy(slots00, 0, newSlots00, 0, slotCount00);
slots00 = newSlots00;
}
Arrays.sort(slots00, tree);
pages[pageRefOffset] = new QTreeLeaf<K, S, V>(slots00, x00, y00);
pageRefOffset += 1;
}
if (slotCount01 > 0) {
if (slotCount01 < slotCount) {
final QTreeEntry<K, S, V>[] newSlots01 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount01];
System.arraycopy(slots01, 0, newSlots01, 0, slotCount01);
slots01 = newSlots01;
}
Arrays.sort(slots01, tree);
pages[pageRefOffset] = new QTreeLeaf<K, S, V>(slots01, x01, y01);
pageRefOffset += 1;
}
if (slotCount10 > 0) {
if (slotCount10 < slotCount) {
final QTreeEntry<K, S, V>[] newSlots10 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount10];
System.arraycopy(slots10, 0, newSlots10, 0, slotCount10);
slots10 = newSlots10;
}
Arrays.sort(slots10, tree);
pages[pageRefOffset] = new QTreeLeaf<K, S, V>(slots10, x10, y10);
pageRefOffset += 1;
}
if (slotCount11 > 0) {
if (slotCount11 < slotCount) {
final QTreeEntry<K, S, V>[] newSlots11 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount11];
System.arraycopy(slots11, 0, newSlots11, 0, slotCount11);
slots11 = newSlots11;
}
Arrays.sort(slots11, tree);
pages[pageRefOffset] = new QTreeLeaf<K, S, V>(slots11, x11, y11);
pageRefOffset += 1;
}
Arrays.sort(pages, PAGE_ORDERING);
if (slotCountXY == 0) {
slotsXY = (QTreeEntry<K, S, V>[]) EMPTY_SLOTS;
} else if (slotCountXY < slotCount) {
final QTreeEntry<K, S, V>[] newSlotsXY = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCountXY];
System.arraycopy(slotsXY, 0, newSlotsXY, 0, slotCountXY);
slotsXY = newSlotsXY;
}
Arrays.sort(slotsXY, tree);
return QTreeNode.create(pages, slotsXY, this.slots.length);
}
@Override
public Cursor<QTreeEntry<K, S, V>> cursor(long x, long y) {
return new QTreeLeafCursor<K, S, V>(this, x, y);
}
private int lookup(K key, QTreeContext<K, S, V> tree) {
final QTreeEntry<K, S, V>[] slots = this.slots;
int low = 0;
int high = slots.length - 1;
while (low <= high) {
final int mid = (low + high) >>> 1;
final int order = tree.compareKey(key, slots[mid].key);
if (order > 0) {
low = mid + 1;
} else if (order < 0) {
high = mid - 1;
} else {
return mid;
}
}
return -(low + 1);
}
public static <K, S, V> QTreeLeaf<K, S, V> create(QTreeEntry<K, S, V>[] slots) {
int xRank = 0;
int yRank = 0;
long xBase = 0L;
long yBase = 0L;
long xMask = -1L;
long yMask = -1L;
for (int i = 0, n = slots.length; i < n; i += 1) {
final QTreeEntry<K, S, V> slot = slots[i];
final long xt = slot.x;
final long yt = slot.y;
final int xtRank = Long.numberOfLeadingZeros(~xt);
final int ytRank = Long.numberOfLeadingZeros(~yt);
final long xtBase = xt << xtRank;
final long ytBase = yt << ytRank;
xRank = Math.max(xRank, xtRank);
yRank = Math.max(yRank, ytRank);
xBase |= xtBase;
yBase |= ytBase;
xMask &= xtBase;
yMask &= ytBase;
}
xMask ^= xBase;
yMask ^= yBase;
xRank = Math.max(xRank, 64 - Long.numberOfLeadingZeros(xMask));
yRank = Math.max(yRank, 64 - Long.numberOfLeadingZeros(yMask));
xMask = ~((1L << xRank) - 1L);
yMask = ~((1L << yRank) - 1L);
xBase &= xMask;
yBase &= yMask;
final long x = BitInterval.from(xRank, xBase);
final long y = BitInterval.from(yRank, yBase);
return new QTreeLeaf<K, S, V>(slots, x, y);
}
private static QTreeLeaf<Object, Object, Object> empty;
@SuppressWarnings("unchecked")
public static <K, S, V> QTreeLeaf<K, S, V> empty() {
if (empty == null) {
empty = new QTreeLeaf<Object, Object, Object>((QTreeEntry<Object, Object, Object>[]) EMPTY_SLOTS, -1L, -1L);
}
return (QTreeLeaf<K, S, V>) empty;
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreeLeafCursor.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.NoSuchElementException;
import swim.util.Cursor;
final class QTreeLeafCursor<K, S, V> implements Cursor<QTreeEntry<K, S, V>> {
final QTreeLeaf<K, S, V> page;
final long x;
final long y;
int index;
QTreeLeafCursor(QTreeLeaf<K, S, V> page, long x, long y, int index) {
this.page = page;
this.x = x;
this.y = y;
this.index = index;
}
QTreeLeafCursor(QTreeLeaf<K, S, V> page, long x, long y) {
this(page, x, y, 0);
}
@Override
public boolean isEmpty() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.index < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.index];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return false;
}
}
return true;
}
@Override
public QTreeEntry<K, S, V> head() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.index < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.index];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return slot;
}
}
throw new NoSuchElementException();
}
@Override
public void step() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.index < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.index];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
this.index += 1;
return;
}
}
throw new UnsupportedOperationException();
}
@Override
public void skip(long count) {
if (count < 0L) {
throw new IllegalArgumentException();
}
this.index = Math.min(this.index + (int) count, this.page.slots.length);
}
@Override
public boolean hasNext() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.index < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.index];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return true;
}
this.index += 1;
}
return false;
}
@Override
public long nextIndexLong() {
return (long) nextIndex();
}
@Override
public int nextIndex() {
return this.index;
}
@Override
public QTreeEntry<K, S, V> next() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.index < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.index];
this.index += 1;
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return slot;
}
}
throw new NoSuchElementException();
}
@Override
public boolean hasPrevious() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.index > 0) {
final QTreeEntry<K, S, V> slot = slots[this.index - 1];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return true;
}
this.index -= 1;
}
return false;
}
@Override
public long previousIndexLong() {
return (long) previousIndex();
}
@Override
public int previousIndex() {
return this.index - 1;
}
@Override
public QTreeEntry<K, S, V> previous() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.index > 0) {
final QTreeEntry<K, S, V> slot = slots[this.index - 1];
this.index -= 1;
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return slot;
}
}
throw new NoSuchElementException();
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreeMap.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Comparator;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.math.Z2Form;
import swim.util.Cursor;
import swim.util.Murmur3;
public class QTreeMap<K, S, V> extends QTreeContext<K, S, V> implements SpatialMap<K, S, V>, Comparator<QTreeEntry<K, S, V>>, Cloneable, Debug {
final Z2Form<S> shapeForm;
volatile QTreePage<K, S, V> root;
protected QTreeMap(Z2Form<S> shapeForm, QTreePage<K, S, V> root) {
this.shapeForm = shapeForm;
this.root = root;
}
public QTreeMap(Z2Form<S> shapeForm) {
this(shapeForm, QTreePage.<K, S, V>empty());
}
public Z2Form<S> shapeForm() {
return this.shapeForm;
}
@Override
public boolean isEmpty() {
return this.root.isEmpty();
}
@Override
public int size() {
return (int) this.root.span();
}
@Override
public boolean containsKey(K key, S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
return this.root.containsKey(key, x, y, this);
}
@Override
public boolean containsKey(Object key) {
final Cursor<QTreeEntry<K, S, V>> cursor = this.root.cursor();
while (cursor.hasNext()) {
if (key.equals(cursor.next().key)) {
return true;
}
}
return false;
}
@Override
public boolean containsValue(Object value) {
final Cursor<QTreeEntry<K, S, V>> cursor = this.root.cursor();
while (cursor.hasNext()) {
if (value.equals(cursor.next().value)) {
return true;
}
}
return false;
}
@Override
public V get(K key, S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
return this.root.get(key, x, y, this);
}
@Override
public V get(Object key) {
final Cursor<QTreeEntry<K, S, V>> cursor = this.root.cursor();
while (cursor.hasNext()) {
final QTreeEntry<K, S, V> slot = cursor.next();
if (key.equals(slot.key)) {
return slot.value;
}
}
return null;
}
@Override
public V put(K key, S shape, V newValue) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
do {
final QTreePage<K, S, V> oldRoot = this.root;
final QTreePage<K, S, V> newRoot = oldRoot.updated(key, shape, x, y, newValue, this)
.balanced(this);
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return oldRoot.get(key, x, y, this);
}
} else {
return null;
}
} while (true);
}
@Override
public V move(K key, S oldShape, S newShape, V newValue) {
final Z2Form<S> shapeForm = this.shapeForm;
final long oldX = BitInterval.span(shapeForm.getXMin(oldShape), shapeForm.getXMax(oldShape));
final long oldY = BitInterval.span(shapeForm.getYMin(oldShape), shapeForm.getYMax(oldShape));
final long newX = BitInterval.span(shapeForm.getXMin(newShape), shapeForm.getXMax(newShape));
final long newY = BitInterval.span(shapeForm.getYMin(newShape), shapeForm.getYMax(newShape));
do {
final QTreePage<K, S, V> oldRoot = this.root;
final QTreePage<K, S, V> newRoot = oldRoot.removed(key, oldX, oldY, this)
.balanced(this)
.updated(key, newShape, newX, newY, newValue, this)
.balanced(this);
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return oldRoot.get(key, oldX, oldY, this);
}
} else {
return null;
}
} while (true);
}
@Override
public V remove(K key, S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
do {
final QTreePage<K, S, V> oldRoot = this.root;
final QTreePage<K, S, V> newRoot = oldRoot.removed(key, x, y, this)
.balanced(this);
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return oldRoot.get(key, x, y, this);
}
} else {
return null;
}
} while (true);
}
@Override
public void clear() {
this.root = QTreePage.empty();
}
public QTreeMap<K, S, V> updated(K key, S shape, V newValue) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
final QTreePage<K, S, V> oldRoot = this.root;
QTreePage<K, S, V> newRoot = oldRoot.updated(key, shape, x, y, newValue, this);
if (oldRoot != newRoot) {
if (newRoot.span() > oldRoot.span()) {
newRoot = newRoot.balanced(this);
}
return copy(newRoot);
} else {
return this;
}
}
public QTreeMap<K, S, V> removed(K key, S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
final QTreePage<K, S, V> oldRoot = this.root;
QTreePage<K, S, V> newRoot = oldRoot.removed(key, x, y, this);
if (oldRoot != newRoot) {
newRoot = newRoot.balanced(this);
return copy(newRoot);
} else {
return this;
}
}
@Override
public Cursor<Entry<K, S, V>> iterator(S shape) {
final Z2Form<S> shapeForm = this.shapeForm;
final long x = BitInterval.span(shapeForm.getXMin(shape), shapeForm.getXMax(shape));
final long y = BitInterval.span(shapeForm.getYMin(shape), shapeForm.getYMax(shape));
return new QTreeShapeCursor<K, S, V>(this.root.cursor(x, y), shapeForm, shape);
}
@SuppressWarnings("unchecked")
@Override
public Cursor<Entry<K, S, V>> iterator() {
return (Cursor<Entry<K, S, V>>) (Cursor<?>) this.root.cursor();
}
@Override
public Cursor<K> keyIterator() {
return Cursor.keys(this.root.cursor());
}
@Override
public Cursor<V> valueIterator() {
return Cursor.values(this.root.cursor());
}
public SpatialMap<K, S, V> snapshot() {
return new QTree<K, S, V>(this.shapeForm, this.root);
}
@Override
public QTreeMap<K, S, V> clone() {
return copy(this.root);
}
protected QTreeMap<K, S, V> copy(QTreePage<K, S, V> root) {
return new QTreeMap<K, S, V>(this.shapeForm, root);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof QTreeMap<?, ?, ?>) {
final QTreeMap<K, S, V> that = (QTreeMap<K, S, V>) other;
if (size() == that.size()) {
final Cursor<Entry<K, S, V>> those = that.iterator();
while (those.hasNext()) {
final Entry<K, S, V> entry = those.next();
final V value = get(entry.getKey());
final V v = entry.getValue();
if (value == null ? v != null : !value.equals(v)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(QTree.class);
}
int a = 0;
int b = 0;
int c = 1;
final Cursor<Entry<K, S, V>> these = iterator();
while (these.hasNext()) {
final Entry<K, S, V> entry = these.next();
final int h = Murmur3.mix(Murmur3.hash(entry.getKey()), Murmur3.hash(entry.getValue()));
a ^= h;
b += h;
if (h != 0) {
c *= h;
}
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, a), b), c));
}
@Override
public void debug(Output<?> output) {
output = output.write("QTree").write('.').write("empty").write('(')
.debug(this.shapeForm).write(')');
for (Entry<K, S, V> entry : this) {
output = output.write('.').write("updated").write('(')
.debug(entry.getKey()).write(", ")
.debug(entry.getShape()).write(", ")
.debug(entry.getValue()).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
@SuppressWarnings("rawtypes")
public static <K, S, V> QTreeMap<K, S, V> empty(Z2Form<S> shapeForm) {
return new QTreeMap<K, S, V>(shapeForm);
}
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<QTreeMap, QTreePage> ROOT =
AtomicReferenceFieldUpdater.newUpdater(QTreeMap.class, QTreePage.class, "root");
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreeNode.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Arrays;
import swim.util.Cursor;
final class QTreeNode<K, S, V> extends QTreePage<K, S, V> {
final QTreePage<K, S, V>[] pages;
final QTreeEntry<K, S, V>[] slots;
final long x;
final long y;
final long span;
QTreeNode(QTreePage<K, S, V>[] pages, QTreeEntry<K, S, V>[] slots, long x, long y, long span) {
this.pages = pages;
this.slots = slots;
this.x = x;
this.y = y;
this.span = span;
}
@Override
public boolean isEmpty() {
return this.span == 0L;
}
@Override
public long span() {
return this.span;
}
@Override
public int arity() {
return this.pages.length + this.slots.length;
}
@Override
public QTreePage<K, S, V> getPage(int index) {
return this.pages[index];
}
@Override
public int slotCount() {
return this.slots.length;
}
@Override
public QTreeEntry<K, S, V> getSlot(int index) {
return this.slots[index];
}
@Override
public long x() {
return this.x;
}
@Override
public int xRank() {
return Long.numberOfLeadingZeros(~this.x);
}
@Override
public long xBase() {
return this.x << xRank();
}
@Override
public long xMask() {
return ~((1L << xRank()) - 1L);
}
@Override
public long xSplit() {
return this.x << 1 & 1L;
}
@Override
public long y() {
return this.y;
}
@Override
public int yRank() {
return Long.numberOfLeadingZeros(~this.y);
}
@Override
public long yBase() {
return this.y << yRank();
}
@Override
public long yMask() {
return ~((1L << yRank()) - 1L);
}
@Override
public long ySplit() {
return this.y << 1 & 1L;
}
@Override
public boolean containsKey(K key, long xk, long yk, QTreeContext<K, S, V> tree) {
final int xRank = Long.numberOfLeadingZeros(~this.x);
final int yRank = Long.numberOfLeadingZeros(~this.y);
final int xkRank = Long.numberOfLeadingZeros(~xk);
final int ykRank = Long.numberOfLeadingZeros(~yk);
if (xkRank <= xRank && ykRank <= yRank) {
final int i = scan(xk, yk);
//final int i = lookup(xk, yk);
if (i >= 0) {
final QTreePage<K, S, V> page = this.pages[i];
if (xkRank <= page.xRank() && ykRank <= page.yRank()) {
if (page.containsKey(key, xk, yk, tree)) {
return true;
}
}
}
return lookup(key, tree) >= 0;
}
return false;
}
@Override
public V get(K key, long xk, long yk, QTreeContext<K, S, V> tree) {
final int xRank = Long.numberOfLeadingZeros(~this.x);
final int yRank = Long.numberOfLeadingZeros(~this.y);
final int xkRank = Long.numberOfLeadingZeros(~xk);
final int ykRank = Long.numberOfLeadingZeros(~yk);
if (xkRank <= xRank && ykRank <= yRank) {
int i = scan(xk, yk);
//int i = lookup(xk, yk);
if (i >= 0) {
final QTreePage<K, S, V> page = this.pages[i];
if (xkRank <= page.xRank() && ykRank <= page.yRank()) {
final V value = page.get(key, xk, yk, tree);
if (value != null) {
return value;
}
}
}
i = lookup(key, tree);
if (i >= 0) {
return this.slots[i].value;
}
}
return null;
}
@Override
QTreeNode<K, S, V> updated(K key, S shape, long xk, long yk, V newValue,
QTreeContext<K, S, V> tree, boolean canSplit) {
final QTreePage<K, S, V>[] pages = this.pages;
final int n = pages.length;
final int j = lookup(xk, yk);
final int i = j >= 0 ? j : -(j + 1);
final QTreePage<K, S, V> oldPage = pages[i];
final QTreePage<K, S, V> newPage = oldPage.updated(key, shape, xk, yk, newValue, tree);
if (oldPage.x() == newPage.x() && oldPage.y() == newPage.y()) {
if (canSplit && oldPage.span() != newPage.span() && tree.pageShouldSplit(newPage)) {
return updatedPageSplit(i, newPage, oldPage, tree);
} else {
return updatedPage(i, newPage, oldPage);
}
} else {
return coalescePage(this, i, newPage, oldPage, tree);
}
}
QTreeNode<K, S, V> coalescePage(QTreeNode<K, S, V> basePage, int i, QTreePage<K, S, V> newPage,
QTreePage<K, S, V> oldPage, QTreeContext<K, S, V> tree) {
do {
basePage = basePage.removedPage(i, oldPage);
int j = basePage.scan(newPage.x(), newPage.y());
//int j = basePage.lookup(newPage.x(), newPage.y());
if (j < 0) {
j = -(j + 1);
return basePage.insertedPage(j, newPage).reinsertedSlots(tree);
} else {
i = j;
oldPage = basePage.getPage(i);
newPage = oldPage.mergedPage(newPage, tree);
}
} while (true);
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> updatedPage(int i, QTreePage<K, S, V> newPage, QTreePage<K, S, V> oldPage) {
final QTreePage<K, S, V>[] oldPages = this.pages;
final int n = oldPages.length;
final QTreePage<K, S, V>[] newPages = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, 0, newPages, 0, n);
newPages[i] = newPage;
Arrays.sort(newPages, PAGE_ORDERING);
final long newSpan = this.span - oldPage.span() + newPage.span();
return QTreeNode.create(newPages, this.slots, newSpan);
}
QTreeNode<K, S, V> updatedPageSplit(int i, QTreePage<K, S, V> newPage,
QTreePage<K, S, V> oldPage, QTreeContext<K, S, V> tree) {
QTreeNode<K, S, V> page = removedPage(i, oldPage);
final QTreeNode<K, S, V> midPage = (QTreeNode<K, S, V>) newPage.split(tree);
final QTreePage<K, S, V>[] midPages = midPage.pages;
final int midArity = midPages.length;
if (midArity <= 1) {
return updatedPage(i, newPage, oldPage);
}
for (int j = 0; j < midArity; j += 1) {
page = page.insertedPage(midPages[j], tree);
}
return page.mergedSlots(midPage.slots, tree);
}
QTreeNode<K, S, V> updatedPageMerge(int i, QTreeNode<K, S, V> newPage,
QTreePage<K, S, V> oldPage, QTreeContext<K, S, V> tree) {
QTreeNode<K, S, V> page = removedPage(i, oldPage);
final QTreePage<K, S, V>[] newPages = newPage.pages;
for (int j = 0, pageCount = newPages.length; j < pageCount; j += 1) {
page = page.insertedPage(newPages[j], tree);
}
final QTreeEntry<K, S, V>[] newSlots = newPage.slots;
for (int j = 0, slotCount = newSlots.length; j < slotCount; j += 1) {
page = page.updatedSlot(newSlots[j], tree);
}
return page;
}
QTreeNode<K, S, V> mergedPage(QTreePage<K, S, V> newPage, QTreeContext<K, S, V> tree) {
QTreeNode<K, S, V> page = this;
if (newPage instanceof QTreeNode<?, ?, ?>) {
for (int i = 0, arity = newPage.arity(); i < arity; i += 1) {
page = page.insertedPage(newPage.getPage(i), tree);
}
}
for (int i = 0, slotCount = newPage.slotCount(); i < slotCount; i += 1) {
final QTreeEntry<K, S, V> slot = newPage.getSlot(i);
page = page.updated(slot.key, slot.shape, slot.x, slot.y, slot.value, tree, false);
}
return page;
}
@SuppressWarnings("unchecked")
@Override
QTreeNode<K, S, V> mergedSlots(QTreeEntry<K, S, V>[] midSlots, QTreeContext<K, S, V> tree) {
if (midSlots.length > 0) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[oldSlots.length + midSlots.length];
System.arraycopy(oldSlots, 0, newSlots, 0, oldSlots.length);
System.arraycopy(midSlots, 0, newSlots, oldSlots.length, midSlots.length);
Arrays.sort(newSlots, tree);
final long newSpan = this.span + midSlots.length;
return create(this.pages, newSlots, newSpan);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> reinsertedSlots(QTreeContext<K, S, V> tree) {
QTreeNode<K, S, V> page = this;
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final int oldSlotCount = oldSlots.length;
QTreeEntry<K, S, V>[] newSlots = null;
int newSlotCount = 0;
for (int i = 0; i < oldSlotCount; i += 1) {
final QTreeEntry<K, S, V> slot = oldSlots[i];
final long x = slot.x;
final long y = slot.y;
final int j = page.lookup(x, y);
if (j >= 0) {
// page will temporarily have two copies of slot,
// one in parent, and one in child
page = page.updated(slot.key, slot.shape, slot.x, slot.y, slot.value, tree, false);
if (newSlots == null) {
newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[oldSlotCount - 1];
System.arraycopy(oldSlots, 0, newSlots, 0, i);
newSlotCount = i;
}
} else if (newSlots != null) {
newSlots[newSlotCount] = slot;
newSlotCount += 1;
}
}
if (newSlots != null) {
if (newSlotCount == 0) {
newSlots = (QTreeEntry<K, S, V>[]) EMPTY_SLOTS;
} else if (newSlotCount < oldSlotCount - 1) {
final QTreeEntry<K, S, V>[] resizedSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[newSlotCount];
System.arraycopy(newSlots, 0, resizedSlots, 0, newSlotCount);
newSlots = resizedSlots;
}
return QTreeNode.create(page.pages, newSlots, this.span);
} else {
return page;
}
}
@Override
QTreeNode<K, S, V> insertedPage(QTreePage<K, S, V> newPage, QTreeContext<K, S, V> tree) {
int i = lookup(newPage.x(), newPage.y());
if (i < 0) {
i = -(i + 1);
return insertedPage(i, newPage);
} else {
return mergedPage(newPage, tree);
}
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> insertedPage(int i, QTreePage<K, S, V> newPage) {
final QTreePage<K, S, V>[] oldPages = this.pages;
final int n = oldPages.length + 1;
final QTreePage<K, S, V>[] newPages = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, 0, newPages, 0, i);
newPages[i] = newPage;
System.arraycopy(oldPages, i, newPages, i + 1, n - (i + 1));
Arrays.sort(newPages, PAGE_ORDERING);
final long newSpan = this.span + newPage.span();
return QTreeNode.create(newPages, this.slots, newSpan);
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> insertedSlot(int i, K key, S shape, long xk, long yk, V newValue) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final int n = oldSlots.length + 1;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, i);
newSlots[i] = new QTreeEntry<K, S, V>(key, shape, xk, yk, newValue);
System.arraycopy(oldSlots, i, newSlots, i + 1, n - (i + 1));
return QTreeNode.create(this.pages, newSlots, this.span + 1L);
}
QTreeNode<K, S, V> updatedSlot(K key, S shape, long xk, long yk, V newValue, QTreeContext<K, S, V> tree) {
return updatedSlot(new QTreeEntry<K, S, V>(key, shape, xk, yk, newValue), tree);
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> updatedSlot(int i, K key, S shape, long xk, long yk, V newValue) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final QTreeEntry<K, S, V> oldSlot = oldSlots[i];
final long oldX = oldSlot.x;
final long oldY = oldSlot.y;
if (!newValue.equals(oldSlot.value) || oldX != xk || oldY != yk) {
final int n = oldSlots.length;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, n);
newSlots[i] = new QTreeEntry<K, S, V>(key, shape, xk, yk, newValue);
return QTreeNode.create(this.pages, newSlots, this.span);
} else {
return this;
}
}
@Override
QTreeNode<K, S, V> updatedSlot(QTreeEntry<K, S, V> newSlot, QTreeContext<K, S, V> tree) {
int i = lookup(newSlot.key, tree);
if (i >= 0) {
return updatedSlot(i, newSlot);
} else {
i = -(i + 1);
return insertedSlot(i, newSlot);
}
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> updatedSlot(int i, QTreeEntry<K, S, V> newSlot) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final QTreeEntry<K, S, V> oldSlot = oldSlots[i];
if (!newSlot.equals(oldSlot)) {
final int n = oldSlots.length;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, n);
newSlots[i] = newSlot;
return QTreeNode.create(this.pages, newSlots, this.span);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> insertedSlot(int i, QTreeEntry<K, S, V> newSlot) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final int n = oldSlots.length + 1;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, i);
newSlots[i] = newSlot;
System.arraycopy(oldSlots, i, newSlots, i + 1, n - (i + 1));
return QTreeNode.create(this.pages, newSlots, this.span);
}
@Override
public QTreePage<K, S, V> removed(K key, long xk, long yk, QTreeContext<K, S, V> tree) {
final int xRank = Long.numberOfLeadingZeros(~this.x);
final int yRank = Long.numberOfLeadingZeros(~this.y);
final int xkRank = Long.numberOfLeadingZeros(~xk);
final int ykRank = Long.numberOfLeadingZeros(~yk);
if (xkRank <= xRank && ykRank <= yRank) {
int i = scan(xk, yk);
//int i = lookup(xk, yk);
if (i >= 0) {
final QTreePage<K, S, V> oldPage = this.pages[i];
final QTreePage<K, S, V> newPage = oldPage.removed(key, xk, yk, tree);
if (oldPage != newPage) {
return replacedPage(i, newPage, oldPage, tree);
}
}
i = lookup(key, tree);
if (i >= 0) {
return removedSlot(i);
}
}
return this;
}
QTreePage<K, S, V> replacedPage(int i, QTreePage<K, S, V> newPage,
QTreePage<K, S, V> oldPage, QTreeContext<K, S, V> tree) {
if (!newPage.isEmpty()) {
if (newPage instanceof QTreeNode<?, ?, ?> && tree.pageShouldMerge(newPage)) {
return updatedPageMerge(i, (QTreeNode<K, S, V>) newPage, oldPage, tree);
} else {
return updatedPage(i, newPage, oldPage);
}
} else if (this.pages.length > 2) {
return removedPage(i, oldPage);
} else if (this.pages.length > 1) {
final QTreePage<K, S, V> onlyChild;
if (i == 0) {
onlyChild = this.pages[1];
} else {
onlyChild = this.pages[0];
}
if (this.slots.length == 0) {
return onlyChild;
} else {
return onlyChild.mergedSlots(this.slots, tree);
}
} else if (this.slots.length > 0) {
return QTreeLeaf.create(this.slots);
} else {
return QTreeLeaf.empty();
}
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> removedPage(int i, QTreePage<K, S, V> oldPage) {
final QTreePage<K, S, V>[] oldPages = this.pages;
final int n = oldPages.length - 1;
final QTreePage<K, S, V>[] newPages = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, 0, newPages, 0, i);
System.arraycopy(oldPages, i + 1, newPages, i, n - i);
Arrays.sort(newPages, PAGE_ORDERING);
final long newSpan = this.span - oldPage.span();
return create(newPages, this.slots, newSpan);
}
@SuppressWarnings("unchecked")
QTreeNode<K, S, V> removedSlot(int i) {
final QTreeEntry<K, S, V>[] oldSlots = this.slots;
final int n = oldSlots.length - 1;
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, i);
System.arraycopy(oldSlots, i + 1, newSlots, i, n - i);
return create(this.pages, newSlots, this.span - 1L);
}
@Override
public QTreePage<K, S, V> flattened(QTreeContext<K, S, V> tree) {
final QTreePage<K, S, V>[] pages = this.pages;
final QTreeEntry<K, S, V>[] slots = this.slots;
if (pages.length > 1) {
return this;
} else if (pages.length == 1) {
final QTreePage<K, S, V> onlyChild = pages[0];
if (slots.length == 0) {
return onlyChild;
} else {
return onlyChild.mergedSlots(slots, tree);
}
} else if (slots.length > 0) {
return QTreeLeaf.create(slots);
} else {
return QTreeLeaf.empty();
}
}
@Override
public QTreeNode<K, S, V> balanced(QTreeContext<K, S, V> tree) {
if (this.pages.length > 1 && tree.pageShouldSplit(this)) {
return split(tree);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public QTreeNode<K, S, V> split(QTreeContext<K, S, V> tree) {
final long x = this.x;
final long y = this.y;
final int xRank = Long.numberOfLeadingZeros(~x);
final int yRank = Long.numberOfLeadingZeros(~y);
final int xnRank = Math.max(0, xRank - 1);
final int ynRank = Math.max(0, yRank - 1);
final long xnMask = ~((1L << xnRank) - 1L);
final long ynMask = ~((1L << ynRank) - 1L);
final long x0Base = x << xRank;
final long y0Base = y << yRank;
final long x1Base = x0Base | (1L << xnRank);
final long y1Base = y0Base | (1L << ynRank);
int x00Rank = 0;
int y00Rank = 0;
int x01Rank = 0;
int y01Rank = 0;
int x10Rank = 0;
int y10Rank = 0;
int x11Rank = 0;
int y11Rank = 0;
int xX0Rank = 0;
int yX0Rank = 0;
int xX1Rank = 0;
int yX1Rank = 0;
long x00Base = 0L;
long y00Base = 0L;
long x01Base = 0L;
long y01Base = 0L;
long x10Base = 0L;
long y10Base = 0L;
long x11Base = 0L;
long y11Base = 0L;
long xX0Base = 0L;
long yX0Base = 0L;
long xX1Base = 0L;
long yX1Base = 0L;
long x00Mask = -1L;
long y00Mask = -1L;
long x01Mask = -1L;
long y01Mask = -1L;
long x10Mask = -1L;
long y10Mask = -1L;
long x11Mask = -1L;
long y11Mask = -1L;
long xX0Mask = -1L;
long yX0Mask = -1L;
long xX1Mask = -1L;
long yX1Mask = -1L;
final QTreePage<K, S, V>[] pages = this.pages;
QTreePage<K, S, V>[] pages00 = null;
QTreePage<K, S, V>[] pages01 = null;
QTreePage<K, S, V>[] pages10 = null;
QTreePage<K, S, V>[] pages11 = null;
final int pageCount = pages.length;
int pageCount00 = 0;
int pageCount01 = 0;
int pageCount10 = 0;
int pageCount11 = 0;
long span00 = 0L;
long span01 = 0L;
long span10 = 0L;
long span11 = 0L;
for (int i = 0; i < pageCount; i += 1) {
final QTreePage<K, S, V> page = pages[i];
final long xc = page.x();
final long yc = page.y();
final int xcRank = Long.numberOfLeadingZeros(~xc);
final int ycRank = Long.numberOfLeadingZeros(~yc);
final long xcBase = xc << xcRank;
final long ycBase = yc << ycRank;
final long xcNorm = xcBase & xnMask;
final long ycNorm = ycBase & ynMask;
if (xcNorm == x0Base) {
if (ycNorm == y0Base) {
if (pages00 == null) {
pages00 = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCount];
}
pages00[pageCount00] = page;
pageCount00 += 1;
span00 += page.span();
x00Rank = Math.max(x00Rank, xcRank);
y00Rank = Math.max(y00Rank, ycRank);
x00Base |= xcBase;
y00Base |= ycBase;
x00Mask &= xcBase;
y00Mask &= ycBase;
} else {
if (pages01 == null) {
pages01 = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCount];
}
pages01[pageCount01] = page;
pageCount01 += 1;
span01 += page.span();
x01Rank = Math.max(x01Rank, xcRank);
y01Rank = Math.max(y01Rank, ycRank);
x01Base |= xcBase;
y01Base |= ycBase;
x01Mask &= xcBase;
y01Mask &= ycBase;
}
} else {
if (ycNorm == y0Base) {
if (pages10 == null) {
pages10 = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCount];
}
pages10[pageCount10] = page;
pageCount10 += 1;
span10 += page.span();
x10Rank = Math.max(x10Rank, xcRank);
y10Rank = Math.max(y10Rank, ycRank);
x10Base |= xcBase;
y10Base |= ycBase;
x10Mask &= xcBase;
y10Mask &= ycBase;
} else {
if (pages11 == null) {
pages11 = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCount];
}
pages11[pageCount11] = page;
pageCount11 += 1;
span11 += page.span();
x11Rank = Math.max(x11Rank, xcRank);
y11Rank = Math.max(y11Rank, ycRank);
x11Base |= xcBase;
y11Base |= ycBase;
x11Mask &= xcBase;
y11Mask &= ycBase;
}
}
}
final QTreeEntry<K, S, V>[] slots = this.slots;
QTreeEntry<K, S, V>[] slots00 = null;
QTreeEntry<K, S, V>[] slots01 = null;
QTreeEntry<K, S, V>[] slots10 = null;
QTreeEntry<K, S, V>[] slots11 = null;
QTreeEntry<K, S, V>[] slotsX0 = null;
QTreeEntry<K, S, V>[] slotsX1 = null;
QTreeEntry<K, S, V>[] slotsXY = null;
final int slotCount = slots.length;
int slotCount00 = 0;
int slotCount01 = 0;
int slotCount10 = 0;
int slotCount11 = 0;
int slotCountX0 = 0;
int slotCountX1 = 0;
int slotCountXY = 0;
for (int i = 0; i < slotCount; i += 1) {
final QTreeEntry<K, S, V> slot = slots[i];
final long xt = slot.x;
final long yt = slot.y;
final int xtRank = Long.numberOfLeadingZeros(~xt);
final int ytRank = Long.numberOfLeadingZeros(~yt);
final long xtBase = xt << xtRank;
final long ytBase = yt << ytRank;
final long xtNorm = xtBase & xnMask;
final long ytNorm = ytBase & ynMask;
if (xnRank > 0 && xtRank > xnRank) {
if (ynRank > 0 && ytRank > ynRank) {
slotsXY[slotCountXY] = slot;
slotCountXY += 1;
} else if (ytNorm == y0Base) {
if (slotsX0 == null) {
slotsX0 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slotsX0[slotCountX0] = slot;
slotCountX0 += 1;
xX0Rank = Math.max(xX0Rank, xtRank);
yX0Rank = Math.max(yX0Rank, ytRank);
xX0Base |= xtBase;
yX0Base |= ytBase;
xX0Mask &= xtBase;
yX0Mask &= ytBase;
} else {
if (slotsX1 == null) {
slotsX1 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slotsX1[slotCountX1] = slot;
slotCountX1 += 1;
xX1Rank = Math.max(xX1Rank, xtRank);
yX1Rank = Math.max(yX1Rank, ytRank);
xX1Base |= xtBase;
yX1Base |= ytBase;
xX1Mask &= xtBase;
yX1Mask &= ytBase;
}
} else if (xtNorm == x0Base) {
if (ytNorm == y0Base) {
if (slots00 == null) {
slots00 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slots00[slotCount00] = slot;
slotCount00 += 1;
span00 += 1L;
x00Rank = Math.max(x00Rank, xtRank);
y00Rank = Math.max(y00Rank, ytRank);
x00Base |= xtBase;
y00Base |= ytBase;
x00Mask &= xtBase;
y00Mask &= ytBase;
} else {
if (slots01 == null) {
slots01 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slots01[slotCount01] = slot;
slotCount01 += 1;
span01 += 1L;
x01Rank = Math.max(x01Rank, xtRank);
y01Rank = Math.max(y01Rank, ytRank);
x01Base |= xtBase;
y01Base |= ytBase;
x01Mask &= xtBase;
y01Mask &= ytBase;
}
} else {
if (ytNorm == y0Base) {
if (slots10 == null) {
slots10 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slots10[slotCount10] = slot;
slotCount10 += 1;
span10 += 1L;
x10Rank = Math.max(x10Rank, xtRank);
y10Rank = Math.max(y10Rank, ytRank);
x10Base |= xtBase;
y10Base |= ytBase;
x10Mask &= xtBase;
y10Mask &= ytBase;
} else {
if (slots11 == null) {
slots11 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
slots11[slotCount11] = slot;
slotCount11 += 1;
span11 += 1L;
x11Rank = Math.max(x11Rank, xtRank);
y11Rank = Math.max(y11Rank, ytRank);
x11Base |= xtBase;
y11Base |= ytBase;
x11Mask &= xtBase;
y11Mask &= ytBase;
}
}
}
x00Mask ^= x00Base;
y00Mask ^= y00Base;
x01Mask ^= x01Base;
y01Mask ^= y01Base;
x10Mask ^= x10Base;
y10Mask ^= y10Base;
x11Mask ^= x11Base;
y11Mask ^= y11Base;
xX0Mask ^= xX0Base;
yX0Mask ^= yX0Base;
xX1Mask ^= xX1Base;
yX1Mask ^= yX1Base;
x00Rank = Math.max(x00Rank, 64 - Long.numberOfLeadingZeros(x00Mask));
y00Rank = Math.max(y00Rank, 64 - Long.numberOfLeadingZeros(y00Mask));
x01Rank = Math.max(x01Rank, 64 - Long.numberOfLeadingZeros(x01Mask));
y01Rank = Math.max(y01Rank, 64 - Long.numberOfLeadingZeros(y01Mask));
x10Rank = Math.max(x10Rank, 64 - Long.numberOfLeadingZeros(x10Mask));
y10Rank = Math.max(y10Rank, 64 - Long.numberOfLeadingZeros(y10Mask));
x11Rank = Math.max(x11Rank, 64 - Long.numberOfLeadingZeros(x11Mask));
y11Rank = Math.max(y11Rank, 64 - Long.numberOfLeadingZeros(y11Mask));
xX0Rank = Math.max(xX0Rank, 64 - Long.numberOfLeadingZeros(xX0Mask));
yX0Rank = Math.max(yX0Rank, 64 - Long.numberOfLeadingZeros(yX0Mask));
xX1Rank = Math.max(xX1Rank, 64 - Long.numberOfLeadingZeros(xX1Mask));
yX1Rank = Math.max(yX1Rank, 64 - Long.numberOfLeadingZeros(yX1Mask));
long x00 = BitInterval.from(x00Rank, x00Base);
long y00 = BitInterval.from(y00Rank, y00Base);
long x01 = BitInterval.from(x01Rank, x01Base);
long y01 = BitInterval.from(y01Rank, y01Base);
long x10 = BitInterval.from(x10Rank, x10Base);
long y10 = BitInterval.from(y10Rank, y10Base);
final long x11 = BitInterval.from(x11Rank, x11Base);
final long y11 = BitInterval.from(y11Rank, y11Base);
final long xX0 = BitInterval.from(xX0Rank, xX0Base);
final long yX0 = BitInterval.from(yX0Rank, yX0Base);
final long xX1 = BitInterval.from(xX1Rank, xX1Base);
final long yX1 = BitInterval.from(yX1Rank, yX1Base);
if (pageCount11 > 0 && pageCount01 > 0 && BitInterval.compare(x11, y11, x01, y01) == 0) {
// Merge tile 11 into tile 01
System.arraycopy(pages11, 0, pages01, pageCount01, pageCount11);
pageCount01 += pageCount11;
span01 += span11;
if (slotCount11 > 0) {
if (slots01 == null) {
slots01 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
System.arraycopy(slots11, 0, slots01, slotCount01, slotCount11);
slotCount01 += slotCount11;
slots11 = null;
slotCount11 = 0;
}
x01 = BitInterval.union(x01, x11);
y01 = BitInterval.union(y01, y11);
pages11 = null;
pageCount11 = 0;
span11 = 0L;
}
if (pageCount01 > 0 && pageCount00 > 0 && BitInterval.compare(x01, y01, x00, y00) == 0) {
// Merge tile 01 into tile 00
System.arraycopy(pages01, 0, pages00, pageCount00, pageCount01);
pageCount00 += pageCount01;
span00 += span01;
if (slotCount01 > 0) {
if (slots00 == null) {
slots00 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
System.arraycopy(slots01, 0, slots00, slotCount00, slotCount01);
slotCount00 += slotCount01;
slots01 = null;
slotCount01 = 0;
}
x00 = BitInterval.union(x00, x01);
y00 = BitInterval.union(y00, y01);
pages01 = null;
pageCount01 = 0;
span01 = 0L;
}
if (pageCount01 > 0 && pageCount10 > 0 && BitInterval.compare(x01, y01, x10, y10) == 0) {
// Merge tile 01 into tile 10
System.arraycopy(pages01, 0, pages10, pageCount10, pageCount01);
pageCount10 += pageCount01;
span10 += span01;
if (slotCount01 > 0) {
if (slots10 == null) {
slots10 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
System.arraycopy(slots01, 0, slots10, slotCount10, slotCount01);
slotCount10 += slotCount01;
slots01 = null;
slotCount01 = 0;
}
x10 = BitInterval.union(x10, x01);
y10 = BitInterval.union(y10, y01);
pages01 = null;
pageCount01 = 0;
span01 = 0L;
}
if (pageCount10 > 0 && pageCount00 > 0 && BitInterval.compare(x10, y10, x00, y00) == 0) {
// Merge tile 10 into tile 00
System.arraycopy(pages10, 0, pages00, pageCount00, pageCount10);
pageCount00 += pageCount10;
span00 += span10;
if (slotCount10 > 0) {
if (slots00 == null) {
slots00 = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
System.arraycopy(slots10, 0, slots00, slotCount00, slotCount10);
slotCount00 += slotCount10;
slots10 = null;
slotCount10 = 0;
}
x00 = BitInterval.union(x00, x10);
y00 = BitInterval.union(y00, y10);
pages10 = null;
pageCount10 = 0;
span10 = 0L;
}
if (slotCountX1 > 0 && BitInterval.compare(xX1, yX1, x01, y01) == 0) {
if (slots01 != null) {
System.arraycopy(slotsX1, 0, slots01, slotCount01, slotCountX1);
} else {
slots01 = slotsX1;
}
slotCount01 += slotCountX1;
span01 += slotCountX1;
x01 = BitInterval.union(x01, xX1);
y01 = BitInterval.union(y01, yX1);
slotsX1 = null;
slotCountX1 = 0;
}
if (slotCountX0 > 0 && BitInterval.compare(xX0, yX0, x00, y00) == 0) {
if (slots00 != null) {
System.arraycopy(slotsX0, 0, slots00, slotCount00, slotCountX0);
} else {
slots00 = slotsX0;
}
slotCount00 += slotCountX0;
span00 += slotCountX0;
x00 = BitInterval.union(x00, xX0);
y00 = BitInterval.union(y00, yX0);
slotsX0 = null;
slotCountX0 = 0;
}
if (slotsX0 != null) {
if (slotsXY == null) {
slotsXY = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
System.arraycopy(slotsX0, 0, slotsXY, slotCountXY, slotCountX0);
slotCountXY += slotCountX0;
slotsX0 = null;
slotCountX0 = 0;
}
if (slotsX1 != null) {
if (slotsXY == null) {
slotsXY = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount];
}
System.arraycopy(slotsX1, 0, slotsXY, slotCountXY, slotCountX1);
slotCountXY += slotCountX1;
slotsX1 = null;
slotCountX1 = 0;
}
int pageCountXY = 0;
if (pageCount00 > 0 || slotCount00 > 0) {
pageCountXY += 1;
}
if (pageCount01 > 0 || slotCount01 > 0) {
pageCountXY += 1;
}
if (pageCount10 > 0 || slotCount10 > 0) {
pageCountXY += 1;
}
if (pageCount11 > 0 || slotCount11 > 0) {
pageCountXY += 1;
}
final QTreePage<K, S, V>[] pagesXY = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCountXY];
int pageOffsetXY = 0;
if (pageCount00 > 0 || slotCount00 > 0) {
if (pageCount00 < pageCount) {
final QTreePage<K, S, V>[] newPages = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCount00];
System.arraycopy(pages00, 0, newPages, 0, pageCount00);
pages00 = newPages;
}
if (slotCount00 == 0) {
slots00 = (QTreeEntry<K, S, V>[]) EMPTY_SLOTS;
} else if (slotCount00 < slotCount) {
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount00];
System.arraycopy(slots00, 0, newSlots, 0, slotCount00);
slots00 = newSlots;
}
if (pageCount00 > 1 || pageCount00 == 1 && slotCount00 > 0) {
Arrays.sort(pages00, PAGE_ORDERING);
Arrays.sort(slots00, tree);
pagesXY[pageOffsetXY] = new QTreeNode<K, S, V>(pages00, slots00, x00, y00, span00);
} else if (slotCount00 == 0) {
pagesXY[pageOffsetXY] = pages00[0];
} else {
Arrays.sort(slots00, tree);
pagesXY[pageOffsetXY] = QTreeLeaf.create(slots00);
}
pageOffsetXY += 1;
}
if (pageCount01 > 0 || slotCount01 > 0) {
if (pageCount01 < pageCount) {
final QTreePage<K, S, V>[] newPages = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCount01];
System.arraycopy(pages01, 0, newPages, 0, pageCount01);
pages01 = newPages;
}
if (slotCount01 == 0) {
slots01 = (QTreeEntry<K, S, V>[]) EMPTY_SLOTS;
} else if (slotCount01 < slotCount) {
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount01];
System.arraycopy(slots01, 0, newSlots, 0, slotCount01);
slots01 = newSlots;
}
if (pageCount01 > 1 || pageCount01 == 1 && slotCount01 > 0) {
Arrays.sort(pages01, PAGE_ORDERING);
Arrays.sort(slots01, tree);
pagesXY[pageOffsetXY] = new QTreeNode<K, S, V>(pages01, slots01, x01, y01, span01);
} else if (slotCount01 == 0) {
pagesXY[pageOffsetXY] = pages01[0];
} else {
Arrays.sort(slots01, tree);
pagesXY[pageOffsetXY] = QTreeLeaf.create(slots01);
}
pageOffsetXY += 1;
}
if (pageCount10 > 0 || slotCount10 > 0) {
if (pageCount10 < pageCount) {
final QTreePage<K, S, V>[] newPages = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCount10];
System.arraycopy(pages10, 0, newPages, 0, pageCount10);
pages10 = newPages;
}
if (slotCount10 == 0) {
slots10 = (QTreeEntry<K, S, V>[]) EMPTY_SLOTS;
} else if (slotCount10 < slotCount) {
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount10];
System.arraycopy(slots10, 0, newSlots, 0, slotCount10);
slots10 = newSlots;
}
if (pageCount10 > 1 || pageCount10 == 1 && slotCount10 > 0) {
Arrays.sort(pages10, PAGE_ORDERING);
Arrays.sort(slots10, tree);
pagesXY[pageOffsetXY] = new QTreeNode<K, S, V>(pages10, slots10, x10, y10, span10);
} else if (slotCount10 == 0) {
pagesXY[pageOffsetXY] = pages10[0];
} else {
Arrays.sort(slots10, tree);
pagesXY[pageOffsetXY] = QTreeLeaf.create(slots10);
}
pageOffsetXY += 1;
}
if (pageCount11 > 0 || slotCount11 > 0) {
if (pageCount11 < pageCount) {
final QTreePage<K, S, V>[] newPages = (QTreePage<K, S, V>[]) new QTreePage<?, ?, ?>[pageCount11];
System.arraycopy(pages11, 0, newPages, 0, pageCount11);
pages11 = newPages;
}
if (slotCount11 == 0) {
slots11 = (QTreeEntry<K, S, V>[]) EMPTY_SLOTS;
} else if (slotCount11 < slotCount) {
final QTreeEntry<K, S, V>[] newSlots = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCount11];
System.arraycopy(slots11, 0, newSlots, 0, slotCount11);
slots11 = newSlots;
}
if (pageCount11 > 1 || pageCount11 == 1 && slotCount11 > 0) {
Arrays.sort(pages11, PAGE_ORDERING);
Arrays.sort(slots11, tree);
pagesXY[pageOffsetXY] = new QTreeNode<K, S, V>(pages11, slots11, x11, y11, span11);
} else if (slotCount11 == 0) {
pagesXY[pageOffsetXY] = pages11[0];
} else {
Arrays.sort(slots11, tree);
pagesXY[pageOffsetXY] = QTreeLeaf.create(slots11);
}
pageOffsetXY += 1;
}
Arrays.sort(pagesXY, PAGE_ORDERING);
if (slotCountXY == 0) {
slotsXY = (QTreeEntry<K, S, V>[]) EMPTY_SLOTS;
} else if (slotCountXY < slotCount) {
final QTreeEntry<K, S, V>[] newSlotsXY = (QTreeEntry<K, S, V>[]) new QTreeEntry<?, ?, ?>[slotCountXY];
System.arraycopy(slotsXY, 0, newSlotsXY, 0, slotCountXY);
slotsXY = newSlotsXY;
}
Arrays.sort(slotsXY, tree);
return create(pagesXY, slotsXY, this.span);
}
@Override
public Cursor<QTreeEntry<K, S, V>> cursor(long x, long y) {
return new QTreeNodeCursor<K, S, V>(this, x, y);
}
private int scan(long xk, long yk) {
final QTreePage<K, S, V>[] pages = this.pages;
int j = 0;
for (int i = 0, n = pages.length; i < n; i += 1) {
final QTreePage<K, S, V> page = pages[i];
final int order = BitInterval.compare(page.x(), page.y(), xk, yk);
if (order == 0) {
return i;
} else if (order < 0) {
j = i;
}
}
return -(j + 1);
}
private int lookup(long xk, long yk) {
final QTreePage<K, S, V>[] pages = this.pages;
int l = 0;
int u = pages.length - 1;
while (l <= u) { // binary search for xlub + 1
final int i = (l + u) >>> 1;
final int xOrder = BitInterval.compare(pages[i].x(), xk);
if (xOrder < 0) {
l = i + 1;
} else if (xOrder > 0) {
u = i - 1;
} else {
l = i + 1;
}
}
l -= 1; // step back to least upper bound
while (l >= 0) { // scan backwards for y match
final int yOrder = BitInterval.compare(pages[l].y(), yk);
if (yOrder < 0) {
break;
} else if (yOrder > 0) {
l -= 1;
} else {
return l;
}
}
if (l >= 0) {
return -(l + 1);
} else {
return -1;
}
}
private int lookup(K key, QTreeContext<K, S, V> tree) {
final QTreeEntry<K, S, V>[] slots = this.slots;
int low = 0;
int high = slots.length - 1;
while (low <= high) {
final int mid = (low + high) >>> 1;
final int order = tree.compareKey(key, slots[mid].key);
if (order > 0) {
low = mid + 1;
} else if (order < 0) {
high = mid - 1;
} else {
return mid;
}
}
return -(low + 1);
}
public static <K, S, V> QTreeNode<K, S, V> create(QTreePage<K, S, V>[] pages,
QTreeEntry<K, S, V>[] slots, long span) {
int xRank = 0;
int yRank = 0;
long xBase = 0L;
long yBase = 0L;
long xMask = -1L;
long yMask = -1L;
for (int i = 0, pageCount = pages.length; i < pageCount; i += 1) {
final QTreePage<K, S, V> page = pages[i];
final long cx = page.x();
final long cy = page.y();
final int cxRank = Long.numberOfLeadingZeros(~cx);
final int cyRank = Long.numberOfLeadingZeros(~cy);
final long cxBase = cx << cxRank;
final long cyBase = cy << cyRank;
xRank = Math.max(xRank, cxRank);
yRank = Math.max(yRank, cyRank);
xBase |= cxBase;
yBase |= cyBase;
xMask &= cxBase;
yMask &= cyBase;
}
for (int i = 0, slotCount = slots.length; i < slotCount; i += 1) {
final QTreeEntry<K, S, V> slot = slots[i];
final long tx = slot.x;
final long ty = slot.y;
final int txRank = Long.numberOfLeadingZeros(~tx);
final int tyRank = Long.numberOfLeadingZeros(~ty);
final long txBase = tx << txRank;
final long tyBase = ty << tyRank;
xRank = Math.max(xRank, txRank);
yRank = Math.max(yRank, tyRank);
xBase |= txBase;
yBase |= tyBase;
xMask &= txBase;
yMask &= tyBase;
}
xMask ^= xBase;
yMask ^= yBase;
xRank = Math.max(xRank, 64 - Long.numberOfLeadingZeros(xMask));
yRank = Math.max(yRank, 64 - Long.numberOfLeadingZeros(yMask));
xMask = ~((1L << xRank) - 1L);
yMask = ~((1L << yRank) - 1L);
xBase &= xMask;
yBase &= yMask;
final long x = BitInterval.from(xRank, xBase);
final long y = BitInterval.from(yRank, yBase);
return new QTreeNode<K, S, V>(pages, slots, x, y, span);
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreeNodeCursor.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.NoSuchElementException;
import swim.util.Cursor;
final class QTreeNodeCursor<K, S, V> implements Cursor<QTreeEntry<K, S, V>> {
final QTreeNode<K, S, V> page;
final long x;
final long y;
long index;
int slotIndex;
int pageIndex;
Cursor<QTreeEntry<K, S, V>> pageCursor;
QTreeNodeCursor(QTreeNode<K, S, V> page, long x, long y, long index, int slotIndex, int pageIndex) {
this.page = page;
this.x = x;
this.y = y;
this.index = index;
this.slotIndex = slotIndex;
this.pageIndex = pageIndex;
}
QTreeNodeCursor(QTreeNode<K, S, V> page, long x, long y) {
this(page, x, y, 0L, 0, 0);
}
Cursor<QTreeEntry<K, S, V>> pageCursor(QTreePage<K, S, V> page) {
return page.cursor(this.x, this.y);
}
@Override
public boolean isEmpty() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.slotIndex < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.slotIndex];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return false;
}
}
do {
final Cursor<QTreeEntry<K, S, V>> pageCursor = this.pageCursor;
if (pageCursor != null) {
if (!pageCursor.isEmpty()) {
return false;
} else {
this.pageCursor = null;
}
} else {
final QTreePage<K, S, V>[] pages = this.page.pages;
final int pageIndex = this.pageIndex;
if (pageIndex < pages.length) {
final QTreePage<K, S, V> page = pages[pageIndex];
if (BitInterval.intersects(x, y, page.x(), page.y())) {
this.pageCursor = pageCursor(page);
} else {
this.index += page.span();
}
this.pageIndex = pageIndex + 1;
} else {
return true;
}
}
} while (true);
}
@Override
public QTreeEntry<K, S, V> head() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.slotIndex < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.slotIndex];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return slot;
}
}
do {
final Cursor<QTreeEntry<K, S, V>> pageCursor = this.pageCursor;
if (pageCursor != null) {
if (!pageCursor.isEmpty()) {
return pageCursor.head();
} else {
this.pageCursor = null;
}
} else {
final QTreePage<K, S, V>[] pages = this.page.pages;
final int pageIndex = this.pageIndex;
if (pageIndex < pages.length) {
final QTreePage<K, S, V> page = pages[pageIndex];
if (BitInterval.intersects(x, y, page.x(), page.y())) {
this.pageCursor = pageCursor(page);
} else {
this.index += page.span();
}
this.pageIndex = pageIndex + 1;
} else {
throw new NoSuchElementException();
}
}
} while (true);
}
@Override
public void step() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.slotIndex < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.slotIndex];
this.index += 1L;
this.slotIndex += 1;
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return;
}
}
do {
final Cursor<QTreeEntry<K, S, V>> pageCursor = this.pageCursor;
if (pageCursor != null) {
if (pageCursor.hasNext()) {
this.index += 1L;
pageCursor.step();
} else {
this.pageCursor = null;
}
} else {
final QTreePage<K, S, V>[] pages = this.page.pages;
final int pageIndex = this.pageIndex;
if (pageIndex < pages.length) {
final QTreePage<K, S, V> page = pages[pageIndex];
if (BitInterval.intersects(x, y, page.x(), page.y())) {
this.pageCursor = pageCursor(page);
} else {
this.index += page.span();
}
this.pageIndex = pageIndex + 1;
} else {
throw new UnsupportedOperationException();
}
}
} while (true);
}
@Override
public void skip(long count) {
while (count > 0L) {
final Cursor<QTreeEntry<K, S, V>> pageCursor = this.pageCursor;
if (pageCursor != null) {
if (pageCursor.hasNext()) {
this.index += 1L;
count -= 1L;
pageCursor.next();
} else {
this.pageCursor = null;
}
} else {
final QTreePage<K, S, V>[] pages = this.page.pages;
final int pageIndex = this.pageIndex;
if (pageIndex < pages.length) {
final QTreePage<K, S, V> page = pages[pageIndex];
final long pageSpan = page.span();
this.pageIndex = pageIndex + 1;
if (pageSpan < count) {
this.pageCursor = pageCursor(page);
if (count > 0L) {
this.index += count;
this.pageCursor.skip(count);
count = 0L;
}
break;
} else {
this.index += pageSpan;
count -= pageSpan;
}
} else {
break;
}
}
}
}
@Override
public boolean hasNext() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.slotIndex < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.slotIndex];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return true;
}
this.index += 1L;
this.slotIndex += 1;
}
do {
final Cursor<QTreeEntry<K, S, V>> pageCursor = this.pageCursor;
if (pageCursor != null) {
if (pageCursor.hasNext()) {
return true;
} else {
this.pageCursor = null;
}
} else {
final QTreePage<K, S, V>[] pages = this.page.pages;
final int pageIndex = this.pageIndex;
if (pageIndex < pages.length) {
final QTreePage<K, S, V> page = pages[pageIndex];
if (BitInterval.intersects(x, y, page.x(), page.y())) {
this.pageCursor = pageCursor(page);
} else {
this.index += page.span();
}
this.pageIndex = pageIndex + 1;
} else {
return false;
}
}
} while (true);
}
@Override
public long nextIndexLong() {
return this.index;
}
@Override
public QTreeEntry<K, S, V> next() {
final long x = this.x;
final long y = this.y;
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.slotIndex < slots.length) {
final QTreeEntry<K, S, V> slot = slots[this.slotIndex];
this.index += 1L;
this.slotIndex += 1;
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return slot;
}
}
do {
final Cursor<QTreeEntry<K, S, V>> pageCursor = this.pageCursor;
if (pageCursor != null) {
if (pageCursor.hasNext()) {
this.index += 1L;
return pageCursor.next();
} else {
this.pageCursor = null;
}
} else {
final QTreePage<K, S, V>[] pages = this.page.pages;
final int pageIndex = this.pageIndex;
if (pageIndex < pages.length) {
final QTreePage<K, S, V> page = pages[pageIndex];
if (BitInterval.intersects(x, y, page.x(), page.y())) {
this.pageCursor = pageCursor(page);
} else {
this.index += page.span();
}
this.pageIndex = pageIndex + 1;
} else {
throw new NoSuchElementException();
}
}
} while (true);
}
@Override
public boolean hasPrevious() {
final long x = this.x;
final long y = this.y;
do {
final Cursor<QTreeEntry<K, S, V>> pageCursor = this.pageCursor;
if (pageCursor != null) {
if (pageCursor.hasPrevious()) {
return true;
} else {
this.pageCursor = null;
}
} else {
final QTreePage<K, S, V>[] pages = this.page.pages;
final int pageIndex = this.pageIndex - 1;
if (pageIndex >= 0) {
final QTreePage<K, S, V> page = pages[pageIndex];
if (BitInterval.intersects(x, y, page.x(), page.y())) {
this.pageCursor = pageCursor(page);
} else {
this.index -= page.span();
}
this.pageIndex = pageIndex;
} else {
break;
}
}
} while (true);
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.slotIndex > 0) {
final QTreeEntry<K, S, V> slot = slots[this.slotIndex - 1];
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return true;
}
this.index -= 1L;
this.slotIndex -= 1;
}
return false;
}
@Override
public long previousIndexLong() {
return this.index - 1L;
}
@Override
public QTreeEntry<K, S, V> previous() {
final long x = this.x;
final long y = this.y;
do {
final Cursor<QTreeEntry<K, S, V>> pageCursor = this.pageCursor;
if (pageCursor != null) {
if (pageCursor.hasPrevious()) {
this.index -= 1L;
return pageCursor.previous();
} else {
this.pageCursor = null;
}
} else {
final QTreePage<K, S, V>[] pages = this.page.pages;
final int pageIndex = this.pageIndex - 1;
if (pageIndex < pages.length) {
final QTreePage<K, S, V> page = pages[pageIndex];
if (BitInterval.intersects(x, y, page.x(), page.y())) {
this.pageCursor = pageCursor(page);
} else {
this.index -= page.span();
}
this.pageIndex = pageIndex;
} else {
break;
}
}
} while (true);
final QTreeEntry<K, S, V>[] slots = this.page.slots;
while (this.slotIndex > 0) {
final QTreeEntry<K, S, V> slot = slots[this.slotIndex - 1];
this.index -= 1L;
this.slotIndex -= 1;
if (BitInterval.intersects(x, y, slot.x, slot.y)) {
return slot;
}
}
throw new NoSuchElementException();
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreePage.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import swim.util.Cursor;
public abstract class QTreePage<K, S, V> {
QTreePage() {
// stub
}
public abstract boolean isEmpty();
public abstract long span();
public abstract int arity();
public abstract QTreePage<K, S, V> getPage(int index);
public abstract int slotCount();
public abstract QTreeEntry<K, S, V> getSlot(int index);
public abstract long x();
public abstract int xRank();
public abstract long xBase();
public abstract long xMask();
public abstract long xSplit();
public abstract long y();
public abstract int yRank();
public abstract long yBase();
public abstract long yMask();
public abstract long ySplit();
public abstract boolean containsKey(K key, long xk, long yk, QTreeContext<K, S, V> tree);
public boolean containsKey(K key, int xkRank, long xkBase, int ykRank, long ykBase, QTreeContext<K, S, V> tree) {
final long x = BitInterval.from(xkRank, xkBase);
final long y = BitInterval.from(ykRank, ykBase);
return containsKey(key, x, y, tree);
}
public abstract V get(K key, long xk, long yk, QTreeContext<K, S, V> tree);
public V get(K key, int xkRank, long xkBase, int ykRank, long ykBase, QTreeContext<K, S, V> tree) {
final long x = BitInterval.from(xkRank, xkBase);
final long y = BitInterval.from(ykRank, ykBase);
return get(key, x, y, tree);
}
public Collection<QTreeEntry<K, S, V>> getAll(long x, long y) {
final Collection<QTreeEntry<K, S, V>> slots = new ArrayList<QTreeEntry<K, S, V>>();
final Cursor<QTreeEntry<K, S, V>> cursor = cursor(x, y);
while (cursor.hasNext()) {
slots.add(cursor.next());
}
return slots;
}
public Collection<QTreeEntry<K, S, V>> getAll(long x0, long y0, long x1, long y1) {
final long x = BitInterval.span(x0, x1);
final long y = BitInterval.span(y0, y1);
return getAll(x, y);
}
abstract QTreePage<K, S, V> updated(K key, S shape, long xk, long yk, V newValue,
QTreeContext<K, S, V> tree, boolean canSplit);
public QTreePage<K, S, V> updated(K key, S shape, long xk, long yk, V newValue, QTreeContext<K, S, V> tree) {
return updated(key, shape, xk, yk, newValue, tree, true);
}
public QTreePage<K, S, V> updated(K key, S shape, int xkRank, long xkBase,
int ykRank, long ykBase, V newValue, QTreeContext<K, S, V> tree) {
final long xk = BitInterval.from(xkRank, xkBase);
final long yk = BitInterval.from(ykRank, ykBase);
return updated(key, shape, xk, yk, newValue, tree);
}
abstract QTreePage<K, S, V> insertedPage(QTreePage<K, S, V> newPage, QTreeContext<K, S, V> tree);
abstract QTreePage<K, S, V> mergedPage(QTreePage<K, S, V> newPage, QTreeContext<K, S, V> tree);
abstract QTreePage<K, S, V> mergedSlots(QTreeEntry<K, S, V>[] midSlots, QTreeContext<K, S, V> tree);
abstract QTreePage<K, S, V> updatedSlot(QTreeEntry<K, S, V> newSlot, QTreeContext<K, S, V> tree);
public abstract QTreePage<K, S, V> removed(K key, long xk, long yk, QTreeContext<K, S, V> tree);
public QTreePage<K, S, V> removed(K key, int xkRank, long xkBase, int ykRank, long ykBase, QTreeContext<K, S, V> tree) {
final long xk = BitInterval.from(xkRank, xkBase);
final long yk = BitInterval.from(ykRank, ykBase);
return removed(key, xk, yk, tree);
}
public abstract QTreePage<K, S, V> flattened(QTreeContext<K, S, V> tree);
public abstract QTreePage<K, S, V> balanced(QTreeContext<K, S, V> tree);
// Always returns QTreeNode, but we don't want to publicly expose it.
public abstract QTreePage<K, S, V> split(QTreeContext<K, S, V> tree);
public abstract Cursor<QTreeEntry<K, S, V>> cursor(long x, long y);
public Cursor<QTreeEntry<K, S, V>> cursor(long x0, long y0, long x1, long y1) {
final long x = BitInterval.span(x0, x1);
final long y = BitInterval.span(y0, y1);
return cursor(x, y);
}
public Cursor<QTreeEntry<K, S, V>> cursor() {
return cursor(-1L, -1L);
}
static final QTreePage<?, ?, ?>[] EMPTY_PAGES = new QTreePage<?, ?, ?>[0];
static final QTreeEntry<?, ?, ?>[] EMPTY_SLOTS = new QTreeEntry<?, ?, ?>[0];
static final Comparator<QTreePage<?, ?, ?>> PAGE_ORDERING = new QTreePageOrdering();
public static <K, S, V> QTreePage<K, S, V> empty() {
return QTreeLeaf.empty();
}
}
final class QTreePageOrdering implements Comparator<QTreePage<?, ?, ?>> {
@Override
public int compare(QTreePage<?, ?, ?> a, QTreePage<?, ?, ?> b) {
return BitInterval.compare(a.x(), a.y(), b.x(), b.y());
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/QTreeShapeCursor.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import swim.math.Z2Form;
import swim.util.Cursor;
final class QTreeShapeCursor<K, S, V> implements Cursor<SpatialMap.Entry<K, S, V>> {
final Cursor<QTreeEntry<K, S, V>> inner;
final Z2Form<S> shapeForm;
final S shape;
QTreeEntry<K, S, V> nextSlot;
QTreeEntry<K, S, V> previousSlot;
QTreeShapeCursor(Cursor<QTreeEntry<K, S, V>> inner, Z2Form<S> shapeForm, S shape) {
this.inner = inner;
this.shapeForm = shapeForm;
this.shape = shape;
}
@Override
public boolean isEmpty() {
QTreeEntry<K, S, V> nextSlot = this.nextSlot;
if (nextSlot == null) {
final Z2Form<S> shapeForm = this.shapeForm;
while (this.inner.hasNext()) {
nextSlot = this.inner.next();
if (shapeForm.intersects(this.shape, nextSlot.shape)) {
this.nextSlot = nextSlot;
return false;
}
}
return true;
}
return false;
}
@Override
public QTreeEntry<K, S, V> head() {
QTreeEntry<K, S, V> nextSlot = this.nextSlot;
if (nextSlot == null) {
final Z2Form<S> shapeForm = this.shapeForm;
do {
nextSlot = this.inner.next();
if (shapeForm.intersects(this.shape, nextSlot.shape)) {
break;
}
} while (true);
}
this.previousSlot = null;
this.nextSlot = nextSlot;
return nextSlot;
}
@Override
public void step() {
QTreeEntry<K, S, V> nextSlot = this.nextSlot;
if (nextSlot == null) {
final Z2Form<S> shapeForm = this.shapeForm;
do {
nextSlot = this.inner.next();
if (shapeForm.intersects(this.shape, nextSlot.shape)) {
break;
}
} while (true);
}
this.previousSlot = nextSlot;
this.nextSlot = null;
}
@Override
public void skip(long count) {
this.inner.skip(count);
}
@Override
public boolean hasNext() {
QTreeEntry<K, S, V> nextSlot = this.nextSlot;
if (nextSlot == null) {
final Z2Form<S> shapeForm = this.shapeForm;
while (this.inner.hasNext()) {
nextSlot = this.inner.next();
if (shapeForm.intersects(this.shape, nextSlot.shape)) {
this.nextSlot = nextSlot;
return true;
}
}
return false;
}
return true;
}
@Override
public long nextIndexLong() {
return this.inner.nextIndexLong();
}
@Override
public int nextIndex() {
return this.inner.nextIndex();
}
@Override
public QTreeEntry<K, S, V> next() {
QTreeEntry<K, S, V> nextSlot = this.nextSlot;
if (nextSlot == null) {
final Z2Form<S> shapeForm = this.shapeForm;
do {
nextSlot = this.inner.next();
if (shapeForm.intersects(this.shape, nextSlot.shape)) {
break;
}
} while (true);
}
this.previousSlot = nextSlot;
this.nextSlot = null;
return nextSlot;
}
@Override
public boolean hasPrevious() {
QTreeEntry<K, S, V> previousSlot = this.previousSlot;
if (previousSlot == null) {
final Z2Form<S> shapeForm = this.shapeForm;
while (this.inner.hasPrevious()) {
previousSlot = this.inner.previous();
if (shapeForm.intersects(this.shape, previousSlot.shape)) {
this.previousSlot = previousSlot;
return true;
}
}
return false;
}
return true;
}
@Override
public long previousIndexLong() {
return this.inner.previousIndexLong();
}
@Override
public int previousIndex() {
return this.inner.previousIndex();
}
@Override
public QTreeEntry<K, S, V> previous() {
QTreeEntry<K, S, V> previousSlot = this.previousSlot;
if (previousSlot == null) {
final Z2Form<S> shapeForm = this.shapeForm;
do {
previousSlot = this.inner.previous();
if (shapeForm.intersects(this.shape, previousSlot.shape)) {
break;
}
} while (true);
}
this.nextSlot = previousSlot;
this.previousSlot = null;
return previousSlot;
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/SpatialMap.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Iterator;
import java.util.Map;
public interface SpatialMap<K, S, V> extends Iterable<SpatialMap.Entry<K, S, V>> {
boolean isEmpty();
int size();
boolean containsKey(K key, S shape);
boolean containsKey(Object key);
boolean containsValue(Object value);
V get(K key, S shape);
V get(Object key);
V put(K key, S shape, V newValue);
V move(K key, S oldShape, S newShape, V newValue);
V remove(K key, S shape);
void clear();
Iterator<Entry<K, S, V>> iterator(S shape);
Iterator<K> keyIterator();
Iterator<V> valueIterator();
interface Entry<K, S, V> extends Map.Entry<K, V> {
S getShape();
}
class SimpleEntry<K, S, V> implements Entry<K, S, V> {
protected K key;
protected S shape;
protected V value;
public SimpleEntry(K key, S shape, V value) {
this.key = key;
this.shape = shape;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public S getShape() {
return shape;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V newValue) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Map.Entry<?, ?>) {
final Map.Entry<?, ?> that = (Map.Entry<?, ?>) other;
final K key = getKey();
if (key == null ? that.getKey() != null : !key.equals(that.getKey())) {
return false;
}
final V value = getValue();
if (value == null ? that.getValue() != null : !value.equals(that.getValue())) {
return false;
}
return true;
}
return false;
}
@Override
public int hashCode() {
final K key = getKey();
final V value = getValue();
return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
}
@Override
public String toString() {
return new StringBuilder().append(getKey()).append('=').append(getValue()).toString();
}
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/SpatialValueEntry.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Map;
import swim.structure.Form;
import swim.structure.Value;
public final class SpatialValueEntry<K, S, V> implements SpatialMap.Entry<K, S, V> {
final SpatialMap.Entry<Value, S, Value> inner;
final Form<K> keyForm;
final Form<V> valueForm;
volatile K keyObject;
volatile V valueObject;
public SpatialValueEntry(SpatialMap.Entry<Value, S, Value> inner, Form<K> keyForm, Form<V> valueForm) {
this.inner = inner;
this.keyForm = keyForm;
this.valueForm = valueForm;
}
@Override
public K getKey() {
K keyObject = this.keyObject;
if (keyObject == null) {
keyObject = this.keyForm.cast(this.inner.getKey());
if (keyObject == null) {
keyObject = this.keyForm.unit();
}
this.keyObject = keyObject;
}
return keyObject;
}
@Override
public S getShape() {
return this.inner.getShape();
}
@Override
public V getValue() {
V valueObject = this.valueObject;
if (valueObject == null) {
valueObject = this.valueForm.cast(this.inner.getValue());
if (valueObject == null) {
valueObject = this.valueForm.unit();
}
this.valueObject = valueObject;
}
return valueObject;
}
@Override
public V setValue(V newValueObject) {
final Value newValue = this.valueForm.mold(newValueObject).toValue();
final Value oldValue = this.inner.setValue(newValue);
final V oldValueObject = this.valueForm.cast(oldValue);
if (oldValueObject != null) {
return oldValueObject;
}
return this.valueForm.unit();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Map.Entry<?, ?>) {
final Map.Entry<?, ?> that = (Map.Entry<?, ?>) other;
final K keyObject = getKey();
if (keyObject == null ? that.getKey() != null : !keyObject.equals(that.getKey())) {
return false;
}
final V valueObject = getValue();
if (valueObject == null ? that.getValue() != null : !valueObject.equals(that.getValue())) {
return false;
}
return true;
}
return false;
}
@Override
public int hashCode() {
final K keyObject = getKey();
final V valueObject = getValue();
return (keyObject == null ? 0 : keyObject.hashCode())
^ (valueObject == null ? 0 : valueObject.hashCode());
}
@Override
public String toString() {
return new StringBuilder().append(getKey()).append('=').append(getValue()).toString();
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/SpatialValueEntryIterator.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Iterator;
import swim.structure.Form;
import swim.structure.Value;
final class SpatialValueEntryIterator<K, S, V> implements Iterator<SpatialMap.Entry<K, S, V>> {
final Iterator<SpatialMap.Entry<Value, S, Value>> inner;
final Form<K> keyForm;
final Form<V> valueForm;
SpatialValueEntryIterator(Iterator<SpatialMap.Entry<Value, S, Value>> inner, Form<K> keyForm, Form<V> valueForm) {
this.inner = inner;
this.keyForm = keyForm;
this.valueForm = valueForm;
}
@Override
public boolean hasNext() {
return this.inner.hasNext();
}
@Override
public SpatialMap.Entry<K, S, V> next() {
return new SpatialValueEntry<K, S, V>(this.inner.next(), this.keyForm, this.valueForm);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/SpatialValueMap.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import java.util.Iterator;
import swim.structure.Form;
import swim.structure.Value;
import swim.structure.collections.ValueIterator;
public class SpatialValueMap<K, S, V> implements SpatialMap<K, S, V> {
protected SpatialMap<Value, S, Value> inner;
protected Form<K> keyForm;
protected Form<V> valueForm;
public SpatialValueMap(SpatialMap<Value, S, Value> inner, Form<K> keyForm, Form<V> valueForm) {
this.inner = inner;
this.keyForm = keyForm;
this.valueForm = valueForm;
}
public SpatialMap<Value, S, Value> inner() {
return this.inner;
}
public Form<K> keyForm() {
return this.keyForm;
}
public <K2> SpatialValueMap<K2, S, V> keyForm(Form<K2> keyForm) {
return new SpatialValueMap<K2, S, V>(this.inner, keyForm, this.valueForm);
}
public <K2> SpatialValueMap<K2, S, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
public Form<V> valueForm() {
return this.valueForm;
}
public <V2> SpatialValueMap<K, S, V2> valueForm(Form<V2> valueForm) {
return new SpatialValueMap<K, S, V2>(this.inner, this.keyForm, valueForm);
}
public <V2> SpatialValueMap<K, S, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
@Override
public boolean isEmpty() {
return this.inner.isEmpty();
}
@Override
public int size() {
return this.inner.size();
}
@Override
public boolean containsKey(K keyObject, S shape) {
final Value key = this.keyForm.mold(keyObject).toValue();
return this.inner.containsKey(key, shape);
}
@SuppressWarnings("unchecked")
@Override
public boolean containsKey(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
return this.inner.containsKey(key);
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean containsValue(Object valueObject) {
final Class<?> valueType = this.valueForm.type();
if (valueType == null || valueType.isInstance(valueObject)) {
final Value value = this.valueForm.mold((V) valueObject).toValue();
return this.inner.containsValue(value);
}
return false;
}
@Override
public V get(K keyObject, S shape) {
final Value key = this.keyForm.mold(keyObject).toValue();
final Value value = this.inner.get(key, shape);
final V valueObject = this.valueForm.cast(value);
if (valueObject != null) {
return valueObject;
}
return this.valueForm.unit();
}
@SuppressWarnings("unchecked")
@Override
public V get(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Value value = this.inner.get(key);
final V valueObject = this.valueForm.cast(value);
if (valueObject != null) {
return valueObject;
}
}
return this.valueForm.unit();
}
@Override
public V put(K keyObject, S shape, V newObject) {
final Value key = this.keyForm.mold(keyObject).toValue();
final Value newValue = this.valueForm.mold(newObject).toValue();
final Value oldValue = this.inner.put(key, shape, newValue);
final V oldObject = this.valueForm.cast(oldValue);
if (oldObject != null) {
return oldObject;
}
return this.valueForm.unit();
}
@Override
public V move(K keyObject, S oldShape, S newShape, V newObject) {
final Value key = this.keyForm.mold(keyObject).toValue();
final Value newValue = this.valueForm.mold(newObject).toValue();
final Value oldValue = this.inner.move(key, oldShape, newShape, newValue);
final V oldObject = this.valueForm.cast(oldValue);
if (oldObject != null) {
return oldObject;
}
return this.valueForm.unit();
}
@Override
public V remove(K keyObject, S shape) {
final Value key = this.keyForm.mold(keyObject).toValue();
final Value oldValue = this.inner.remove(key, shape);
final V oldObject = this.valueForm.cast(oldValue);
if (oldObject != null) {
return oldObject;
}
return this.valueForm.unit();
}
@Override
public void clear() {
this.inner.clear();
}
@SuppressWarnings("unchecked")
@Override
public Iterator<Entry<K, S, V>> iterator(S shape) {
if (keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
return new SpatialValueEntryIterator<K, S, V>(this.inner.iterator(shape), this.keyForm, this.valueForm);
} else {
return (Iterator<Entry<K, S, V>>) (Iterator<?>) this.inner.iterator(shape);
}
}
@SuppressWarnings("unchecked")
@Override
public Iterator<Entry<K, S, V>> iterator() {
if (keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
return new SpatialValueEntryIterator<K, S, V>(this.inner.iterator(), this.keyForm, this.valueForm);
} else {
return (Iterator<Entry<K, S, V>>) (Iterator<?>) this.inner.iterator();
}
}
@SuppressWarnings("unchecked")
public Iterator<K> keyIterator() {
if (keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
return new ValueIterator<K>(this.inner.keyIterator(), this.keyForm);
} else {
return (Iterator<K>) this.inner.keyIterator();
}
}
@SuppressWarnings("unchecked")
public Iterator<V> valueIterator() {
if (keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
return new ValueIterator<V>(this.inner.valueIterator(), this.valueForm);
} else {
return (Iterator<V>) this.inner.valueIterator();
}
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof SpatialMap<?, ?, ?>) {
final SpatialMap<?, ?, ?> that = (SpatialMap<?, ?, ?>) other;
if (size() != that.size()) {
return false;
}
try {
final Iterator<Entry<K, S, V>> these = iterator();
while (these.hasNext()) {
final Entry<K, S, V> entry = these.next();
final K keyObject = entry.getKey();
final V valueObject = entry.getValue();
if (valueObject != null) {
if (!valueObject.equals(that.get(keyObject))) {
return false;
}
} else {
if (!(that.get(keyObject) == null && that.containsKey(keyObject))) {
return false;
}
}
}
return true;
} catch (ClassCastException | NullPointerException e) {
// swallow
}
}
return false;
}
@Override
public int hashCode() {
final Iterator<Entry<K, S, V>> these = iterator();
int h = 0;
while (these.hasNext()) {
h += these.next().hashCode();
}
return h;
}
@Override
public String toString() {
final Iterator<Entry<K, S, V>> these = iterator();
if (!these.hasNext()) {
return "{}";
}
final StringBuilder sb = new StringBuilder();
sb.append('{');
do {
sb.append(these.next());
if (these.hasNext()) {
sb.append(", ");
} else {
break;
}
} while (true);
return sb.append('}').toString();
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/SphericalMercator.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import swim.math.R2Shape;
import swim.math.R2ToZ2Operator;
import swim.math.Z2Form;
import swim.math.Z2ToR2Operator;
import swim.structure.Item;
final class SphericalMercator extends Z2Form<R2Shape> implements R2ToZ2Operator {
@Override
public Class<?> type() {
return R2Shape.class;
}
@Override
public long getXMin(R2Shape shape) {
return transformLng(shape.xMin());
}
@Override
public long getYMin(R2Shape shape) {
return transformLat(shape.yMin());
}
@Override
public long getXMax(R2Shape shape) {
return transformLng(shape.xMax());
}
@Override
public long getYMax(R2Shape shape) {
return transformLat(shape.yMax());
}
@Override
public boolean contains(R2Shape outer, R2Shape inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(R2Shape s, R2Shape t) {
return s.intersects(t);
}
@Override
public Item mold(R2Shape shape) {
return R2Shape.shapeForm().mold(shape);
}
@Override
public R2Shape cast(Item item) {
return R2Shape.shapeForm().cast(item);
}
@Override
public long transformX(double lng, double lat) {
return transformLng(lng);
}
@Override
public long transformY(double lng, double lat) {
return transformLat(lat);
}
@Override
public Z2ToR2Operator inverse() {
return GeoProjection.sphericalMercatorInverse();
}
static final double MAX_LAT = Math.atan(Math.sinh(Math.PI));
static long transformLng(double lng) {
return scale(Math.toRadians(lng));
}
static long transformLat(double lat) {
return scale(Math.log(Math.tan(Math.PI / 4.0 + Math.min(Math.max(-MAX_LAT, Math.toRadians(lat)), MAX_LAT) / 2.0)));
}
static long scale(double x) {
return (long) (((Math.min(Math.max(-Math.PI, x), Math.PI) + Math.PI) / (Math.PI * 2.0)) * (double) 0x7fffffffffffffffL);
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/SphericalMercatorInverse.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import swim.math.R2ToZ2Operator;
import swim.math.Z2ToR2Operator;
final class SphericalMercatorInverse implements Z2ToR2Operator {
@Override
public double transformX(long x, long y) {
return transformX(x);
}
@Override
public double transformY(long x, long y) {
return transformY(y);
}
@Override
public R2ToZ2Operator inverse() {
return GeoProjection.sphericalMercator();
}
static double transformX(long x) {
return round(Math.toDegrees(unscale(x)));
}
static double transformY(long y) {
return round(Math.toDegrees(Math.atan(Math.exp(unscale(y))) * 2.0 - Math.PI / 2.0));
}
static double unscale(long x) {
return ((double) x / (double) 0x7fffffffffffffffL) * (Math.PI * 2.0) - Math.PI;
}
static double round(double value) {
return (double) Math.round(value * 100000000.0) / 100000000.0;
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/WGS84.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import swim.math.R2Shape;
import swim.math.R2ToZ2Operator;
import swim.math.Z2Form;
import swim.math.Z2ToR2Operator;
import swim.structure.Item;
final class WGS84 extends Z2Form<R2Shape> implements R2ToZ2Operator {
@Override
public Class<?> type() {
return R2Shape.class;
}
@Override
public long getXMin(R2Shape shape) {
return transformLng(shape.xMin());
}
@Override
public long getYMin(R2Shape shape) {
return transformLat(shape.yMin());
}
@Override
public long getXMax(R2Shape shape) {
return transformLng(shape.xMax());
}
@Override
public long getYMax(R2Shape shape) {
return transformLat(shape.yMax());
}
@Override
public boolean contains(R2Shape outer, R2Shape inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(R2Shape s, R2Shape t) {
return s.intersects(t);
}
@Override
public Item mold(R2Shape shape) {
return R2Shape.shapeForm().mold(shape);
}
@Override
public R2Shape cast(Item item) {
return R2Shape.shapeForm().cast(item);
}
@Override
public long transformX(double lng, double lat) {
return transformLng(lng);
}
@Override
public long transformY(double lng, double lat) {
return transformLat(lat);
}
@Override
public Z2ToR2Operator inverse() {
return GeoProjection.wgs84Inverse();
}
static long transformLng(double lng) {
return (long) (((Math.min(Math.max(-180.0, lng), 180.0) + 180.0) / 360.0) * (double) 0x7fffffffffffffffL);
}
static long transformLat(double lat) {
return (long) (((Math.min(Math.max(-90.0, lat), 90.0) + 90.0) / 180.0) * (double) 0x7fffffffffffffffL);
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/WGS84Inverse.java | // Copyright 2015-2019 SWIM.AI 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 swim.spatial;
import swim.math.R2ToZ2Operator;
import swim.math.Z2ToR2Operator;
final class WGS84Inverse implements Z2ToR2Operator {
@Override
public double transformX(long x, long y) {
return transformX(x);
}
@Override
public double transformY(long x, long y) {
return transformY(y);
}
@Override
public R2ToZ2Operator inverse() {
return GeoProjection.wgs84();
}
static double transformX(long x) {
return round(((double) x / (double) 0x7fffffffffffffffL) * 360.0 - 180.0);
}
static double transformY(long y) {
return round(((double) y / (double) 0x7fffffffffffffffL) * 180.0 - 90.0);
}
static double round(double value) {
return (double) Math.round(value * 100000000.0) / 100000000.0;
}
}
|
0 | java-sources/ai/swim/swim-spatial/3.10.0/swim | java-sources/ai/swim/swim-spatial/3.10.0/swim/spatial/package-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Spatial collections and geospatial projections.
*/
package swim.spatial;
|
0 | java-sources/ai/swim/swim-store | java-sources/ai/swim/swim-store/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Storage runtime interface.
*/
module swim.store {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.structure;
requires transitive swim.math;
requires transitive swim.spatial;
requires transitive swim.api;
exports swim.store;
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/DataBinding.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.structure.Value;
public interface DataBinding {
DataContext dataContext();
StoreBinding storeBinding();
void setStoreBinding(StoreBinding storeBinding);
<T> T unwrapData(Class<T> dataClass);
Value name();
long dataSize();
boolean isResident();
DataBinding isResident(boolean isResident);
boolean isTransient();
DataBinding isTransient(boolean isTransient);
void close();
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/DataContext.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
public interface DataContext {
void didChange();
void didCommit();
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/ListDataBinding.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.ListData;
import swim.structure.Value;
public interface ListDataBinding extends ListData<Value>, DataBinding {
@Override
ListDataContext dataContext();
void setDataContext(ListDataContext dataContext);
@Override
ListDataBinding isResident(boolean isResident);
@Override
ListDataBinding isTransient(boolean isTransient);
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/ListDataContext.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.structure.Value;
public interface ListDataContext extends DataContext {
void didUpdate(long index, Value newValue, Value oldValue);
void didInsert(long index, Value newValue);
void didRemove(long index, Value oldValue);
void didDrop(long lower);
void didTake(long upper);
void didClear();
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/ListDataProxy.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import swim.api.data.ListData;
import swim.structure.Form;
import swim.structure.Value;
import swim.util.KeyedList;
public class ListDataProxy implements ListDataBinding, ListDataContext {
protected final ListDataBinding dataBinding;
protected ListDataContext dataContext;
public ListDataProxy(ListDataBinding dataBinding) {
this.dataBinding = dataBinding;
}
public final ListDataBinding dataBinding() {
return this.dataBinding;
}
@Override
public final ListDataContext dataContext() {
return this.dataContext;
}
@Override
public void setDataContext(ListDataContext dataContext) {
this.dataContext = dataContext;
this.dataBinding.setDataContext(this);
}
@Override
public StoreBinding storeBinding() {
return this.dataBinding.storeBinding();
}
@Override
public void setStoreBinding(StoreBinding storeBinding) {
this.dataBinding.setStoreBinding(storeBinding);
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapData(Class<T> dataClass) {
if (dataClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.dataBinding.unwrapData(dataClass);
}
}
@Override
public Value name() {
return this.dataBinding.name();
}
@Override
public long dataSize() {
return this.dataBinding.dataSize();
}
@Override
public boolean isResident() {
return this.dataBinding.isResident();
}
@Override
public Form<Value> valueForm() {
return Form.forValue();
}
@Override
public <V> ListData<V> valueForm(Form<V> valueForm) {
return new ListDataView<V>(this, valueForm);
}
@Override
public <V> ListData<V> valueClass(Class<V> valueClass) {
return valueForm(Form.<V>forClass(valueClass));
}
@Override
public ListDataBinding isResident(boolean isResident) {
this.dataBinding.isResident(isResident);
return this;
}
@Override
public boolean isTransient() {
return this.dataBinding.isTransient();
}
@Override
public ListDataBinding isTransient(boolean isTransient) {
this.dataBinding.isTransient(isTransient);
return this;
}
@Override
public boolean isEmpty() {
return this.dataBinding.isEmpty();
}
@Override
public int size() {
return this.dataBinding.size();
}
@Override
public boolean contains(Object value) {
return this.dataBinding.contains(value);
}
@Override
public boolean containsAll(Collection<?> values) {
return this.dataBinding.containsAll(values);
}
@Override
public int indexOf(Object value) {
return this.dataBinding.indexOf(value);
}
@Override
public int lastIndexOf(Object value) {
return this.dataBinding.lastIndexOf(value);
}
@Override
public Value get(int index) {
return this.dataBinding.get(index);
}
@Override
public Value get(int index, Object key) {
return this.dataBinding.get(index, key);
}
@Override
public Map.Entry<Object, Value> getEntry(int index) {
return this.dataBinding.getEntry(index);
}
@Override
public Map.Entry<Object, Value> getEntry(int index, Object key) {
return this.dataBinding.getEntry(index, key);
}
@Override
public Value set(int index, Value value) {
return this.dataBinding.set(index, value);
}
@Override
public Value set(int index, Value value, Object key) {
return this.dataBinding.set(index, value, key);
}
@Override
public boolean add(Value value) {
return this.dataBinding.add(value);
}
@Override
public boolean add(Value value, Object key) {
return this.dataBinding.add(value, key);
}
@Override
public boolean addAll(Collection<? extends Value> values) {
return this.dataBinding.addAll(values);
}
@Override
public void add(int index, Value value) {
this.dataBinding.add(index, value);
}
@Override
public void add(int index, Value value, Object key) {
this.dataBinding.add(index, value, key);
}
@Override
public boolean addAll(int index, Collection<? extends Value> values) {
return this.dataBinding.addAll(index, values);
}
@Override
public Value remove(int index) {
return this.dataBinding.remove(index);
}
@Override
public Value remove(int index, Object key) {
return this.dataBinding.remove(index, key);
}
@Override
public boolean remove(Object value) {
return this.dataBinding.remove(value);
}
@Override
public boolean removeAll(Collection<?> values) {
return this.dataBinding.removeAll(values);
}
@Override
public boolean retainAll(Collection<?> values) {
return this.dataBinding.retainAll(values);
}
@Override
public void move(int fromIndex, int toIndex) {
this.dataBinding.move(fromIndex, toIndex);
}
@Override
public void move(int fromIndex, int toIndex, Object key) {
this.dataBinding.move(fromIndex, toIndex, key);
}
@Override
public void drop(int lower) {
this.dataBinding.drop(lower);
}
@Override
public void take(int upper) {
this.dataBinding.take(upper);
}
@Override
public void clear() {
this.dataBinding.clear();
}
@Override
public Iterator<Value> iterator() {
return this.dataBinding.iterator();
}
@Override
public ListIterator<Value> listIterator() {
return this.dataBinding.listIterator();
}
@Override
public ListIterator<Value> listIterator(int index) {
return this.dataBinding.listIterator(index);
}
@Override
public ListIterator<Object> keyIterator() {
return this.dataBinding.keyIterator();
}
@Override
public ListIterator<Map.Entry<Object, Value>> entryIterator() {
return this.dataBinding.entryIterator();
}
@Override
public List<Value> subList(int fromIndex, int toIndex) {
return this.dataBinding.subList(fromIndex, toIndex);
}
@Override
public KeyedList<Value> snapshot() {
return this.dataBinding.snapshot();
}
@Override
public Object[] toArray() {
return this.dataBinding.toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return this.dataBinding.toArray(array);
}
@Override
public void close() {
this.dataBinding.close();
}
@Override
public void didChange() {
this.dataContext.didChange();
}
@Override
public void didCommit() {
this.dataContext.didCommit();
}
@Override
public void didUpdate(long index, Value newValue, Value oldValue) {
this.dataContext.didUpdate(index, newValue, oldValue);
}
@Override
public void didInsert(long index, Value newValue) {
this.dataContext.didInsert(index, newValue);
}
@Override
public void didRemove(long index, Value oldValue) {
this.dataContext.didRemove(index, oldValue);
}
@Override
public void didDrop(long lower) {
this.dataContext.didDrop(lower);
}
@Override
public void didTake(long upper) {
this.dataContext.didTake(upper);
}
@Override
public void didClear() {
this.dataContext.didClear();
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/ListDataView.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.ListData;
import swim.structure.Form;
import swim.structure.Value;
import swim.structure.collections.ValueKeyedList;
import swim.util.KeyedList;
public class ListDataView<V> extends ValueKeyedList<V> implements ListData<V>, ListDataContext {
public ListDataView(ListDataBinding dataBinding, Form<V> valueForm) {
super(dataBinding, valueForm);
dataBinding.setDataContext(this);
}
public ListDataBinding dataBinding() {
return (ListDataBinding) this.inner;
}
@Override
public Value name() {
return ((ListDataBinding) this.inner).name();
}
public <V> ListDataView<V> valueForm(Form<V> valueForm) {
return new ListDataView<V>((ListDataBinding) this.inner, valueForm);
}
public <V> ListDataView<V> valueClass(Class<V> valueClass) {
return valueForm(Form.<V>forClass(valueClass));
}
@Override
public boolean isResident() {
return ((ListDataBinding) this.inner).isResident();
}
@Override
public ListDataView<V> isResident(boolean isResident) {
((ListDataBinding) this.inner).isResident(isResident);
return this;
}
@Override
public boolean isTransient() {
return ((ListDataBinding) this.inner).isTransient();
}
@Override
public ListDataView<V> isTransient(boolean isTransient) {
((ListDataBinding) this.inner).isTransient(isTransient);
return this;
}
@Override
public void drop(int lower) {
((ListDataBinding) this.inner).drop(lower);
}
@Override
public void take(int upper) {
((ListDataBinding) this.inner).take(upper);
}
@Override
public KeyedList<V> snapshot() {
return new ValueKeyedList<V>(((ListDataBinding) this.inner).snapshot(), this.valueForm);
}
@Override
public void close() {
((ListDataBinding) this.inner).close();
}
@Override
public void didChange() {
// stub
}
@Override
public void didCommit() {
// stub
}
@Override
public void didUpdate(long index, Value newValue, Value oldValue) {
// stub
}
@Override
public void didInsert(long index, Value newValue) {
// stub
}
@Override
public void didRemove(long index, Value oldValue) {
// stub
}
@Override
public void didDrop(long lower) {
// stub
}
@Override
public void didTake(long upper) {
// stub
}
@Override
public void didClear() {
// stub
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/MapDataBinding.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.MapData;
import swim.structure.Value;
public interface MapDataBinding extends MapData<Value, Value>, DataBinding {
@Override
MapDataContext dataContext();
void setDataContext(MapDataContext dataContext);
@Override
MapDataBinding isResident(boolean isResident);
@Override
MapDataBinding isTransient(boolean isTransient);
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/MapDataContext.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.structure.Value;
public interface MapDataContext extends DataContext {
void didUpdate(Value key, Value newValue, Value oldValue);
void didRemove(Value key, Value oldValue);
void didDrop(long lower);
void didTake(long upper);
void didClear();
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/MapDataProxy.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import swim.api.data.MapData;
import swim.structure.Form;
import swim.structure.Value;
import swim.util.Cursor;
import swim.util.OrderedMap;
import swim.util.OrderedMapCursor;
public class MapDataProxy implements MapDataBinding, MapDataContext {
protected final MapDataBinding dataBinding;
protected MapDataContext dataContext;
public MapDataProxy(MapDataBinding dataBinding) {
this.dataBinding = dataBinding;
}
public final MapDataBinding dataBinding() {
return this.dataBinding;
}
@Override
public final MapDataContext dataContext() {
return this.dataContext;
}
@Override
public void setDataContext(MapDataContext dataContext) {
this.dataContext = dataContext;
this.dataBinding.setDataContext(this);
}
@Override
public StoreBinding storeBinding() {
return this.dataBinding.storeBinding();
}
@Override
public void setStoreBinding(StoreBinding storeBinding) {
this.dataBinding.setStoreBinding(storeBinding);
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapData(Class<T> dataClass) {
if (dataClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.dataBinding.unwrapData(dataClass);
}
}
@Override
public Value name() {
return this.dataBinding.name();
}
@Override
public long dataSize() {
return this.dataBinding.dataSize();
}
@Override
public Form<Value> keyForm() {
return Form.forValue();
}
@Override
public <K> MapData<K, Value> keyForm(Form<K> keyForm) {
return new MapDataView<K, Value>(this, keyForm, Form.forValue());
}
@Override
public <K> MapData<K, Value> keyClass(Class<K> keyClass) {
return keyForm(Form.<K>forClass(keyClass));
}
@Override
public Form<Value> valueForm() {
return Form.forValue();
}
@Override
public <V> MapData<Value, V> valueForm(Form<V> valueForm) {
return new MapDataView<Value, V>(this, Form.forValue(), valueForm);
}
@Override
public <V> MapData<Value, V> valueClass(Class<V> valueClass) {
return valueForm(Form.<V>forClass(valueClass));
}
@Override
public boolean isResident() {
return this.dataBinding.isResident();
}
@Override
public MapDataBinding isResident(boolean isResident) {
this.dataBinding.isResident(isResident);
return this;
}
@Override
public boolean isTransient() {
return this.dataBinding.isTransient();
}
@Override
public MapDataBinding isTransient(boolean isTransient) {
this.dataBinding.isTransient(isTransient);
return this;
}
@Override
public boolean isEmpty() {
return this.dataBinding.isEmpty();
}
@Override
public int size() {
return this.dataBinding.size();
}
@Override
public boolean containsKey(Object key) {
return this.dataBinding.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.dataBinding.containsValue(value);
}
@Override
public int indexOf(Object key) {
return this.dataBinding.indexOf(key);
}
@Override
public Value get(Object key) {
return this.dataBinding.get(key);
}
@Override
public Entry<Value, Value> getEntry(Object key) {
return this.dataBinding.getEntry(key);
}
@Override
public Entry<Value, Value> getIndex(int index) {
return this.dataBinding.getIndex(index);
}
@Override
public Entry<Value, Value> firstEntry() {
return this.dataBinding.firstEntry();
}
@Override
public Value firstKey() {
return this.dataBinding.firstKey();
}
@Override
public Value firstValue() {
return this.dataBinding.firstValue();
}
@Override
public Entry<Value, Value> lastEntry() {
return this.dataBinding.lastEntry();
}
@Override
public Value lastKey() {
return this.dataBinding.lastKey();
}
@Override
public Value lastValue() {
return this.dataBinding.lastValue();
}
@Override
public Entry<Value, Value> nextEntry(Value key) {
return this.dataBinding.nextEntry(key);
}
@Override
public Value nextKey(Value key) {
return this.dataBinding.nextKey(key);
}
@Override
public Value nextValue(Value key) {
return this.dataBinding.nextValue(key);
}
@Override
public Entry<Value, Value> previousEntry(Value key) {
return this.dataBinding.previousEntry(key);
}
@Override
public Value previousKey(Value key) {
return this.dataBinding.previousKey(key);
}
@Override
public Value previousValue(Value key) {
return this.dataBinding.previousValue(key);
}
@Override
public Value put(Value key, Value value) {
return this.dataBinding.put(key, value);
}
@Override
public void putAll(Map<? extends Value, ? extends Value> items) {
this.dataBinding.putAll(items);
}
@Override
public Value remove(Object key) {
return this.dataBinding.remove(key);
}
@Override
public void drop(int lower) {
this.dataBinding.drop(lower);
}
@Override
public void take(int upper) {
this.dataBinding.take(upper);
}
@Override
public void clear() {
this.dataBinding.clear();
}
@Override
public OrderedMap<Value, Value> headMap(Value toKey) {
return this.dataBinding.headMap(toKey);
}
@Override
public OrderedMap<Value, Value> tailMap(Value fromKey) {
return this.dataBinding.tailMap(fromKey);
}
@Override
public OrderedMap<Value, Value> subMap(Value fromKey, Value toKey) {
return this.dataBinding.subMap(fromKey, toKey);
}
@Override
public Set<Entry<Value, Value>> entrySet() {
return this.dataBinding.entrySet();
}
@Override
public Set<Value> keySet() {
return this.dataBinding.keySet();
}
@Override
public Collection<Value> values() {
return this.dataBinding.values();
}
@Override
public OrderedMapCursor<Value, Value> iterator() {
return this.dataBinding.iterator();
}
@Override
public Cursor<Value> keyIterator() {
return this.dataBinding.keyIterator();
}
@Override
public Cursor<Value> valueIterator() {
return this.dataBinding.valueIterator();
}
@Override
public OrderedMap<Value, Value> snapshot() {
return this.dataBinding.snapshot();
}
@Override
public Comparator<? super Value> comparator() {
return this.dataBinding.comparator();
}
@Override
public void close() {
this.dataBinding.close();
}
@Override
public void didChange() {
this.dataContext.didChange();
}
@Override
public void didCommit() {
this.dataContext.didCommit();
}
@Override
public void didUpdate(Value key, Value newValue, Value oldValue) {
this.dataContext.didUpdate(key, newValue, oldValue);
}
@Override
public void didRemove(Value key, Value oldValue) {
this.dataContext.didRemove(key, oldValue);
}
@Override
public void didDrop(long lower) {
this.dataContext.didDrop(lower);
}
@Override
public void didTake(long upper) {
this.dataContext.didTake(upper);
}
@Override
public void didClear() {
this.dataContext.didClear();
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/MapDataView.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.MapData;
import swim.structure.Form;
import swim.structure.Value;
import swim.structure.collections.ValueEntry;
import swim.structure.collections.ValueOrderedMap;
import swim.util.OrderedMap;
public class MapDataView<K, V> extends ValueOrderedMap<K, V> implements MapData<K, V>, MapDataContext {
public MapDataView(MapDataBinding dataBinding, Form<K> keyForm, Form<V> valueForm) {
super(dataBinding, keyForm, valueForm);
dataBinding.setDataContext(this);
}
public MapDataBinding dataBinding() {
return (MapDataBinding) this.inner;
}
@Override
public Value name() {
return ((MapDataBinding) this.inner).name();
}
public <K2> MapDataView<K2, V> keyForm(Form<K2> keyForm) {
return new MapDataView<K2, V>((MapDataBinding) this.inner, keyForm, this.valueForm);
}
public <K2> MapDataView<K2, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
public <V2> MapDataView<K, V2> valueForm(Form<V2> valueForm) {
return new MapDataView<K, V2>((MapDataBinding) this.inner, this.keyForm, valueForm);
}
public <V2> MapDataView<K, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
@Override
public boolean isResident() {
return ((MapDataBinding) this.inner).isResident();
}
@Override
public MapDataView<K, V> isResident(boolean isResident) {
((MapDataBinding) this.inner).isResident(isResident);
return this;
}
@Override
public boolean isTransient() {
return ((MapDataBinding) this.inner).isTransient();
}
@Override
public MapDataView<K, V> isTransient(boolean isTransient) {
((MapDataBinding) this.inner).isTransient(isTransient);
return this;
}
@Override
public Entry<K, V> getIndex(int index) {
final Entry<Value, Value> entry = ((MapDataBinding) this.inner).getIndex(index);
if (entry != null) {
return new ValueEntry<K, V>(entry, this.keyForm, this.valueForm);
} else {
return null;
}
}
@Override
public void drop(int lower) {
((MapDataBinding) this.inner).drop(lower);
}
@Override
public void take(int upper) {
((MapDataBinding) this.inner).take(upper);
}
@Override
public OrderedMap<K, V> snapshot() {
return new ValueOrderedMap<K, V>(((MapDataBinding) this.inner).snapshot(), this.keyForm, this.valueForm);
}
@Override
public void close() {
((MapDataBinding) this.inner).close();
}
@Override
public void didChange() {
// stub
}
@Override
public void didCommit() {
// stub
}
@Override
public void didUpdate(Value key, Value newValue, Value oldValue) {
// stub
}
@Override
public void didRemove(Value key, Value oldValue) {
// stub
}
@Override
public void didDrop(long lower) {
// stub
}
@Override
public void didTake(long upper) {
// stub
}
@Override
public void didClear() {
// stub
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/SpatialDataBinding.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.SpatialData;
import swim.structure.Value;
public interface SpatialDataBinding<S> extends SpatialData<Value, S, Value>, DataBinding {
@Override
SpatialDataContext<S> dataContext();
void setDataContext(SpatialDataContext<S> dataContext);
@Override
SpatialDataBinding<S> isResident(boolean isResident);
@Override
SpatialDataBinding<S> isTransient(boolean isTransient);
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/SpatialDataContext.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.structure.Value;
public interface SpatialDataContext<S> extends DataContext {
void didUpdate(Value key, long x, long y, Value newValue, Value oldValue);
void didMove(Value key, long newX, long newY, Value newValue, long oldX, long oldY, Value oldValue);
void didRemove(Value key, long x, long y, Value oldValue);
void didClear();
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/SpatialDataProxy.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import java.util.Iterator;
import swim.api.data.SpatialData;
import swim.math.Z2Form;
import swim.spatial.SpatialMap;
import swim.structure.Form;
import swim.structure.Value;
public class SpatialDataProxy<S> implements SpatialDataBinding<S>, SpatialDataContext<S> {
protected final SpatialDataBinding<S> dataBinding;
protected SpatialDataContext<S> dataContext;
public SpatialDataProxy(SpatialDataBinding<S> dataBinding) {
this.dataBinding = dataBinding;
}
public final SpatialDataBinding<S> dataBinding() {
return this.dataBinding;
}
@Override
public final SpatialDataContext<S> dataContext() {
return this.dataContext;
}
@Override
public void setDataContext(SpatialDataContext<S> dataContext) {
this.dataContext = dataContext;
this.dataBinding.setDataContext(this);
}
@Override
public StoreBinding storeBinding() {
return this.dataBinding.storeBinding();
}
@Override
public void setStoreBinding(StoreBinding storeBinding) {
this.dataBinding.setStoreBinding(storeBinding);
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapData(Class<T> dataClass) {
if (dataClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.dataBinding.unwrapData(dataClass);
}
}
@Override
public Value name() {
return this.dataBinding.name();
}
@Override
public long dataSize() {
return this.dataBinding.dataSize();
}
@Override
public Form<Value> keyForm() {
return Form.forValue();
}
@Override
public <K> SpatialData<K, S, Value> keyForm(Form<K> keyForm) {
return new SpatialDataView<K, S, Value>(this, keyForm, Form.forValue());
}
@Override
public <K> SpatialData<K, S, Value> keyClass(Class<K> keyClass) {
return keyForm(Form.<K>forClass(keyClass));
}
@Override
public Z2Form<S> shapeForm() {
return this.dataBinding.shapeForm();
}
@Override
public Form<Value> valueForm() {
return Form.forValue();
}
@Override
public <V> SpatialData<Value, S, V> valueForm(Form<V> valueForm) {
return new SpatialDataView<Value, S, V>(this, Form.forValue(), valueForm);
}
@Override
public <V> SpatialData<Value, S, V> valueClass(Class<V> valueClass) {
return valueForm(Form.<V>forClass(valueClass));
}
@Override
public boolean isResident() {
return this.dataBinding.isResident();
}
@Override
public SpatialDataBinding<S> isResident(boolean isResident) {
this.dataBinding.isResident(isResident);
return this;
}
@Override
public boolean isTransient() {
return this.dataBinding.isTransient();
}
@Override
public SpatialDataBinding<S> isTransient(boolean isTransient) {
this.dataBinding.isTransient(isTransient);
return this;
}
@Override
public boolean isEmpty() {
return this.dataBinding.isEmpty();
}
@Override
public int size() {
return this.dataBinding.size();
}
@Override
public boolean containsKey(Value key, S shape) {
return this.dataBinding.containsKey(key, shape);
}
@Override
public boolean containsKey(Object key) {
return this.dataBinding.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.dataBinding.containsValue(value);
}
@Override
public Value get(Value key, S shape) {
return this.dataBinding.get(key, shape);
}
@Override
public Value get(Object key) {
return this.dataBinding.get(key);
}
@Override
public Value put(Value key, S shape, Value newValue) {
return this.dataBinding.put(key, shape, newValue);
}
@Override
public Value move(Value key, S oldShape, S newShape, Value newValue) {
return this.dataBinding.move(key, oldShape, newShape, newValue);
}
@Override
public Value remove(Value key, S shape) {
return this.dataBinding.remove(key, shape);
}
@Override
public void clear() {
this.dataBinding.clear();
}
@Override
public Iterator<Entry<Value, S, Value>> iterator(S shape) {
return this.dataBinding.iterator(shape);
}
@Override
public Iterator<Entry<Value, S, Value>> iterator() {
return this.dataBinding.iterator();
}
@Override
public Iterator<Value> keyIterator() {
return this.dataBinding.keyIterator();
}
@Override
public Iterator<Value> valueIterator() {
return this.dataBinding.valueIterator();
}
@Override
public SpatialMap<Value, S, Value> snapshot() {
return this.dataBinding.snapshot();
}
@Override
public void close() {
this.dataBinding.close();
}
@Override
public void didChange() {
this.dataContext.didChange();
}
@Override
public void didCommit() {
this.dataContext.didCommit();
}
@Override
public void didUpdate(Value key, long x, long y, Value newValue, Value oldValue) {
this.dataContext.didUpdate(key, x, y, newValue, oldValue);
}
@Override
public void didMove(Value key, long newX, long newY, Value newValue, long oldX, long oldY, Value oldValue) {
this.dataContext.didMove(key, newX, newY, newValue, oldX, oldY, oldValue);
}
@Override
public void didRemove(Value key, long x, long y, Value oldValue) {
this.dataContext.didRemove(key, x, y, oldValue);
}
@Override
public void didClear() {
this.dataContext.didClear();
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/SpatialDataView.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.SpatialData;
import swim.math.Z2Form;
import swim.spatial.SpatialMap;
import swim.spatial.SpatialValueMap;
import swim.structure.Form;
import swim.structure.Value;
public class SpatialDataView<K, S, V> extends SpatialValueMap<K, S, V> implements SpatialData<K, S, V>, SpatialDataContext<S> {
public SpatialDataView(SpatialDataBinding<S> dataBinding, Form<K> keyForm, Form<V> valueForm) {
super(dataBinding, keyForm, valueForm);
dataBinding.setDataContext(this);
}
@SuppressWarnings("unchecked")
public SpatialDataBinding<S> dataBinding() {
return (SpatialDataBinding<S>) this.inner;
}
@Override
public Value name() {
return ((SpatialDataBinding<?>) this.inner).name();
}
@SuppressWarnings("unchecked")
public <K2> SpatialDataView<K2, S, V> keyForm(Form<K2> keyForm) {
return new SpatialDataView<K2, S, V>((SpatialDataBinding<S>) this.inner, keyForm, this.valueForm);
}
public <K2> SpatialDataView<K2, S, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
@SuppressWarnings("unchecked")
@Override
public Z2Form<S> shapeForm() {
return ((SpatialDataBinding<S>) this.inner).shapeForm();
}
@SuppressWarnings("unchecked")
public <V2> SpatialDataView<K, S, V2> valueForm(Form<V2> valueForm) {
return new SpatialDataView<K, S, V2>((SpatialDataBinding<S>) this.inner, this.keyForm, valueForm);
}
public <V2> SpatialDataView<K, S, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
@Override
public boolean isResident() {
return ((SpatialDataBinding<?>) this.inner).isResident();
}
@Override
public SpatialDataView<K, S, V> isResident(boolean isResident) {
((SpatialDataBinding<?>) this.inner).isResident(isResident);
return this;
}
@Override
public boolean isTransient() {
return ((SpatialDataBinding<?>) this.inner).isTransient();
}
@Override
public SpatialDataView<K, S, V> isTransient(boolean isTransient) {
((SpatialDataBinding<?>) this.inner).isTransient(isTransient);
return this;
}
@SuppressWarnings("unchecked")
@Override
public SpatialMap<K, S, V> snapshot() {
return new SpatialValueMap<K, S, V>(((SpatialDataBinding<S>) this.inner).snapshot(), this.keyForm, this.valueForm);
}
@Override
public void close() {
((SpatialDataBinding<?>) this.inner).close();
}
@Override
public void didChange() {
// stub
}
@Override
public void didCommit() {
// stub
}
@Override
public void didUpdate(Value key, long x, long y, Value newValue, Value oldValue) {
// stub
}
@Override
public void didMove(Value key, long newX, long newY, Value newValue,
long oldX, long oldY, Value oldValue) {
// stub
}
@Override
public void didRemove(Value key, long x, long y, Value oldValue) {
// stub
}
@Override
public void didClear() {
// stub
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/StoreBinding.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import java.util.Iterator;
import swim.api.store.Store;
import swim.structure.Value;
public interface StoreBinding extends Store {
StoreContext storeContext();
void setStoreContext(StoreContext storeContext);
Iterator<DataBinding> dataBindings();
void closeData(Value name);
void close();
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/StoreContext.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.math.Z2Form;
import swim.structure.Value;
public interface StoreContext {
StoreBinding openStore(Value name);
StoreBinding injectStore(StoreBinding storeBinding);
ListDataBinding openListData(Value name);
ListDataBinding injectListData(ListDataBinding dataBinding);
MapDataBinding openMapData(Value name);
MapDataBinding injectMapData(MapDataBinding dataBinding);
<S> SpatialDataBinding<S> openSpatialData(Value name, Z2Form<S> shapeForm);
<S> SpatialDataBinding<S> injectSpatialData(SpatialDataBinding<S> dataBinding);
ValueDataBinding openValueData(Value name);
ValueDataBinding injectValueData(ValueDataBinding dataBinding);
void close();
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/StoreDef.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
public interface StoreDef {
String storeName();
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/StoreProxy.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import java.util.Iterator;
import swim.api.data.ListData;
import swim.api.data.MapData;
import swim.api.data.SpatialData;
import swim.api.data.ValueData;
import swim.math.R2Shape;
import swim.math.Z2Form;
import swim.spatial.GeoProjection;
import swim.structure.Text;
import swim.structure.Value;
public class StoreProxy implements StoreBinding, StoreContext {
protected final StoreBinding storeBinding;
protected StoreContext storeContext;
public StoreProxy(StoreBinding storeBinding) {
this.storeBinding = storeBinding;
}
public final StoreBinding storeBinding() {
return this.storeBinding;
}
@Override
public final StoreContext storeContext() {
return this.storeContext;
}
@Override
public void setStoreContext(StoreContext storeContext) {
this.storeContext = storeContext;
this.storeBinding.setStoreContext(this);
}
@Override
public Iterator<DataBinding> dataBindings() {
return this.storeBinding.dataBindings();
}
@Override
public void closeData(Value name) {
this.storeBinding.closeData(name);
}
@Override
public void close() {
this.storeContext.close();
}
@Override
public StoreBinding openStore(Value name) {
return this.storeContext.openStore(name);
}
@Override
public StoreBinding injectStore(StoreBinding storeBinding) {
return this.storeContext.injectStore(storeBinding);
}
@Override
public ListDataBinding openListData(Value name) {
return this.storeContext.openListData(name);
}
@Override
public ListDataBinding injectListData(ListDataBinding dataBinding) {
return this.storeContext.injectListData(dataBinding);
}
@Override
public MapDataBinding openMapData(Value name) {
return this.storeContext.openMapData(name);
}
@Override
public MapDataBinding injectMapData(MapDataBinding dataBinding) {
return this.storeContext.injectMapData(dataBinding);
}
@Override
public <S> SpatialDataBinding<S> openSpatialData(Value name, Z2Form<S> shapeForm) {
return this.storeContext.openSpatialData(name, shapeForm);
}
@Override
public <S> SpatialDataBinding<S> injectSpatialData(SpatialDataBinding<S> dataBinding) {
return this.storeContext.injectSpatialData(dataBinding);
}
@Override
public ValueDataBinding openValueData(Value name) {
return this.storeContext.openValueData(name);
}
@Override
public ValueDataBinding injectValueData(ValueDataBinding dataBinding) {
return this.storeContext.injectValueData(dataBinding);
}
@Override
public ListData<Value> listData(Value name) {
ListDataBinding dataBinding = openListData(name);
dataBinding = injectListData(dataBinding);
return dataBinding;
}
@Override
public ListData<Value> listData(String name) {
return listData(Text.from(name));
}
@Override
public MapData<Value, Value> mapData(Value name) {
MapDataBinding dataBinding = openMapData(name);
dataBinding = injectMapData(dataBinding);
return dataBinding;
}
@Override
public MapData<Value, Value> mapData(String name) {
return mapData(Text.from(name));
}
@Override
public <S> SpatialData<Value, S, Value> spatialData(Value name, Z2Form<S> shapeForm) {
SpatialDataBinding<S> dataBinding = openSpatialData(name, shapeForm);
dataBinding = injectSpatialData(dataBinding);
return dataBinding;
}
@Override
public <S> SpatialData<Value, S, Value> spatialData(String name, Z2Form<S> shapeForm) {
return spatialData(Text.from(name), shapeForm);
}
@Override
public SpatialData<Value, R2Shape, Value> geospatialData(Value name) {
return spatialData(name, GeoProjection.wgs84Form());
}
@Override
public SpatialData<Value, R2Shape, Value> geospatialData(String name) {
return geospatialData(Text.from(name));
}
@Override
public ValueData<Value> valueData(Value name) {
ValueDataBinding dataBinding = openValueData(name);
dataBinding = injectValueData(dataBinding);
return dataBinding;
}
@Override
public ValueData<Value> valueData(String name) {
return valueData(Text.from(name));
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/ValueDataBinding.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.ValueData;
import swim.structure.Value;
public interface ValueDataBinding extends ValueData<Value>, DataBinding {
@Override
ValueDataContext dataContext();
void setDataContext(ValueDataContext dataContext);
@Override
ValueDataBinding isResident(boolean isResident);
@Override
ValueDataBinding isTransient(boolean isTransient);
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/ValueDataContext.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.structure.Value;
public interface ValueDataContext extends DataContext {
void didSet(Value newValue, Value oldValue);
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/ValueDataProxy.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.ValueData;
import swim.structure.Form;
import swim.structure.Value;
public class ValueDataProxy implements ValueDataBinding, ValueDataContext {
protected final ValueDataBinding dataBinding;
protected ValueDataContext dataContext;
public ValueDataProxy(ValueDataBinding dataBinding) {
this.dataBinding = dataBinding;
}
public final ValueDataBinding dataBinding() {
return this.dataBinding;
}
@Override
public final ValueDataContext dataContext() {
return this.dataContext;
}
@Override
public void setDataContext(ValueDataContext dataContext) {
this.dataContext = dataContext;
this.dataBinding.setDataContext(this);
}
@Override
public StoreBinding storeBinding() {
return this.dataBinding.storeBinding();
}
@Override
public void setStoreBinding(StoreBinding storeBinding) {
this.dataBinding.setStoreBinding(storeBinding);
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapData(Class<T> dataClass) {
if (dataClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.dataBinding.unwrapData(dataClass);
}
}
@Override
public Value name() {
return this.dataBinding.name();
}
@Override
public long dataSize() {
return this.dataBinding.dataSize();
}
@Override
public Form<Value> valueForm() {
return Form.forValue();
}
@Override
public <V> ValueData<V> valueForm(Form<V> valueForm) {
return new ValueDataView<V>(this, valueForm);
}
@Override
public <V> ValueData<V> valueClass(Class<V> valueClass) {
return valueForm(Form.<V>forClass(valueClass));
}
@Override
public boolean isResident() {
return this.dataBinding.isResident();
}
@Override
public ValueDataBinding isResident(boolean isResident) {
this.dataBinding.isResident(isResident);
return this;
}
@Override
public boolean isTransient() {
return this.dataBinding.isTransient();
}
@Override
public ValueDataBinding isTransient(boolean isTransient) {
this.dataBinding.isTransient(isTransient);
return this;
}
@Override
public Value get() {
return this.dataBinding.get();
}
@Override
public Value set(Value newValue) {
return this.dataBinding.set(newValue);
}
@Override
public void close() {
this.dataBinding.close();
}
@Override
public void didChange() {
this.dataContext.didChange();
}
@Override
public void didCommit() {
this.dataContext.didCommit();
}
@Override
public void didSet(Value newValue, Value oldValue) {
this.dataContext.didSet(newValue, oldValue);
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/ValueDataView.java | // Copyright 2015-2019 SWIM.AI 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 swim.store;
import swim.api.data.ValueData;
import swim.structure.Form;
import swim.structure.Value;
public class ValueDataView<V> implements ValueData<V>, ValueDataContext {
protected final ValueDataBinding dataBinding;
protected final Form<V> valueForm;
public ValueDataView(ValueDataBinding dataBinding, Form<V> valueForm) {
this.dataBinding = dataBinding;
this.valueForm = valueForm;
}
public ValueDataBinding dataBinding() {
return this.dataBinding;
}
@Override
public Value name() {
return this.dataBinding.name();
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
public <V2> ValueDataView<V2> valueForm(Form<V2> valueForm) {
return new ValueDataView<V2>(this.dataBinding, valueForm);
}
public <V2> ValueDataView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
@Override
public boolean isResident() {
return this.dataBinding.isResident();
}
@Override
public ValueDataView<V> isResident(boolean isResident) {
this.dataBinding.isResident(isResident);
return this;
}
@Override
public boolean isTransient() {
return this.dataBinding.isTransient();
}
@Override
public ValueDataView<V> isTransient(boolean isTransient) {
this.dataBinding.isTransient(isTransient);
return this;
}
@Override
public V get() {
final Value value = this.dataBinding.get();
final V valueObject = this.valueForm.cast(value);
if (valueObject != null) {
return valueObject;
}
return this.valueForm.unit();
}
@Override
public V set(V newValueObject) {
final Value newValue = this.valueForm.mold(newValueObject).toValue();
final Value oldValue = this.dataBinding.set(newValue);
final V oldValueObject = this.valueForm.cast(oldValue);
if (oldValueObject != null) {
return oldValueObject;
}
return this.valueForm.unit();
}
@Override
public void close() {
this.dataBinding.close();
}
@Override
public void didChange() {
// stub
}
@Override
public void didCommit() {
// stub
}
@Override
public void didSet(Value newValue, Value oldValue) {
// stub
}
}
|
0 | java-sources/ai/swim/swim-store/3.10.0/swim | java-sources/ai/swim/swim-store/3.10.0/swim/store/package-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Storage runtime interface.
*/
package swim.store;
|
0 | java-sources/ai/swim/swim-store-mem | java-sources/ai/swim/swim-store-mem/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* In-memory storage runtime.
*/
module swim.store.mem {
requires transitive swim.collections;
requires transitive swim.spatial;
requires transitive swim.store;
requires transitive swim.kernel;
exports swim.store.mem;
provides swim.kernel.Kernel with swim.store.mem.MemStoreKernel;
}
|
0 | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store/mem/ListDataModel.java | // Copyright 2015-2019 SWIM.AI 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 swim.store.mem;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import swim.api.data.ListData;
import swim.collections.STreeList;
import swim.store.ListDataBinding;
import swim.store.ListDataContext;
import swim.store.ListDataView;
import swim.store.StoreBinding;
import swim.structure.Form;
import swim.structure.Value;
import swim.util.KeyedList;
public class ListDataModel implements ListDataBinding {
protected final Value name;
protected final STreeList<Value> tree;
protected ListDataContext dataContext;
protected StoreBinding storeBinding;
public ListDataModel(Value name, STreeList<Value> tree) {
this.name = name;
this.tree = tree;
}
@Override
public ListDataContext dataContext() {
return this.dataContext;
}
@Override
public void setDataContext(ListDataContext dataContext) {
this.dataContext = dataContext;
}
@Override
public StoreBinding storeBinding() {
return this.storeBinding;
}
@Override
public void setStoreBinding(StoreBinding storeBinding) {
this.storeBinding = storeBinding;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapData(Class<T> dataClass) {
if (dataClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
public final STreeList<Value> tree() {
return this.tree;
}
@Override
public final Value name() {
return this.name;
}
@Override
public Form<Value> valueForm() {
return Form.forValue();
}
@Override
public <V2> ListData<V2> valueForm(Form<V2> valueForm) {
return new ListDataView<V2>(this, valueForm);
}
@Override
public <V2> ListData<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
@Override
public long dataSize() {
return 0;
}
@Override
public boolean isResident() {
return true;
}
@Override
public ListDataModel isResident(boolean isResident) {
return this;
}
@Override
public boolean isTransient() {
return true;
}
@Override
public ListDataModel isTransient(boolean isTransient) {
return this;
}
@Override
public int size() {
return this.tree.size();
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean contains(Object value) {
return this.tree.contains(value);
}
@Override
public boolean containsAll(Collection<?> values) {
return this.tree.containsAll(values);
}
@Override
public int indexOf(Object value) {
return this.tree.indexOf(value);
}
@Override
public int lastIndexOf(Object value) {
return this.tree.lastIndexOf(value);
}
@Override
public Value get(int index) {
return this.tree.get(index);
}
@Override
public Value set(int index, Value value) {
return this.tree.set(index, value.commit());
}
@Override
public boolean add(Value value) {
return this.tree.add(value.commit());
}
@Override
public boolean addAll(Collection<? extends Value> values) {
for (Value v : values) {
v.commit();
}
return this.tree.addAll(values);
}
@Override
public void add(int index, Value value) {
this.tree.add(index, value.commit());
}
@Override
public boolean addAll(int index, Collection<? extends Value> values) {
return this.tree.addAll(index, values);
}
@Override
public Value remove(int index) {
return this.tree.remove(index);
}
@Override
public boolean remove(Object value) {
return this.tree.remove(value);
}
@Override
public boolean removeAll(Collection<?> values) {
return this.tree.removeAll(values);
}
@Override
public boolean retainAll(Collection<?> values) {
return this.tree.retainAll(values);
}
@Override
public void drop(int lower) {
this.tree.drop(lower);
}
@Override
public void take(int upper) {
this.tree.take(upper);
}
@Override
public void clear() {
this.tree.clear();
}
@Override
public Iterator<Value> iterator() {
return this.tree.iterator();
}
@Override
public ListIterator<Value> listIterator() {
return this.tree.listIterator();
}
@Override
public ListIterator<Value> listIterator(int index) {
return this.tree.listIterator(index);
}
@Override
public List<Value> subList(int fromIndex, int toIndex) {
return this.tree.subList(fromIndex, toIndex);
}
/**
* An immutable copy of this {@code STreeList}'s data.
*/
@Override
public KeyedList<Value> snapshot() {
return this.tree.snapshot();
}
@Override
public Object[] toArray() {
return this.tree.toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return this.tree.toArray(array);
}
@Override
public void close() {
final StoreBinding storeBinding = this.storeBinding;
if (storeBinding != null) {
storeBinding.closeData(this.name);
}
}
@Override
public Value get(int index, Object key) {
return this.tree.get(index, key);
}
@Override
public Map.Entry<Object, Value> getEntry(int index) {
return this.tree.getEntry(index);
}
@Override
public Map.Entry<Object, Value> getEntry(int index, Object key) {
return this.tree.getEntry(index, key);
}
@Override
public Value set(int index, Value element, Object key) {
return this.tree.set(index, element.commit(), key);
}
@Override
public boolean add(Value element, Object key) {
return this.tree.add(element.commit(), key);
}
@Override
public void add(int index, Value element, Object key) {
this.tree.add(index, element.commit(), key);
}
@Override
public Value remove(int index, Object key) {
return this.tree.remove(index, key);
}
@Override
public void move(int fromIndex, int toIndex) {
this.tree.move(fromIndex, toIndex);
}
@Override
public void move(int fromIndex, int toIndex, Object key) {
this.tree.move(fromIndex, toIndex, key);
}
@Override
public ListIterator<Object> keyIterator() {
return this.tree.keyIterator();
}
@Override
public ListIterator<Map.Entry<Object, Value>> entryIterator() {
return this.tree.entryIterator();
}
}
|
0 | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store/mem/MapDataModel.java | // Copyright 2015-2019 SWIM.AI 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 swim.store.mem;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import swim.api.data.MapData;
import swim.collections.BTreeMap;
import swim.store.MapDataBinding;
import swim.store.MapDataContext;
import swim.store.MapDataView;
import swim.store.StoreBinding;
import swim.structure.Form;
import swim.structure.Value;
import swim.util.Cursor;
import swim.util.OrderedMap;
import swim.util.OrderedMapCursor;
public class MapDataModel implements MapDataBinding {
protected final Value name;
protected final BTreeMap<Value, Value, Value> tree;
protected MapDataContext dataContext;
protected StoreBinding storeBinding;
public MapDataModel(Value name, BTreeMap<Value, Value, Value> tree) {
this.name = name;
this.tree = tree;
}
@Override
public MapDataContext dataContext() {
return this.dataContext;
}
@Override
public void setDataContext(MapDataContext dataContext) {
this.dataContext = dataContext;
}
@Override
public StoreBinding storeBinding() {
return this.storeBinding;
}
@Override
public void setStoreBinding(StoreBinding storeBinding) {
this.storeBinding = storeBinding;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapData(Class<T> dataClass) {
if (dataClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
public final BTreeMap<Value, Value, Value> tree() {
return this.tree;
}
@Override
public final Value name() {
return this.name;
}
@Override
public Form<Value> keyForm() {
return Form.forValue();
}
@Override
public <K2> MapData<K2, Value> keyForm(Form<K2> keyForm) {
return new MapDataView<K2, Value>(this, keyForm, Form.forValue());
}
@Override
public <K2> MapData<K2, Value> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
@Override
public Form<Value> valueForm() {
return Form.forValue();
}
@Override
public <V2> MapData<Value, V2> valueForm(Form<V2> valueForm) {
return new MapDataView<Value, V2>(this, Form.forValue(), valueForm);
}
@Override
public <V2> MapData<Value, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
@Override
public long dataSize() {
return 0;
}
@Override
public boolean isResident() {
return true;
}
@Override
public MapDataBinding isResident(boolean isResident) {
return this;
}
@Override
public boolean isTransient() {
return true;
}
@Override
public MapDataBinding isTransient(boolean isTransient) {
return this;
}
@Override
public boolean isEmpty() {
return this.tree.isEmpty();
}
@Override
public int size() {
return this.tree.size();
}
@Override
public boolean containsKey(Object key) {
return this.tree.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.tree.containsValue(value);
}
@Override
public int indexOf(Object key) {
return this.tree.indexOf(key);
}
@Override
public Value get(Object key) {
Value res = this.tree.get(key);
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Entry<Value, Value> getEntry(Object key) {
return this.tree.getEntry(key);
}
@Override
public Entry<Value, Value> getIndex(int index) {
return this.tree.getIndex(index);
}
@Override
public Entry<Value, Value> firstEntry() {
return this.tree.firstEntry();
}
@Override
public Value firstKey() {
Value res = this.tree.firstKey();
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Value firstValue() {
Value res = this.tree.firstValue();
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Entry<Value, Value> lastEntry() {
return this.tree.lastEntry();
}
@Override
public Value lastKey() {
Value res = this.tree.lastKey();
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Value lastValue() {
Value res = this.tree.lastValue();
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Entry<Value, Value> nextEntry(Value key) {
return this.tree.nextEntry(key);
}
@Override
public Value nextKey(Value key) {
Value res = this.tree.nextKey(key);
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Value nextValue(Value key) {
Value res = this.tree.nextValue(key);
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Entry<Value, Value> previousEntry(Value key) {
return this.tree.previousEntry(key);
}
@Override
public Value previousKey(Value key) {
Value res = this.tree.previousKey(key);
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Value previousValue(Value key) {
Value res = this.tree.previousValue(key);
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public Value put(Value key, Value value) {
Value res = this.tree.put(key.commit(), value.commit());
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public void putAll(Map<? extends Value, ? extends Value> items) {
for (Map.Entry<? extends Value, ? extends Value> entry : items.entrySet()) {
entry.getKey().commit();
entry.getValue().commit();
}
this.tree.putAll(items);
}
@Override
public Value remove(Object key) {
Value res = this.tree.remove(key);
if (res == null) {
res = Value.absent();
}
return res;
}
@Override
public void drop(int lower) {
this.tree.drop(lower);
}
@Override
public void take(int upper) {
this.tree.take(upper);
}
@Override
public void clear() {
this.tree.clear();
}
@Override
public OrderedMap<Value, Value> headMap(Value toKey) {
return this.tree.headMap(toKey);
}
@Override
public OrderedMap<Value, Value> tailMap(Value fromKey) {
return this.tree.tailMap(fromKey);
}
@Override
public OrderedMap<Value, Value> subMap(Value fromKey, Value toKey) {
return this.tree.subMap(fromKey, toKey);
}
@Override
public Set<Entry<Value, Value>> entrySet() {
return this.tree.entrySet();
}
@Override
public Set<Value> keySet() {
return this.tree.keySet();
}
@Override
public Collection<Value> values() {
return this.tree.values();
}
@Override
public OrderedMapCursor<Value, Value> iterator() {
return this.tree.iterator();
}
@Override
public Cursor<Value> keyIterator() {
return this.tree.keyIterator();
}
@Override
public Cursor<Value> valueIterator() {
return this.tree.valueIterator();
}
@Override
public OrderedMap<Value, Value> snapshot() {
return this.tree.snapshot();
}
@Override
public Comparator<? super Value> comparator() {
return this.tree.comparator();
}
@Override
public void close() {
final StoreBinding storeBinding = this.storeBinding;
if (storeBinding != null) {
storeBinding.closeData(this.name);
}
}
}
|
0 | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store/mem/MemStore.java | // Copyright 2015-2019 SWIM.AI 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 swim.store.mem;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.data.ListData;
import swim.api.data.MapData;
import swim.api.data.SpatialData;
import swim.api.data.ValueData;
import swim.collections.BTreeMap;
import swim.collections.HashTrieMap;
import swim.collections.STreeList;
import swim.math.R2Shape;
import swim.math.Z2Form;
import swim.spatial.GeoProjection;
import swim.spatial.QTreeMap;
import swim.store.DataBinding;
import swim.store.ListDataBinding;
import swim.store.MapDataBinding;
import swim.store.SpatialDataBinding;
import swim.store.StoreBinding;
import swim.store.StoreContext;
import swim.store.ValueDataBinding;
import swim.structure.Text;
import swim.structure.Value;
public class MemStore implements StoreBinding, StoreContext {
protected StoreContext storeContext;
volatile HashTrieMap<Value, StoreBinding> stores;
volatile HashTrieMap<Value, DataBinding> trees;
public MemStore() {
this.stores = HashTrieMap.empty();
this.trees = HashTrieMap.empty();
}
@Override
public StoreContext storeContext() {
return this.storeContext != null ? this.storeContext : this;
}
@Override
public void setStoreContext(StoreContext storeContext) {
this.storeContext = storeContext;
}
@Override
public Iterator<DataBinding> dataBindings() {
return this.trees.valueIterator();
}
@Override
public void closeData(Value name) {
do {
final HashTrieMap<Value, DataBinding> oldTrees = this.trees;
final HashTrieMap<Value, DataBinding> newTrees = oldTrees.removed(name);
if (oldTrees != newTrees) {
if (TREES.compareAndSet(this, oldTrees, newTrees)) {
break;
}
} else {
break;
}
} while (true);
}
@Override
public void close() {
// nop
}
@Override
public StoreBinding openStore(Value name) {
StoreBinding store = null;
do {
final HashTrieMap<Value, StoreBinding> oldStores = this.stores;
final StoreBinding oldStore = oldStores.get(name);
if (oldStore != null) {
store = oldStore;
break;
} else {
if (store == null) {
store = new MemStore();
}
final HashTrieMap<Value, StoreBinding> newStores = oldStores.updated(name, store);
if (STORES.compareAndSet(this, oldStores, newStores)) {
break;
}
}
} while (true);
return store;
}
@Override
public StoreBinding injectStore(StoreBinding storeBinding) {
return storeBinding;
}
@Override
public ListDataBinding openListData(Value name) {
ListDataModel tree = null;
do {
final HashTrieMap<Value, DataBinding> oldTrees = this.trees;
final DataBinding oldTree = oldTrees.get(name);
if (oldTree != null) {
tree = (ListDataModel) oldTree;
break;
} else {
if (tree == null) {
tree = new ListDataModel(name, new STreeList<Value>());
}
final HashTrieMap<Value, DataBinding> newTrees = oldTrees.updated(name, tree);
if (TREES.compareAndSet(this, oldTrees, newTrees)) {
break;
}
}
} while (true);
return tree;
}
@Override
public ListDataBinding injectListData(ListDataBinding dataBinding) {
return dataBinding;
}
@Override
public MapDataBinding openMapData(Value name) {
MapDataModel tree = null;
do {
final HashTrieMap<Value, DataBinding> oldTrees = this.trees;
final DataBinding oldTree = oldTrees.get(name);
if (oldTree != null) {
tree = (MapDataModel) oldTree;
break;
} else {
if (tree == null) {
tree = new MapDataModel(name, new BTreeMap<Value, Value, Value>());
}
final HashTrieMap<Value, DataBinding> newTrees = oldTrees.updated(name, tree);
if (TREES.compareAndSet(this, oldTrees, newTrees)) {
break;
}
}
} while (true);
return tree;
}
@Override
public MapDataBinding injectMapData(MapDataBinding dataBinding) {
return dataBinding;
}
@SuppressWarnings("unchecked")
@Override
public <S> SpatialDataBinding<S> openSpatialData(Value name, Z2Form<S> shapeForm) {
SpatialDataModel<S> tree = null;
do {
final HashTrieMap<Value, DataBinding> oldTrees = this.trees;
final DataBinding oldTree = oldTrees.get(name);
if (oldTree != null) {
tree = (SpatialDataModel<S>) oldTree;
break;
} else {
if (tree == null) {
tree = new SpatialDataModel<S>(name, new QTreeMap<Value, S, Value>(shapeForm));
}
final HashTrieMap<Value, DataBinding> newTrees = oldTrees.updated(name, tree);
if (TREES.compareAndSet(this, oldTrees, newTrees)) {
break;
}
}
} while (true);
return tree;
}
@Override
public <S> SpatialDataBinding<S> injectSpatialData(SpatialDataBinding<S> dataBinding) {
return dataBinding;
}
@Override
public ValueDataBinding openValueData(Value name) {
ValueDataModel tree = null;
do {
final HashTrieMap<Value, DataBinding> oldTrees = this.trees;
final DataBinding oldTree = oldTrees.get(name);
if (oldTree != null) {
tree = (ValueDataModel) oldTree;
break;
} else {
if (tree == null) {
tree = new ValueDataModel(name, Value.absent());
}
final HashTrieMap<Value, DataBinding> newTrees = oldTrees.updated(name, tree);
if (TREES.compareAndSet(this, oldTrees, newTrees)) {
break;
}
}
} while (true);
return tree;
}
@Override
public ValueDataBinding injectValueData(ValueDataBinding dataBinding) {
return dataBinding;
}
@Override
public ListData<Value> listData(Value name) {
ListDataBinding dataBinding = openListData(name);
dataBinding = injectListData(dataBinding);
return dataBinding;
}
@Override
public ListData<Value> listData(String name) {
return listData(Text.from(name));
}
@Override
public MapData<Value, Value> mapData(Value name) {
MapDataBinding dataBinding = openMapData(name);
dataBinding = injectMapData(dataBinding);
return dataBinding;
}
@Override
public MapData<Value, Value> mapData(String name) {
return mapData(Text.from(name));
}
@Override
public <S> SpatialData<Value, S, Value> spatialData(Value name, Z2Form<S> shapeForm) {
SpatialDataBinding<S> dataBinding = openSpatialData(name, shapeForm);
dataBinding = injectSpatialData(dataBinding);
return dataBinding;
}
@Override
public <S> SpatialData<Value, S, Value> spatialData(String name, Z2Form<S> shapeForm) {
return spatialData(Text.from(name), shapeForm);
}
@Override
public SpatialData<Value, R2Shape, Value> geospatialData(Value name) {
return spatialData(name, GeoProjection.wgs84Form());
}
@Override
public SpatialData<Value, R2Shape, Value> geospatialData(String name) {
return geospatialData(Text.from(name));
}
@Override
public ValueData<Value> valueData(Value name) {
ValueDataBinding dataBinding = openValueData(name);
dataBinding = injectValueData(dataBinding);
return dataBinding;
}
@Override
public ValueData<Value> valueData(String name) {
return valueData(Text.from(name));
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<MemStore, HashTrieMap<Value, StoreBinding>> STORES =
AtomicReferenceFieldUpdater.newUpdater(MemStore.class, (Class<HashTrieMap<Value, StoreBinding>>) (Class<?>) HashTrieMap.class, "stores");
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<MemStore, HashTrieMap<Value, DataBinding>> TREES =
AtomicReferenceFieldUpdater.newUpdater(MemStore.class, (Class<HashTrieMap<Value, DataBinding>>) (Class<?>) HashTrieMap.class, "trees");
}
|
0 | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store/mem/MemStoreKernel.java | // Copyright 2015-2019 SWIM.AI 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 swim.store.mem;
import swim.kernel.KernelProxy;
import swim.store.StoreBinding;
import swim.store.StoreDef;
import swim.structure.Value;
public class MemStoreKernel extends KernelProxy {
final double kernelPriority;
public MemStoreKernel(double kernelPriority) {
this.kernelPriority = kernelPriority;
}
public MemStoreKernel() {
this(KERNEL_PRIORITY);
}
@Override
public final double kernelPriority() {
return this.kernelPriority;
}
@Override
public StoreBinding createStore(StoreDef storeDef, ClassLoader classLoader) {
StoreBinding store = super.createStore(storeDef, classLoader);
if (store == null) {
store = new MemStore();
}
return store;
}
@Override
public StoreBinding openEdgeStore(String edgeName) {
StoreBinding store = super.openEdgeStore(edgeName);
if (store == null) {
store = new MemStore();
}
return store;
}
private static final double KERNEL_PRIORITY = -1.0;
public static MemStoreKernel fromValue(Value moduleConfig) {
final Value header = moduleConfig.getAttr("kernel");
final String kernelClassName = header.get("class").stringValue(null);
if (kernelClassName == null || MemStoreKernel.class.getName().equals(kernelClassName)) {
final double kernelPriority = header.get("priority").doubleValue(KERNEL_PRIORITY);
return new MemStoreKernel(kernelPriority);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store/mem/SpatialDataModel.java | // Copyright 2015-2019 SWIM.AI 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 swim.store.mem;
import java.util.Iterator;
import swim.api.data.SpatialData;
import swim.math.Z2Form;
import swim.spatial.QTreeMap;
import swim.spatial.SpatialMap;
import swim.store.SpatialDataBinding;
import swim.store.SpatialDataContext;
import swim.store.SpatialDataView;
import swim.store.StoreBinding;
import swim.structure.Form;
import swim.structure.Value;
public class SpatialDataModel<S> implements SpatialDataBinding<S> {
protected final Value name;
protected final QTreeMap<Value, S, Value> tree;
protected SpatialDataContext<S> dataContext;
protected StoreBinding storeBinding;
public SpatialDataModel(Value name, QTreeMap<Value, S, Value> tree) {
this.name = name;
this.tree = tree;
}
@Override
public SpatialDataContext<S> dataContext() {
return this.dataContext;
}
@Override
public void setDataContext(SpatialDataContext<S> dataContext) {
this.dataContext = dataContext;
}
@Override
public StoreBinding storeBinding() {
return this.storeBinding;
}
@Override
public void setStoreBinding(StoreBinding storeBinding) {
this.storeBinding = storeBinding;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapData(Class<T> dataClass) {
if (dataClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
public final QTreeMap<Value, S, Value> tree() {
return this.tree;
}
@Override
public final Value name() {
return this.name;
}
@Override
public Form<Value> keyForm() {
return Form.forValue();
}
@Override
public <K2> SpatialData<K2, S, Value> keyForm(Form<K2> keyForm) {
return new SpatialDataView<K2, S, Value>(this, keyForm, Form.forValue());
}
@Override
public <K2> SpatialData<K2, S, Value> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
@Override
public long dataSize() {
return 0;
}
@Override
public final Z2Form<S> shapeForm() {
return this.tree.shapeForm();
}
@Override
public Form<Value> valueForm() {
return Form.forValue();
}
@Override
public <V2> SpatialData<Value, S, V2> valueForm(Form<V2> valueForm) {
return new SpatialDataView<Value, S, V2>(this, Form.forValue(), valueForm);
}
@Override
public <V2> SpatialData<Value, S, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
@Override
public boolean isResident() {
return true;
}
@Override
public SpatialDataBinding<S> isResident(boolean isResident) {
return this;
}
@Override
public boolean isTransient() {
return true;
}
@Override
public SpatialDataBinding<S> isTransient(boolean isTransient) {
return this;
}
@Override
public boolean isEmpty() {
return this.tree.isEmpty();
}
@Override
public int size() {
return this.tree.size();
}
@Override
public boolean containsKey(Value key, S shape) {
return this.tree.containsKey(key, shape);
}
@Override
public boolean containsKey(Object key) {
return this.tree.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.tree.containsValue(value);
}
@Override
public Value get(Value key, S shape) {
return this.tree.get(key.commit(), shape);
}
@Override
public Value get(Object key) {
return this.tree.get(key);
}
@Override
public Value put(Value key, S shape, Value newValue) {
return this.tree.put(key.commit(), shape, newValue.commit());
}
@Override
public Value move(Value key, S oldShape, S newShape, Value newValue) {
return this.tree.move(key.commit(), oldShape, newShape, newValue.commit());
}
@Override
public Value remove(Value key, S shape) {
return this.tree.remove(key, shape);
}
@Override
public void clear() {
this.tree.clear();
}
@Override
public Iterator<Entry<Value, S, Value>> iterator(S shape) {
return this.tree.iterator(shape);
}
@Override
public Iterator<Entry<Value, S, Value>> iterator() {
return this.tree.iterator();
}
@Override
public Iterator<Value> keyIterator() {
return this.tree.keyIterator();
}
@Override
public Iterator<Value> valueIterator() {
return this.tree.valueIterator();
}
@Override
public SpatialMap<Value, S, Value> snapshot() {
return this.tree.snapshot();
}
@Override
public void close() {
final StoreBinding storeBinding = this.storeBinding;
if (storeBinding != null) {
storeBinding.closeData(this.name);
}
}
}
|
0 | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store/mem/ValueDataModel.java | // Copyright 2015-2019 SWIM.AI 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 swim.store.mem;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.data.ValueData;
import swim.store.StoreBinding;
import swim.store.ValueDataBinding;
import swim.store.ValueDataContext;
import swim.store.ValueDataView;
import swim.structure.Form;
import swim.structure.Value;
public class ValueDataModel implements ValueDataBinding {
protected final Value name;
protected volatile Value value;
protected ValueDataContext dataContext;
protected StoreBinding storeBinding;
public ValueDataModel(Value name, Value value) {
this.name = name;
this.value = value.commit();
}
@Override
public ValueDataContext dataContext() {
return this.dataContext;
}
@Override
public void setDataContext(ValueDataContext dataContext) {
this.dataContext = dataContext;
}
@Override
public StoreBinding storeBinding() {
return this.storeBinding;
}
@Override
public void setStoreBinding(StoreBinding storeBinding) {
this.storeBinding = storeBinding;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapData(Class<T> dataClass) {
if (dataClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public Value name() {
return this.name;
}
@Override
public long dataSize() {
return 0;
}
@Override
public Form<Value> valueForm() {
return Form.forValue();
}
@Override
public <V2> ValueData<V2> valueForm(Form<V2> valueForm) {
return new ValueDataView<V2>(this, valueForm);
}
@Override
public <V2> ValueData<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
@Override
public boolean isResident() {
return true;
}
@Override
public ValueDataBinding isResident(boolean isResident) {
return this;
}
@Override
public boolean isTransient() {
return true;
}
@Override
public ValueDataBinding isTransient(boolean isTransient) {
return this;
}
@Override
public Value get() {
return this.value;
}
@Override
public Value set(Value newValue) {
do {
final Value oldValue = this.value;
if (!oldValue.equals(newValue)) {
if (VALUE.compareAndSet(this, oldValue, newValue.commit())) {
return oldValue;
}
} else {
return oldValue;
}
} while (true);
}
@Override
public void close() {
final StoreBinding storeBinding = this.storeBinding;
if (storeBinding != null) {
storeBinding.closeData(this.name);
}
}
static final AtomicReferenceFieldUpdater<ValueDataModel, Value> VALUE =
AtomicReferenceFieldUpdater.newUpdater(ValueDataModel.class, Value.class, "value");
}
|
0 | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store | java-sources/ai/swim/swim-store-mem/3.10.0/swim/store/mem/package-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* In-memory storage runtime.
*/
package swim.store.mem;
|
0 | java-sources/ai/swim/swim-streamlet | java-sources/ai/swim/swim-streamlet/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI 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.
/**
* Stateful streaming component model.
*/
module swim.streamlet {
requires transitive swim.util;
requires transitive swim.collections;
requires transitive swim.concurrent;
exports swim.streamlet;
exports swim.streamlet.combinator;
exports swim.streamlet.function;
}
|
0 | java-sources/ai/swim/swim-streamlet/3.10.0/swim | java-sources/ai/swim/swim-streamlet/3.10.0/swim/streamlet/AbstractInlet.java | // Copyright 2015-2019 SWIM.AI 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 swim.streamlet;
public abstract class AbstractInlet<I> implements Inlet<I> {
protected Outlet<? extends I> input;
protected int version;
public AbstractInlet() {
this.input = null;
this.version = -1;
}
@Override
public Outlet<? extends I> input() {
return this.input;
}
@Override
public void bindInput(Outlet<? extends I> input) {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = input;
if (this.input != null) {
this.input.bindOutput(this);
}
}
@Override
public void unbindInput() {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = null;
}
@Override
public void disconnectInputs() {
final Outlet<? extends I> input = this.input;
if (input != null) {
input.unbindOutput(this);
this.input = null;
input.disconnectInputs();
}
}
@Override
public void disconnectOutputs() {
// nop
}
@Override
public void invalidateOutput() {
if (this.version >= 0) {
willInvalidateOutput();
this.version = -1;
onInvalidateOutput();
didInvalidateOutput();
}
}
@Override
public void reconcileOutput(int version) {
if (this.version < 0) {
willReconcileOutput(version);
this.version = version;
if (this.input != null) {
this.input.reconcileInput(version);
}
onReconcileOutput(version);
didReconcileOutput(version);
}
}
protected void willInvalidateOutput() {
// stub
}
protected void onInvalidateOutput() {
// stub
}
protected void didInvalidateOutput() {
// stub
}
protected void willReconcileOutput(int version) {
// stub
}
protected void onReconcileOutput(int version) {
// stub
}
protected void didReconcileOutput(int version) {
// stub
}
}
|
0 | java-sources/ai/swim/swim-streamlet/3.10.0/swim | java-sources/ai/swim/swim-streamlet/3.10.0/swim/streamlet/AbstractInoutlet.java | // Copyright 2015-2019 SWIM.AI 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 swim.streamlet;
import java.util.Iterator;
import swim.util.Cursor;
public abstract class AbstractInoutlet<I, O> implements Inoutlet<I, O> {
protected Outlet<? extends I> input;
protected Inlet<? super O>[] outputs;
protected int version;
public AbstractInoutlet() {
this.input = null;
this.outputs = null;
this.version = -1;
}
@Override
public abstract O get();
@Override
public Outlet<? extends I> input() {
return this.input;
}
@Override
public void bindInput(Outlet<? extends I> input) {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = input;
if (this.input != null) {
this.input.bindOutput(this);
}
}
@Override
public void unbindInput() {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = null;
}
@Override
public void disconnectInputs() {
if (this.outputs == null) {
final Outlet<? extends I> input = this.input;
if (input != null) {
input.unbindOutput(this);
this.input = null;
input.disconnectInputs();
}
}
}
@Override
public Iterator<Inlet<? super O>> outputIterator() {
return this.outputs != null ? Cursor.array(this.outputs) : Cursor.empty();
}
@SuppressWarnings("unchecked")
@Override
public void bindOutput(Inlet<? super O> output) {
final Inlet<? super O>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
final Inlet<? super O>[] newOutputs = (Inlet<? super O>[]) new Inlet<?>[n + 1];
if (n > 0) {
System.arraycopy(oldOutputs, 0, newOutputs, 0, n);
}
newOutputs[n] = output;
this.outputs = newOutputs;
}
@SuppressWarnings("unchecked")
@Override
public void unbindOutput(Inlet<? super O> output) {
final Inlet<? super O>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
for (int i = 0; i < n; i += 1) {
if (oldOutputs[i].equals(output)) {
if (n > 1) {
final Inlet<? super O>[] newOutputs = (Inlet<? super O>[]) new Inlet<?>[n - 1];
System.arraycopy(oldOutputs, 0, newOutputs, 0, i);
System.arraycopy(oldOutputs, i + 1, newOutputs, i, (n - 1) - i);
this.outputs = newOutputs;
} else {
this.outputs = null;
}
break;
}
}
}
@Override
public void unbindOutputs() {
final Inlet<? super O>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super O> output = outputs[i];
output.unbindInput();
}
}
}
@Override
public void disconnectOutputs() {
if (this.input == null) {
final Inlet<? super O>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super O> output = outputs[i];
output.unbindInput();
output.disconnectOutputs();
}
}
}
}
@Override
public void invalidateOutput() {
invalidate();
}
@Override
public void invalidateInput() {
invalidate();
}
public void invalidate() {
if (this.version >= 0) {
willInvalidate();
this.version = -1;
onInvalidate();
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].invalidateOutput();
}
didInvalidate();
}
}
@Override
public void reconcileOutput(int version) {
reconcile(version);
}
@Override
public void reconcileInput(int version) {
reconcile(version);
}
public void reconcile(int version) {
if (this.version < 0) {
willReconcile(version);
this.version = version;
if (this.input != null) {
this.input.reconcileInput(version);
}
onReconcile(version);
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].reconcileOutput(version);
}
didReconcile(version);
}
}
protected void willInvalidate() {
// stub
}
protected void onInvalidate() {
// stub
}
protected void didInvalidate() {
// stub
}
protected void willReconcile(int version) {
// stub
}
protected void onReconcile(int version) {
// stub
}
protected void didReconcile(int version) {
// stub
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.