index
int64 0
0
| repo_id
stringlengths 26
205
| file_path
stringlengths 51
246
| content
stringlengths 8
433k
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/serializer/NFCompressedGraphSerializer.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.serializer;
import com.netflix.nfgraph.NFGraphModelHolder;
import com.netflix.nfgraph.compressed.NFCompressedGraph;
import com.netflix.nfgraph.compressed.NFCompressedGraphPointers;
import com.netflix.nfgraph.spec.NFGraphSpec;
import com.netflix.nfgraph.spec.NFNodeSpec;
import com.netflix.nfgraph.spec.NFPropertySpec;
import com.netflix.nfgraph.util.ByteData;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* This class is used by {@link NFCompressedGraph#writeTo(OutputStream)}.<p>
*
* It is unlikely that this class will need to be used externally.
*/
public class NFCompressedGraphSerializer {
private final NFGraphSpec spec;
private final NFGraphModelHolder modelHolder;
private final NFCompressedGraphPointersSerializer pointersSerializer;
private final ByteData data;
private final long dataLength;
public NFCompressedGraphSerializer(NFGraphSpec spec, NFGraphModelHolder modelHolder, NFCompressedGraphPointers pointers, ByteData data, long dataLength) {
this.spec = spec;
this.modelHolder = modelHolder;
this.pointersSerializer = new NFCompressedGraphPointersSerializer(pointers, dataLength);
this.data = data;
this.dataLength = dataLength;
}
public void serializeTo(OutputStream os) throws IOException {
DataOutputStream dos = new DataOutputStream(os);
serializeSpec(dos);
serializeModels(dos);
pointersSerializer.serializePointers(dos);
serializeData(dos);
dos.flush();
}
private void serializeSpec(DataOutputStream dos) throws IOException {
dos.writeInt(spec.size());
for(NFNodeSpec nodeSpec : spec) {
dos.writeUTF(nodeSpec.getNodeTypeName());
dos.writeInt(nodeSpec.getPropertySpecs().length);
for(NFPropertySpec propertySpec : nodeSpec.getPropertySpecs()) {
dos.writeUTF(propertySpec.getName());
dos.writeUTF(propertySpec.getToNodeType());
dos.writeBoolean(propertySpec.isGlobal());
dos.writeBoolean(propertySpec.isMultiple());
dos.writeBoolean(propertySpec.isHashed());
}
}
}
private void serializeModels(DataOutputStream dos) throws IOException {
dos.writeInt(modelHolder.size());
for(String model : modelHolder) {
dos.writeUTF(model);
}
}
private void serializeData(DataOutputStream dos) throws IOException {
/// In order to maintain backwards compatibility of produced artifacts,
/// if more than Integer.MAX_VALUE bytes are required in the data,
/// first serialize a negative 1 integer, then serialize the number
/// of required bits as a long.
if(dataLength > Integer.MAX_VALUE) {
dos.writeInt(-1);
dos.writeLong(dataLength);
} else {
dos.writeInt((int)dataLength);
}
data.writeTo(dos, dataLength);
}
}
| 1,600 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/serializer/NFCompressedGraphPointersSerializer.java
|
/*
* Copyright 2014-2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.serializer;
import com.netflix.nfgraph.compressed.NFCompressedGraphPointers;
import com.netflix.nfgraph.util.ByteArrayBuffer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
public class NFCompressedGraphPointersSerializer {
private final NFCompressedGraphPointers pointers;
private final long dataLength;
NFCompressedGraphPointersSerializer(NFCompressedGraphPointers pointers, long dataLength) {
this.pointers = pointers;
this.dataLength = dataLength;
}
void serializePointers(DataOutputStream dos) throws IOException {
int numNodeTypes = pointers.asMap().size();
if(dataLength > 0xFFFFFFFFL)
numNodeTypes |= Integer.MIN_VALUE;
/// In order to maintain backwards compatibility of produced artifacts,
/// if more than 32 bits is required to represent the pointers, then flag
/// the sign bit in the serialized number of node types.
dos.writeInt(numNodeTypes);
for(Map.Entry<String, long[]>entry : pointers.asMap().entrySet()) {
dos.writeUTF(entry.getKey());
serializePointerArray(dos, entry.getValue());
}
}
private void serializePointerArray(DataOutputStream dos, long pointers[]) throws IOException {
ByteArrayBuffer buf = new ByteArrayBuffer();
long currentPointer = 0;
for(int i=0;i<pointers.length;i++) {
if(pointers[i] == -1) {
buf.writeVInt(-1);
} else {
long delta = pointers[i] - currentPointer;
if(delta >= 0xFFFFFFFFL) {
buf.writeVLong(delta);
} else {
buf.writeVInt((int)delta);
}
currentPointer = pointers[i];
}
}
dos.writeInt(pointers.length);
dos.writeInt((int)buf.length());
buf.copyTo(dos);
}
}
| 1,601 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/ByteArrayReader.java
|
/*
* Copyright 2013-2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.compressed.NFCompressedGraph;
/**
* Used by the {@link NFCompressedGraph}, and various {@link OrdinalSet} and {@link OrdinalIterator} implementations to read the encoded graph data.<p>
*
* It is unlikely that this class will be required externally.
*/
public class ByteArrayReader {
private final ByteData data;
private long pointer;
private long startByte;
private long endByte = Integer.MAX_VALUE;
public ByteArrayReader(ByteData data, long pointer) {
this.data = data;
this.pointer = pointer;
this.startByte = pointer;
this.endByte = data.length();
}
public ByteArrayReader(ByteData data, long startByte, long endByte) {
this.data = data;
this.startByte = startByte;
this.endByte = endByte;
this.pointer = startByte;
}
/**
* @return the byte value at the given offset.
*/
public byte getByte(long offset) {
return data.get(startByte + offset);
}
/**
* Set the current offset of this reader.
*/
public void setPointer(long pointer) {
this.pointer = pointer;
}
/**
* Increment the current offset of this reader by numBytes.
*/
public void skip(long numBytes) {
pointer += numBytes;
}
/**
* @return a variable-byte integer at the current offset. The offset is incremented by the size of the returned integer.
*/
public int readVInt() {
if(pointer >= endByte)
return -1;
byte b = readByte();
if(b == (byte) 0x80)
return -1;
int value = b & 0x7F;
while ((b & 0x80) != 0) {
b = readByte();
value <<= 7;
value |= (b & 0x7F);
}
return value;
}
/**
* @return a variable-byte long at the current offset. The offset is incremented by the size of the returned long.
*/
public long readVLong() {
if(pointer >= endByte)
return -1;
byte b = readByte();
if(b == (byte) 0x80)
return -1;
long value = b & 0x7F;
while ((b & 0x80) != 0) {
b = readByte();
value <<= 7;
value |= (b & 0x7F);
}
return value;
}
/**
* @return the byte at the current offset. The offset is incremented by one.
*/
public byte readByte() {
return data.get(pointer++);
}
/**
* Sets the start byte of this reader to the current offset, then sets the end byte to the current offset + <code>remainingBytes</code>
*/
public void setRemainingBytes(int remainingBytes) {
this.startByte = pointer;
this.endByte = pointer + remainingBytes;
}
/**
* Sets the current offset of this reader to the start byte.
*/
public void reset() {
this.pointer = startByte;
}
/**
* @return the length of this reader.
*/
public long length() {
return endByte - startByte;
}
/**
* @return a copy of this reader. The copy will have the same underlying byte array, start byte, and end byte, but the current offset will be equal to the start byte.
*/
public ByteArrayReader copy() {
return new ByteArrayReader(data, startByte, endByte);
}
}
| 1,602 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/Mixer.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
public class Mixer {
/**
* Thomas Wang's commonly used 32 bit mix function.
*/
public static int hashInt(int key) {
key = ~key + (key << 15);
key = key ^ (key >>> 12);
key = key + (key << 2);
key = key ^ (key >>> 4);
key = key * 2057;
key = key ^ (key >>> 16);
return key & Integer.MAX_VALUE;
}
}
| 1,603 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/OrdinalMap.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
import java.util.Arrays;
import java.util.Iterator;
/**
* An <code>OrdinalMap</code> will generate and maintain a mapping between objects added and an integer value between
* 0 and n, where n is the number of objects in the map.<p>
*
* The values mapped to the objects will be the order in which the objects are inserted.<p>
*
* The <code>OrdinalMap</code> is memory-efficient and can retrieve an object given an ordinal, or an ordinal given an object, both in <code>O(1)</code> time.<p>
*
* If, for example, some application refers to graph nodes as Strings, the OrdinalMap can be used as follows:<p>
*
* <pre>
* {@code
*
* OrdinalMap<String> ordinalMap = new OrdinalMap<String>();
*
* int ord0 = ordinalMap.add("node0"); // returns 0
* int ord1 = ordinalMap.add("node1"); // returns 1
* int ord2 = ordinalMap.add("node2"); // returns 2
* int ord3 = ordinalMap.add("node1"); // returns 1
*
* ordinalMap.get("node2"); // returns 2
* ordinalMap.get(ord2); // returns "node2"
*
* }
* </pre>
*/
public class OrdinalMap<T> implements Iterable<T> {
private int hashedOrdinalArray[];
private T objectsByOrdinal[];
private int size;
public OrdinalMap() {
this(10);
}
@SuppressWarnings("unchecked")
public OrdinalMap(int expectedSize) {
int mapArraySize = 1 << (32 - Integer.numberOfLeadingZeros(expectedSize * 4 / 3));
int ordinalArraySize = mapArraySize * 3 / 4;
hashedOrdinalArray = newHashedOrdinalArray(mapArraySize);
objectsByOrdinal = (T[]) new Object[ordinalArraySize];
}
/**
* Add an object into this <code>OrdinalMap</code>. If the same object (or an {@link Object#equals(Object)} object) is
* already in the map, then no changes will be made.
*
* @return the ordinal of <code>obj</code>
*/
public int add(T obj) {
int ordinal = get(obj);
if(ordinal != -1)
return ordinal;
if(size == objectsByOrdinal.length)
growCapacity();
objectsByOrdinal[size] = obj;
hashOrdinalIntoArray(size, hashedOrdinalArray);
return size++;
}
/**
* @return the ordinal of an object previously added to the map. If the object has not been added to the map, returns -1 instead.
*/
public int get(T obj) {
int hash = Mixer.hashInt(obj.hashCode());
int bucket = hash % hashedOrdinalArray.length;
int ordinal = hashedOrdinalArray[bucket];
while(ordinal != -1) {
if(objectsByOrdinal[ordinal].equals(obj))
return ordinal;
bucket = (bucket + 1) % hashedOrdinalArray.length;
ordinal = hashedOrdinalArray[bucket];
}
return -1;
}
/**
* @return the object for a given ordinal. If the ordinal does not yet exist, returns null.
*/
public T get(int ordinal) {
if(ordinal >= size)
return null;
return objectsByOrdinal[ordinal];
}
/**
* @return the number of objects in this map.
*/
public int size() {
return size;
}
private void growCapacity() {
int newHashedOrdinalArray[] = newHashedOrdinalArray(hashedOrdinalArray.length * 2);
for(int i=0;i<objectsByOrdinal.length;i++) {
hashOrdinalIntoArray(i, newHashedOrdinalArray);
}
objectsByOrdinal = Arrays.copyOf(objectsByOrdinal, objectsByOrdinal.length * 2);
hashedOrdinalArray = newHashedOrdinalArray;
}
private void hashOrdinalIntoArray(int ordinal, int hashedOrdinalArray[]) {
int hash = Mixer.hashInt(objectsByOrdinal[ordinal].hashCode());
int bucket = hash % hashedOrdinalArray.length;
while(hashedOrdinalArray[bucket] != -1) {
bucket = (bucket + 1) % hashedOrdinalArray.length;
}
hashedOrdinalArray[bucket] = ordinal;
}
private int[] newHashedOrdinalArray(int length) {
int arr[] = new int[length];
Arrays.fill(arr, -1);
return arr;
}
/**
* @return an {@link Iterator} over the objects in this mapping.
*/
@Override
public Iterator<T> iterator() {
return new ArrayIterator<T>(objectsByOrdinal, size);
}
}
| 1,604 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/ByteData.java
|
/*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
import java.io.IOException;
import java.io.OutputStream;
public interface ByteData {
public void set(long idx, byte b);
public byte get(long idx);
public long length();
public void writeTo(OutputStream os, long length) throws IOException;
}
| 1,605 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/SimpleByteArray.java
|
/*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
import java.io.IOException;
import java.io.OutputStream;
public class SimpleByteArray implements ByteData {
private final byte data[];
public SimpleByteArray(int length) {
this.data = new byte[length];
}
public SimpleByteArray(byte[] data) {
this.data = data;
}
@Override
public void set(long idx, byte b) {
data[(int)idx] = b;
}
@Override
public byte get(long idx) {
return data[(int)idx];
}
@Override
public long length() {
return data.length;
}
@Override
public void writeTo(OutputStream os, long length) throws IOException {
os.write(data, 0, (int)length);
}
}
| 1,606 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/SegmentedByteArray.java
|
/*
* Copyright 2014-2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
public class SegmentedByteArray implements ByteData {
private byte[][] segments;
private final ByteSegmentPool memoryPool;
private final int log2OfSegmentSize;
private final int bitmask;
private long length;
public SegmentedByteArray(int log2OfSegmentSize) {
this(new ByteSegmentPool(log2OfSegmentSize));
}
public SegmentedByteArray(ByteSegmentPool memoryPool) {
this.segments = new byte[2][];
this.memoryPool = memoryPool;
this.log2OfSegmentSize = memoryPool.getLog2OfSegmentSize();
this.bitmask = (1 << log2OfSegmentSize) - 1;
this.length = 0;
}
/**
* Set the byte at the given index to the specified value
*/
public void set(long index, byte value) {
int segmentIndex = (int)(index >> log2OfSegmentSize);
ensureCapacity(segmentIndex);
segments[segmentIndex][(int)(index & bitmask)] = value;
}
/**
* Get the value of the byte at the specified index.
*/
public byte get(long index) {
return segments[(int)(index >>> log2OfSegmentSize)][(int)(index & bitmask)];
}
/**
* For a SegmentedByteArray, this is a faster copy implementation.
*
* @param src
* @param srcPos
* @param destPos
* @param length
*/
public void copy(SegmentedByteArray src, long srcPos, long destPos, long length) {
int segmentLength = 1 << log2OfSegmentSize;
int currentSegment = (int)(destPos >>> log2OfSegmentSize);
int segmentStartPos = (int)(destPos & bitmask);
int remainingBytesInSegment = segmentLength - segmentStartPos;
while(length > 0) {
int bytesToCopyFromSegment = (int)Math.min(remainingBytesInSegment, length);
ensureCapacity(currentSegment);
int copiedBytes = src.copy(srcPos, segments[currentSegment], segmentStartPos, bytesToCopyFromSegment);
srcPos += copiedBytes;
length -= copiedBytes;
segmentStartPos = 0;
remainingBytesInSegment = segmentLength;
currentSegment++;
}
}
/**
* copies exactly data.length bytes from this SegmentedByteArray into the provided byte array
*
* @return the number of bytes copied
*/
public int copy(long srcPos, byte[] data, int destPos, int length) {
int segmentSize = 1 << log2OfSegmentSize;
int remainingBytesInSegment = (int)(segmentSize - (srcPos & bitmask));
int dataPosition = destPos;
while(length > 0) {
byte[] segment = segments[(int)(srcPos >>> log2OfSegmentSize)];
int bytesToCopyFromSegment = Math.min(remainingBytesInSegment, length);
System.arraycopy(segment, (int)(srcPos & bitmask), data, dataPosition, bytesToCopyFromSegment);
dataPosition += bytesToCopyFromSegment;
srcPos += bytesToCopyFromSegment;
remainingBytesInSegment = segmentSize - (int)(srcPos & bitmask);
length -= bytesToCopyFromSegment;
}
return dataPosition - destPos;
}
public void readFrom(InputStream is, long length) throws IOException {
int segmentSize = 1 << log2OfSegmentSize;
int segment = 0;
while(length > 0) {
ensureCapacity(segment);
long bytesToCopy = Math.min(segmentSize, length);
long bytesCopied = 0;
while(bytesCopied < bytesToCopy) {
bytesCopied += is.read(segments[segment], (int)bytesCopied, (int)(bytesToCopy - bytesCopied));
}
segment++;
length -= bytesCopied;
}
}
@Override
public void writeTo(OutputStream os, long length) throws IOException {
writeTo(os, 0, length);
}
/**
* Write a portion of this data to an OutputStream.
*/
public void writeTo(OutputStream os, long startPosition, long len) throws IOException {
int segmentSize = 1 << log2OfSegmentSize;
int remainingBytesInSegment = segmentSize - (int)(startPosition & bitmask);
long remainingBytesInCopy = len;
while(remainingBytesInCopy > 0) {
long bytesToCopyFromSegment = Math.min(remainingBytesInSegment, remainingBytesInCopy);
os.write(segments[(int)(startPosition >>> log2OfSegmentSize)], (int)(startPosition & bitmask), (int)bytesToCopyFromSegment);
startPosition += bytesToCopyFromSegment;
remainingBytesInSegment = segmentSize - (int)(startPosition & bitmask);
remainingBytesInCopy -= bytesToCopyFromSegment;
}
}
/**
* Ensures that the segment at segmentIndex exists
*
* @param segmentIndex
*/
private void ensureCapacity(int segmentIndex) {
while(segmentIndex >= segments.length) {
segments = Arrays.copyOf(segments, segments.length * 3 / 2);
}
long numSegmentsPopulated = length >> log2OfSegmentSize;
for(long i=numSegmentsPopulated; i <= segmentIndex; i++) {
segments[(int)i] = memoryPool.getSegment();
length += 1 << log2OfSegmentSize;
}
}
@Override
public long length() {
return length;
}
/**
* Note that this is NOT thread safe.
*/
public void destroy() {
for(byte[] segment : segments) {
memoryPool.returnSegment(segment);
}
}
}
| 1,607 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/ArrayIterator.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
import java.util.Iterator;
/**
* A simple implementation of {@link Iterator} over an array of objects.
*
* It is unlikely that this class will be required externally.
*/
public class ArrayIterator<T> implements Iterator<T> {
private T arr[];
private int size;
private int counter = 0;
public ArrayIterator(T arr[]) {
this(arr, arr.length);
}
public ArrayIterator(T arr[], int size) {
this.arr = arr;
this.size = size;
}
@Override
public boolean hasNext() {
return counter < size;
}
@Override
public T next() {
return arr[counter++];
}
@Override
public void remove() {
throw new UnsupportedOperationException("Cannot remove elements from this array.");
}
}
| 1,608 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/ByteSegmentPool.java
|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
import java.util.Arrays;
import java.util.LinkedList;
/**
* This is a memory pool which can be used to allocate and reuse memory for deserialized NFCompressedGraph data.
*
* Note that this is NOT thread safe, and it is up to implementations to ensure that only a single update thread
* is accessing this memory pool at any given time.
*/
public class ByteSegmentPool {
private final LinkedList<byte[]> pooledSegments;
private final int log2OfSegmentSize;
public ByteSegmentPool(int log2OfSegmentSize) {
this.pooledSegments = new LinkedList<>();
this.log2OfSegmentSize = log2OfSegmentSize;
}
public int getLog2OfSegmentSize() {
return log2OfSegmentSize;
}
public byte[] getSegment() {
if(pooledSegments.isEmpty())
return new byte[1 << log2OfSegmentSize];
try {
byte[] segment = pooledSegments.removeFirst();
Arrays.fill(segment, (byte)0);
return segment;
} catch(NullPointerException ex) {
throw ex;
}
}
public void returnSegment(byte[] segment) {
if(segment != null)
pooledSegments.addLast(segment);
}
}
| 1,609 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/util/ByteArrayBuffer.java
|
/*
* Copyright 2013-2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.util;
import com.netflix.nfgraph.compressor.NFCompressedGraphBuilder;
import java.io.IOException;
import java.io.OutputStream;
/**
* A <code>ByteArrayBuffer</code> is used by the {@link NFCompressedGraphBuilder} to write data to a byte array.<p>
*
* It is unlikely that this class will need to be used externally.
*/
public class ByteArrayBuffer {
private final SegmentedByteArray data;
private long pointer;
public ByteArrayBuffer() {
this.data = new SegmentedByteArray(new ByteSegmentPool(14));
this.pointer = 0;
}
/**
* @deprecated Use zero-argument constructor instead.
*/
@Deprecated
public ByteArrayBuffer(int initialSize) {
this();
}
/**
* Copies the contents of the specified buffer into this buffer at the current position.
*/
public void write(ByteArrayBuffer buf) {
data.copy(buf.data, 0, pointer, buf.length());
pointer += buf.length();
}
/**
* Writes a variable-byte encoded integer to the byte array.
*/
public void writeVInt(int value) {
if(value == -1) {
writeByte((byte)0x80);
return;
} else if(value < 0) {
writeByte((byte)(0x80 | ((value >>> 28))));
writeByte((byte)(0x80 | ((value >>> 21) & 0x7F)));
writeByte((byte)(0x80 | ((value >>> 14) & 0x7F)));
writeByte((byte)(0x80 | ((value >>> 7) & 0x7F)));
writeByte((byte)(value & 0x7F));
} else {
if(value > 0x0FFFFFFF) writeByte((byte)(0x80 | ((value >>> 28))));
if(value > 0x1FFFFF) writeByte((byte)(0x80 | ((value >>> 21) & 0x7F)));
if(value > 0x3FFF) writeByte((byte)(0x80 | ((value >>> 14) & 0x7F)));
if(value > 0x7F) writeByte((byte)(0x80 | ((value >>> 7) & 0x7F)));
writeByte((byte)(value & 0x7F));
}
}
/**
* Writes a variable-byte encoded integer to the byte array.
*/
public void writeVLong(long value) {
if(value < 0) {
writeByte((byte)0x80);
return;
} else {
if(value > 0xFFFFFFFFFFFFFFL) writeByte((byte)(0x80 | ((value >>> 56) & 0x7FL)));
if(value > 0x1FFFFFFFFFFFFL) writeByte((byte)(0x80 | ((value >>> 49) & 0x7FL)));
if(value > 0x3FFFFFFFFFFL) writeByte((byte)(0x80 | ((value >>> 42) & 0x7FL)));
if(value > 0x7FFFFFFFFL) writeByte((byte)(0x80 | ((value >>> 35) & 0x7FL)));
if(value > 0xFFFFFFFL) writeByte((byte)(0x80 | ((value >>> 28) & 0x7FL)));
if(value > 0x1FFFFFL) writeByte((byte)(0x80 | ((value >>> 21) & 0x7FL)));
if(value > 0x3FFFL) writeByte((byte)(0x80 | ((value >>> 14) & 0x7FL)));
if(value > 0x7FL) writeByte((byte)(0x80 | ((value >>> 7) & 0x7FL)));
writeByte((byte)(value & 0x7F));
}
}
/**
* The current length of the written data, in bytes.
*/
public long length() {
return pointer;
}
/**
* Sets the length of the written data to 0.
*/
public void reset() {
pointer = 0;
}
/**
* @return The underlying SegmentedByteArray containing the written data.
*/
public SegmentedByteArray getData() {
return data;
}
/**
* Writes a byte of data.
*/
public void writeByte(byte b) {
data.set(pointer++, b);
}
/**
* Writes each byte of data, in order.
*/
public void write(byte[] data) {
for(int i=0;i<data.length;i++) {
writeByte(data[i]);
}
}
/**
* Copies the written data to the given <code>OutputStream</code>
*/
public void copyTo(OutputStream os) throws IOException {
data.writeTo(os, 0, pointer);
}
}
| 1,610 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressor/BitSetPropertyBuilder.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressor;
import static com.netflix.nfgraph.OrdinalIterator.NO_MORE_ORDINALS;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.compressed.BitSetOrdinalSet;
import com.netflix.nfgraph.util.ByteArrayBuffer;
/**
* This class is used by {@link NFCompressedGraphBuilder} to write sets of ordinals represented with bit sets.<p>
*
* It is unlikely that this class will need to be used externally.
*
* @see BitSetOrdinalSet
*/
public class BitSetPropertyBuilder {
private final ByteArrayBuffer buf;
public BitSetPropertyBuilder(ByteArrayBuffer buf) {
this.buf = buf;
}
public void buildProperty(OrdinalSet ordinals, int numBits) {
byte[] data = buildBitSetData(numBits, ordinals.iterator());
buf.write(data);
}
private byte[] buildBitSetData(int numBits, OrdinalIterator iter) {
int numBytes = ((numBits - 1) / 8) + 1;
byte data[] = new byte[numBytes];
int ordinal = iter.nextOrdinal();
while(ordinal != NO_MORE_ORDINALS) {
data[ordinal >> 3] |= (byte)(1 << (ordinal & 0x07));
ordinal = iter.nextOrdinal();
}
return data;
}
}
| 1,611 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressor/CompactPropertyBuilder.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressor;
import java.util.Arrays;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.compressed.CompactOrdinalSet;
import com.netflix.nfgraph.util.ByteArrayBuffer;
/**
* This class is used by {@link NFCompressedGraphBuilder} to write sets of ordinals represented as variable-byte deltas.<p>
*
* It is unlikely that this class will need to be used externally.
*
* @see CompactOrdinalSet
*/
public class CompactPropertyBuilder {
private final ByteArrayBuffer buf;
public CompactPropertyBuilder(ByteArrayBuffer buf) {
this.buf = buf;
}
public void buildProperty(OrdinalSet ordinalSet) {
int connectedOrdinals[] = ordinalSet.asArray();
Arrays.sort(connectedOrdinals);
int previousOrdinal = 0;
for(int i=0;i<connectedOrdinals.length;i++) {
buf.writeVInt(connectedOrdinals[i] - previousOrdinal);
previousOrdinal = connectedOrdinals[i];
}
}
}
| 1,612 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressor/NFCompressedGraphBuilder.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressor;
import com.netflix.nfgraph.NFGraphModelHolder;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.build.NFBuildGraph;
import com.netflix.nfgraph.build.NFBuildGraphNode;
import com.netflix.nfgraph.build.NFBuildGraphNodeCache;
import com.netflix.nfgraph.build.NFBuildGraphNodeList;
import com.netflix.nfgraph.compressed.NFCompressedGraph;
import com.netflix.nfgraph.compressed.NFCompressedGraphLongPointers;
import com.netflix.nfgraph.spec.NFGraphSpec;
import com.netflix.nfgraph.spec.NFNodeSpec;
import com.netflix.nfgraph.spec.NFPropertySpec;
import com.netflix.nfgraph.util.ByteArrayBuffer;
/**
* <code>NFCompressedGraphBuilder</code> is used by {@link NFBuildGraph#compress()} to create an {@link NFCompressedGraph}.<p>
*
* It is unlikely that this class will need to be used externally.
*/
public class NFCompressedGraphBuilder {
private final NFGraphSpec graphSpec;
private final NFBuildGraphNodeCache buildGraphNodeCache;
private final NFGraphModelHolder modelHolder;
private final ByteArrayBuffer graphBuffer;
private final ByteArrayBuffer modelBuffer;
private final ByteArrayBuffer fieldBuffer;
private final CompactPropertyBuilder compactPropertyBuilder;
private final HashedPropertyBuilder hashedPropertyBuilder;
private final BitSetPropertyBuilder bitSetPropertyBuilder;
private final NFCompressedGraphLongPointers compressedGraphPointers;
public NFCompressedGraphBuilder(NFGraphSpec graphSpec, NFBuildGraphNodeCache buildGraphNodeCache, NFGraphModelHolder modelHolder) {
this.graphSpec = graphSpec;
this.buildGraphNodeCache = buildGraphNodeCache;
this.modelHolder = modelHolder;
this.graphBuffer = new ByteArrayBuffer();
this.modelBuffer = new ByteArrayBuffer();
this.fieldBuffer = new ByteArrayBuffer();
this.compactPropertyBuilder = new CompactPropertyBuilder(fieldBuffer);
this.hashedPropertyBuilder = new HashedPropertyBuilder(fieldBuffer);
this.bitSetPropertyBuilder = new BitSetPropertyBuilder(fieldBuffer);
this.compressedGraphPointers = new NFCompressedGraphLongPointers();
}
public NFCompressedGraph buildGraph() {
for(String nodeType : graphSpec.getNodeTypes()) {
NFBuildGraphNodeList nodeOrdinals = buildGraphNodeCache.getNodes(nodeType);
addNodeType(nodeType, nodeOrdinals);
}
return new NFCompressedGraph(graphSpec, modelHolder, graphBuffer.getData(), graphBuffer.length(), compressedGraphPointers);
}
private void addNodeType(String nodeType, NFBuildGraphNodeList nodes) {
NFNodeSpec nodeSpec = graphSpec.getNodeSpec(nodeType);
long ordinalPointers[] = new long[nodes.size()];
for(int i=0;i<nodes.size();i++) {
NFBuildGraphNode node = nodes.get(i);
if(node != null) {
ordinalPointers[i] = graphBuffer.length();
serializeNode(node, nodeSpec);
} else {
ordinalPointers[i] = -1;
}
}
compressedGraphPointers.addPointers(nodeType, ordinalPointers);
}
private void serializeNode(NFBuildGraphNode node, NFNodeSpec nodeSpec) {
for(NFPropertySpec propertySpec : nodeSpec.getPropertySpecs()) {
serializeProperty(node, propertySpec);
}
}
private void serializeProperty(NFBuildGraphNode node, NFPropertySpec propertySpec) {
if(propertySpec.isConnectionModelSpecific()) {
for(int i=0;i<modelHolder.size();i++) {
serializeProperty(node, propertySpec, i, modelBuffer);
}
copyBuffer(modelBuffer, graphBuffer);
} else {
serializeProperty(node, propertySpec, 0, graphBuffer);
}
}
private void serializeProperty(NFBuildGraphNode node, NFPropertySpec propertySpec, int connectionModelIndex, ByteArrayBuffer toBuffer) {
if(propertySpec.isMultiple()) {
serializeMultipleProperty(node, propertySpec, connectionModelIndex, toBuffer);
} else {
int connection = node.getConnection(connectionModelIndex, propertySpec);
if(connection == -1) {
toBuffer.writeByte((byte)0x80);
} else {
toBuffer.writeVInt(connection);
}
}
}
private void serializeMultipleProperty(NFBuildGraphNode node, NFPropertySpec propertySpec, int connectionModelIndex, ByteArrayBuffer toBuffer) {
OrdinalSet connections = node.getConnectionSet(connectionModelIndex, propertySpec);
int numBitsInBitSet = buildGraphNodeCache.numNodes(propertySpec.getToNodeType());
int bitSetSize = ((numBitsInBitSet - 1) / 8) + 1;
if(connections.size() < bitSetSize) {
if(propertySpec.isHashed()) {
hashedPropertyBuilder.buildProperty(connections);
if(fieldBuffer.length() < bitSetSize) {
int log2BytesUsed = 32 - Integer.numberOfLeadingZeros((int)fieldBuffer.length());
toBuffer.writeByte((byte)log2BytesUsed);
toBuffer.write(fieldBuffer);
fieldBuffer.reset();
return;
}
} else {
compactPropertyBuilder.buildProperty(connections);
if(fieldBuffer.length() < bitSetSize) {
toBuffer.writeVInt((int)fieldBuffer.length());
toBuffer.write(fieldBuffer);
fieldBuffer.reset();
return;
}
}
fieldBuffer.reset();
}
bitSetPropertyBuilder.buildProperty(connections, numBitsInBitSet);
toBuffer.writeByte((byte)0x80);
toBuffer.write(fieldBuffer);
fieldBuffer.reset();
}
private void copyBuffer(ByteArrayBuffer from, ByteArrayBuffer to) {
to.writeVInt((int)from.length());
to.write(from);
from.reset();
}
}
| 1,613 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressor/HashedPropertyBuilder.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressor;
import static com.netflix.nfgraph.OrdinalIterator.NO_MORE_ORDINALS;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.compressed.HashSetOrdinalSet;
import com.netflix.nfgraph.util.ByteArrayBuffer;
import com.netflix.nfgraph.util.Mixer;
/**
* This class is used by {@link NFCompressedGraphBuilder} to write sets of ordinals represented as as variable-byte hashed integer arrays.<p>
*
* It is unlikely that this class will need to be used externally.
*
* @see HashSetOrdinalSet
*/
public class HashedPropertyBuilder {
private ByteArrayBuffer buf;
public HashedPropertyBuilder(ByteArrayBuffer buf) {
this.buf = buf;
}
public void buildProperty(OrdinalSet ordinals) {
if(ordinals.size() == 0)
return;
byte data[] = buildHashedPropertyData(ordinals);
buf.write(data);
}
private byte[] buildHashedPropertyData(OrdinalSet ordinals) {
byte data[] = new byte[calculateByteArraySize(ordinals)];
OrdinalIterator iter = ordinals.iterator();
int ordinal = iter.nextOrdinal();
while(ordinal != NO_MORE_ORDINALS) {
put(ordinal, data);
ordinal = iter.nextOrdinal();
}
return data;
}
private void put(int value, byte data[]) {
value += 1;
int bucket = Mixer.hashInt(value) & (data.length - 1);
if (data[bucket] != 0) {
bucket = nextEmptyByte(data, bucket);
}
writeKey(value, bucket, data);
}
private void writeKey(int value, int offset, byte data[]) {
int numBytes = calculateVIntSize(value);
ensureSpaceIsAvailable(numBytes, offset, data);
writeVInt(value, offset, data, numBytes);
}
private void writeVInt(int value, int offset, byte data[], int numBytes) {
int b = (value >>> (7 * (numBytes - 1))) & 0x7F;
data[offset] = (byte)b;
offset = nextOffset(data.length, offset);
for (int i = numBytes - 2; i >= 0; i--) {
b = (value >>> (7 * i)) & 0x7F;
data[offset] = (byte)(b | 0x80);
offset = nextOffset(data.length, offset);
}
}
private int nextOffset(int length, int offset) {
offset++;
if (offset == length)
offset = 0;
return offset;
}
private int previousOffset(int length, int offset) {
offset--;
if (offset == -1)
offset = length - 1;
return offset;
}
private void ensureSpaceIsAvailable(int requiredSpace, int offset, byte data[]) {
int copySpaces = 0;
int foundSpace = 1;
int currentOffset = offset;
while (foundSpace < requiredSpace) {
currentOffset = nextOffset(data.length, currentOffset);
if (data[currentOffset] == 0) {
foundSpace++;
} else {
copySpaces++;
}
}
int moveToOffset = currentOffset;
currentOffset = previousOffset(data.length, currentOffset);
while (copySpaces > 0) {
if (data[currentOffset] != 0) {
data[moveToOffset] = data[currentOffset];
copySpaces--;
moveToOffset = previousOffset(data.length, moveToOffset);
}
currentOffset = previousOffset(data.length, currentOffset);
}
}
private int nextEmptyByte(byte data[], int offset) {
while (data[offset] != 0) {
offset = nextOffset(data.length, offset);
}
return offset;
}
private int calculateByteArraySize(OrdinalSet ordinals) {
int numPopulatedBytes = calculateNumPopulatedBytes(ordinals.iterator());
return calculateByteArraySizeAfterLoadFactor(numPopulatedBytes);
}
private int calculateNumPopulatedBytes(OrdinalIterator ordinalIterator) {
int totalSize = 0;
int ordinal = ordinalIterator.nextOrdinal();
while(ordinal != NO_MORE_ORDINALS) {
totalSize += calculateVIntSize(ordinal + 1);
ordinal = ordinalIterator.nextOrdinal();
}
return totalSize;
}
private int calculateVIntSize(int value) {
int numBitsSet = numBitsUsed(value);
return ((numBitsSet - 1) / 7) + 1;
}
private int calculateByteArraySizeAfterLoadFactor(int numPopulatedBytes) {
int desiredSizeAfterLoadFactor = (numPopulatedBytes * 4) / 3;
int nextPowerOfTwo = 1 << numBitsUsed(desiredSizeAfterLoadFactor);
return nextPowerOfTwo;
}
private int numBitsUsed(int value) {
return 32 - Integer.numberOfLeadingZeros(value);
}
}
| 1,614 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/spec/NFPropertySpec.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.spec;
import com.netflix.nfgraph.build.NFBuildGraph;
import com.netflix.nfgraph.compressed.BitSetOrdinalSet;
import com.netflix.nfgraph.compressed.CompactOrdinalSet;
import com.netflix.nfgraph.compressed.NFCompressedGraph;
/**
* This class defines a specification for a single property.<p>
*
* The recommended interface for creating a property is to instantiate with the flag method below.<p>
*
* By default, an <code>NFPropertySpec</code> is {@link #GLOBAL}, {@link #MULTIPLE}, and {@link #COMPACT}.<p>
*
* <pre>
* {@code
* import static com.netflix.nfgraph.spec.NFPropertySpec.*;
*
* ...
*
* NFPropertySpec spec1 = new NFPropertySpec( "property1", "foreignNodeType1", MULTIPLE | HASH );
* NFPropertySpec spec2 = new NFPropertySpec( "property2", "foreignNodeType2", MULTIPLE | COMPACT | MODEL_SPECIFIC);
* NFPropertySpec spec3 = new NFPropertySpec( "property2", "foreignNodeType3", SINGLE );
* }
* </pre>
*
*/
public class NFPropertySpec {
/**
* A property spec instantiated with this flag will not be separable into connection models.
*/
public static final int GLOBAL = 0x00;
/**
* A property spec instantiated with this flag will be separable into connection models.
*/
public static final int MODEL_SPECIFIC = 0x01;
/**
* A property spec instantiated with this flag will be allowed multiple connections.
*/
public static final int MULTIPLE = 0x00;
/**
* A property spec instantiated with this flag will be allowed only a single connection.
*/
public static final int SINGLE = 0x02;
/**
* A {@link #MULTIPLE} property instantiated with this flag will be represented as a {@link BitSetOrdinalSet} in an {@link NFCompressedGraph}.
*
* @see BitSetOrdinalSet
*/
public static final int HASH = 0x04;
/**
* A {@link #MULTIPLE} property instantiated with this flag will be represented as a {@link CompactOrdinalSet} in an {@link NFCompressedGraph}.
*
* @see CompactOrdinalSet
*/
public static final int COMPACT = 0x00;
private final boolean isGlobal;
private final boolean isMultiple;
private final boolean isHashed;
private final String name;
private final String toNodeType;
private int propertyIndex;
/**
* The recommended constructor.
*
* @param name the name of the property.
* @param toNodeType the node type to which this property connects
* @param flags a bitwise-or of the various flags defined as constants in {@link NFPropertySpec}.<br>For example, a global, multiple, compact property would take the value <code>NFPropertySpec.GLOBAL | NFPropertySpec.MULTIPLE | NFPropertySpec.COMPACT</code>
*
*/
public NFPropertySpec(String name, String toNodeType, int flags) {
this.name = name;
this.toNodeType = toNodeType;
this.isGlobal = (flags & MODEL_SPECIFIC) == 0;
this.isMultiple = (flags & SINGLE) == 0;
this.isHashed = (flags & HASH) != 0;
}
public NFPropertySpec(String name, String toNodeType, boolean isGlobal, boolean isMultiple, boolean isHashed) {
this.name = name;
this.toNodeType = toNodeType;
this.isGlobal = isGlobal;
this.isMultiple = isMultiple;
this.isHashed = isHashed;
}
public boolean isConnectionModelSpecific() {
return !isGlobal;
}
public boolean isGlobal() {
return isGlobal;
}
public boolean isMultiple() {
return isMultiple;
}
public boolean isSingle() {
return !isMultiple;
}
public boolean isHashed() {
return isHashed;
}
public boolean isCompact() {
return !isHashed;
}
public String getName() {
return name;
}
public String getToNodeType() {
return toNodeType;
}
void setPropertyIndex(int propertyIndex) {
this.propertyIndex = propertyIndex;
}
/**
* Used by the {@link NFBuildGraph}.
*
* It is unlikely that this method will be required externally.
*/
public int getPropertyIndex() {
return this.propertyIndex;
}
}
| 1,615 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/spec/NFNodeSpec.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.spec;
import java.util.Iterator;
import com.netflix.nfgraph.exception.NFGraphException;
import com.netflix.nfgraph.util.ArrayIterator;
/**
* An <code>NFNodeSpec</code> specifies the schema for a node type.
*
* It is defined by a node name and a number of {@link NFPropertySpec}.
*/
public class NFNodeSpec implements Iterable<NFPropertySpec> {
private final String nodeTypeName;
private final NFPropertySpec propertySpecs[];
private final int numSingleProperties;
private final int numMultipleProperties;
/**
* The constructor for an <code>NFNodeSpec</code>.
*
* @param nodeTypeName the name of the node type
* @param propertySpecs a complete listing of the properties available for this node type.
*/
public NFNodeSpec(String nodeTypeName, NFPropertySpec... propertySpecs) {
this.nodeTypeName = nodeTypeName;
this.propertySpecs = propertySpecs;
int numSingleProperties = 0;
int numMultipleProperties = 0;
for(NFPropertySpec propertySpec : propertySpecs) {
propertySpec.setPropertyIndex(propertySpec.isSingle() ? numSingleProperties++ : numMultipleProperties++);
}
this.numSingleProperties = numSingleProperties;
this.numMultipleProperties = numMultipleProperties;
}
public String getNodeTypeName() {
return nodeTypeName;
}
public NFPropertySpec[] getPropertySpecs() {
return propertySpecs;
}
public NFPropertySpec getPropertySpec(String propertyName) {
for(NFPropertySpec spec : propertySpecs) {
if(spec.getName().equals(propertyName))
return spec;
}
throw new NFGraphException("Property " + propertyName + " is undefined for node type " + nodeTypeName);
}
public int getNumSingleProperties() {
return numSingleProperties;
}
public int getNumMultipleProperties() {
return numMultipleProperties;
}
@Override
public Iterator<NFPropertySpec> iterator() {
return new ArrayIterator<NFPropertySpec>(propertySpecs);
}
}
| 1,616 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/spec/NFGraphSpec.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.spec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.netflix.nfgraph.exception.NFGraphException;
/**
* An <code>NFGraphSpec</code> defines the schema for a graph. It contains a mapping of node type
* name to {@link NFNodeSpec}s.<p>
*
* The example code below will create two node types "a" and "b". An "a" node can be connected to "b" nodes
* via the properties "a-to-one-b" and/or "a-to-many-b". A "b" node can be connected to "a" nodes via the property
* "b-to-many-a".<p>
*
* <pre>
* {@code
*
* NFGraphSpec spec = new NFGraphSpec(
* new NFNodeSpec(
* "a",
* new NFPropertySpec("a-to-one-b", "b", NFPropertySpec.SINGLE),
* new NFPropertySpec("a-to-many-b", "b", NFPropertySpec.MULTIPLE | NFPropertySpec.COMPACT)
* ),
* new NFNodeSpec(
* "b",
* new NFPropertySpec("b-to-many-a", "a", NFPropertySpec.MULTIPLE | NFPropertySpec.HASH)
* )
* );
*
* }
* </pre>
*
* @see NFNodeSpec
* @see NFPropertySpec
*/
public class NFGraphSpec implements Iterable<NFNodeSpec> {
private final Map<String, NFNodeSpec> nodeSpecs;
/**
* Instantiate a graph specification with no {@link NFNodeSpec}s.
*/
public NFGraphSpec() {
this.nodeSpecs = new HashMap<String, NFNodeSpec>();
}
/**
* Instantiate a graph specification with the given {@link NFNodeSpec}.
*/
public NFGraphSpec(NFNodeSpec... nodeTypes) {
this();
for(NFNodeSpec spec : nodeTypes) {
addNodeSpec(spec);
}
}
/**
* @return the {@link NFNodeSpec} for the specified node type.
*/
public NFNodeSpec getNodeSpec(String nodeType) {
NFNodeSpec spec = nodeSpecs.get(nodeType);
if(spec == null)
throw new NFGraphException("Node spec " + nodeType + " is undefined");
return spec;
}
/**
* Add a node type to this graph specification.
*/
public void addNodeSpec(NFNodeSpec nodeSpec) {
nodeSpecs.put(nodeSpec.getNodeTypeName(), nodeSpec);
}
/**
* @return the number of node types defined by this graph specification.
*/
public int size() {
return nodeSpecs.size();
}
/**
* @return a {@link List} containing the names of each of the node types.
*/
public List<String> getNodeTypes() {
return new ArrayList<String>(nodeSpecs.keySet());
}
/**
* Returns an {@link Iterator} over the {@link NFNodeSpec}s contained in this graph specification.
*/
@Override
public Iterator<NFNodeSpec> iterator() {
return nodeSpecs.values().iterator();
}
}
| 1,617 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/BitSetOrdinalSet.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.compressor.NFCompressedGraphBuilder;
import com.netflix.nfgraph.spec.NFPropertySpec;
import com.netflix.nfgraph.util.ByteArrayReader;
/**
* An implementation of {@link OrdinalSet}, returned for connections represented as a bit set in an {@link NFCompressedGraph}.<p>
*
* A bit set representation contains a single bit per ordinal in the type to which the connections point. If the bit at the
* position for a given ordinal is set, then there is a connection to that ordinal in this set.<p>
*
* Because determining membership in a set requires only checking whether the bit at a given position is set, <code>contains()</code>
* is an <code>O(1)</code> operation.<p>
*
* This representation will automatically be chosen for a set by the {@link NFCompressedGraphBuilder} when it requires fewer bytes than
* the configured representation (either {@link NFPropertySpec#COMPACT} or {@link NFPropertySpec#HASH}).
*
* @see <a href="https://github.com/Netflix/netflix-graph/wiki/Compact-representations">Compact Representations</a>
*/
public class BitSetOrdinalSet extends OrdinalSet {
private final ByteArrayReader reader;
public BitSetOrdinalSet(ByteArrayReader reader) {
this.reader = reader;
}
@Override
public boolean contains(int value) {
int offset = value >>> 3;
int mask = 1 << (value & 0x07);
if(offset >= reader.length())
return false;
return (reader.getByte(offset) & mask) != 0;
}
@Override
public OrdinalIterator iterator() {
return new BitSetOrdinalIterator(reader);
}
@Override
public int size() {
int cardinalitySum = 0;
for(int i=0;i<(reader.length());i++) {
cardinalitySum += BITS_SET_TABLE[reader.getByte(i) & 0xFF];
}
return cardinalitySum;
}
private static final int BITS_SET_TABLE[] = new int[256];
static {
for(int i=0;i<256;i++) {
BITS_SET_TABLE[i] = (i & 1) + BITS_SET_TABLE[i / 2];
}
}
}
| 1,618 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/CompactOrdinalIterator.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.util.ByteArrayReader;
/**
* An implementation of {@link OrdinalIterator} returned for ordinals represented as variable-byte deltas in an {@link NFCompressedGraph}.
*
* @see CompactOrdinalSet
*/
public class CompactOrdinalIterator implements OrdinalIterator {
private final ByteArrayReader arrayReader;
private int currentOrdinal = 0;
CompactOrdinalIterator(ByteArrayReader arrayReader) {
this.arrayReader = arrayReader;
}
@Override
public int nextOrdinal() {
int delta = arrayReader.readVInt();
if(delta == -1)
return NO_MORE_ORDINALS;
currentOrdinal += delta;
return currentOrdinal;
}
@Override
public void reset() {
arrayReader.reset();
currentOrdinal = 0;
}
@Override
public OrdinalIterator copy() {
return new CompactOrdinalIterator(arrayReader.copy());
}
@Override
public boolean isOrdered() {
return true;
}
}
| 1,619 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/BitSetOrdinalIterator.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.util.ByteArrayReader;
/**
* An implementation of {@link OrdinalIterator} returned for ordinals represented as bit sets in an {@link NFCompressedGraph}.
*
* @see BitSetOrdinalSet
*/
public class BitSetOrdinalIterator implements OrdinalIterator {
private final ByteArrayReader reader;
public int offset;
public BitSetOrdinalIterator(ByteArrayReader reader) {
this.reader = reader;
}
/**
* {@inheritDoc}
*/
@Override
public int nextOrdinal() {
if(offset >>> 3 == reader.length())
return NO_MORE_ORDINALS;
skipToNextPopulatedByte();
while(moreBytesToRead()) {
if(testCurrentBit()) {
return offset++;
}
offset++;
}
return NO_MORE_ORDINALS;
}
/**
* {@inheritDoc}
*/
@Override
public void reset() {
offset = 0;
}
/**
* {@inheritDoc}
*/
@Override
public OrdinalIterator copy() {
return new BitSetOrdinalIterator(reader);
}
/**
* @return <code>true</code>
*/
@Override
public boolean isOrdered() {
return true;
}
private void skipToNextPopulatedByte() {
if(moreBytesToRead()
&& (currentByte() >>> (offset & 0x07)) == 0) {
offset += 0x08;
offset &= ~0x07;
while(moreBytesToRead() && currentByte() == 0)
offset += 0x08;
}
}
private boolean moreBytesToRead() {
return (offset >>> 3) < reader.length();
}
private boolean testCurrentBit() {
int b = currentByte();
return (b & (1 << (offset & 0x07))) != 0;
}
private byte currentByte() {
return reader.getByte(offset >>> 3);
}
}
| 1,620 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/NFCompressedGraphLongPointers.java
|
/*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import java.util.HashMap;
import java.util.Map;
import com.netflix.nfgraph.exception.NFGraphException;
/**
* This class holds all of the offsets into the {@link NFCompressedGraph}'s byte array.<p>
*
* This class maintains a mapping of type name to int array. For a given type, the offset in the {@link NFCompressedGraph}'s byte array
* where the connections for a given node are encoded is equal to the value of the int array for the node's type at the index for the node's ordinal.<p>
*
* It is unlikely that this class will need to be used externally.
*/
public class NFCompressedGraphLongPointers implements NFCompressedGraphPointers {
private final Map<String, long[]>pointersByOrdinal;
public NFCompressedGraphLongPointers() {
this.pointersByOrdinal = new HashMap<String, long[]>();
}
/**
* @return the offset into the {@link NFCompressedGraph}'s byte array for the node identified by the given type and ordinal.
*/
public long getPointer(String nodeType, int ordinal) {
long pointers[] = pointersByOrdinal.get(nodeType);
if(pointers == null)
throw new NFGraphException("Undefined node type: " + nodeType);
if(ordinal < pointers.length)
return pointers[ordinal];
return -1;
}
public void addPointers(String nodeType, long pointers[]) {
pointersByOrdinal.put(nodeType, pointers);
}
public int numPointers(String nodeType) {
return pointersByOrdinal.get(nodeType).length;
}
public Map<String, long[]> asMap() {
return pointersByOrdinal;
}
}
| 1,621 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/CompactOrdinalSet.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import java.util.Arrays;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.spec.NFPropertySpec;
import com.netflix.nfgraph.util.ByteArrayReader;
/**
* An implementation of {@link OrdinalSet}, returned for connections represented as variable-byte deltas in an {@link NFCompressedGraph}.<p>
*
* A variable-byte delta representation contains between one and five bytes per connection.
* The ordinals in the set are sorted ascending, then encoded as the difference between each ordinal and the last ordinal.<p>
*
* For example, the values [ 7, 11, 13, 21 ] will be encoded as [ 7, 4, 2, 8 ].<p>
*
* This is done because smaller values can be represented in fewer bytes.<p>
*
* Because each value can only be derived using the previous value, <code>contains()</code> is an <code>O(n)</code> operation.<p>
*
* This representation for a connection set can be configured for an {@link NFPropertySpec} using {@link NFPropertySpec#COMPACT}.
*
* @see <a href="http://techblog.netflix.com/2013/01/netflixgraph-metadata-library_18.html">The Netflix Tech Blog</a>
* @see <a href="http://en.wikipedia.org/wiki/Variable-length_quantity">Variable-length quantity</a>
* @see <a href="https://github.com/Netflix/netflix-graph/wiki/Compact-representations">Compact Representations</a>
*/
public class CompactOrdinalSet extends OrdinalSet {
private final ByteArrayReader reader;
private int size = Integer.MIN_VALUE;
public CompactOrdinalSet(ByteArrayReader reader) {
this.reader = reader;
}
@Override
public boolean contains(int value) {
OrdinalIterator iter = iterator();
int iterValue = iter.nextOrdinal();
while(iterValue < value) {
iterValue = iter.nextOrdinal();
}
return iterValue == value;
}
@Override
public boolean containsAll(int... values) {
OrdinalIterator iter = iterator();
Arrays.sort(values);
int valuesIndex = 0;
int setValue = iter.nextOrdinal();
while(valuesIndex < values.length) {
if(setValue == values[valuesIndex]) {
valuesIndex++;
} else if(setValue < values[valuesIndex]) {
setValue = iter.nextOrdinal();
} else {
break;
}
}
return valuesIndex == values.length;
}
@Override
public OrdinalIterator iterator() {
return new CompactOrdinalIterator(reader.copy());
}
@Override
public int size() {
if(sizeIsUnknown())
size = countVInts(reader.copy());
return size;
}
private boolean sizeIsUnknown() {
return size == Integer.MIN_VALUE;
}
private int countVInts(ByteArrayReader myReader) {
int counter = 0;
while(myReader.readVInt() >= 0)
counter++;
return counter;
}
}
| 1,622 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/SingleOrdinalIterator.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import com.netflix.nfgraph.OrdinalIterator;
/**
* An implementation of {@link OrdinalIterator} which "iterates" over a single ordinal.
*/
public class SingleOrdinalIterator implements OrdinalIterator {
private final int ordinal;
private boolean returned;
public SingleOrdinalIterator(int ordinal) {
this.ordinal = ordinal;
}
@Override
public int nextOrdinal() {
if(returned)
return NO_MORE_ORDINALS;
returned = true;
return ordinal;
}
@Override
public void reset() {
returned = false;
}
@Override
public OrdinalIterator copy() {
return new SingleOrdinalIterator(ordinal);
}
@Override
public boolean isOrdered() {
return true;
}
}
| 1,623 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/HashSetOrdinalSet.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.spec.NFPropertySpec;
import com.netflix.nfgraph.util.ByteArrayReader;
import com.netflix.nfgraph.util.Mixer;
/**
* An implementation of {@link OrdinalSet}, returned for connections represented as variable-byte hashed integer arrays in an {@link NFCompressedGraph}.<p>
*
* A variable-byte hashed integer array representation contains between one and five bytes per connection. The ordinal for each
* connection is hashed into a byte array, then represented as a variant on the variable-byte integers used in the {@link CompactOrdinalSet}.<p>
*
* The byte array can be thought of as a open-addressed hash table, with each byte representing a single bucket. Because
* values may be represented in more than one byte, single values may spill over into multiple buckets. The beginning of the
* value is indicated by an unset sign bit, and will be located at or after the bucket to which it is hashed. If the value's
* first bit is not located at the hashed position, it will be located in a position after the bucket with no empty buckets in between.<p>
*
* This implementation provides <code>O(1)</code> time for <code>contains()</code>, but is not as memory-efficient as a {@link CompactOrdinalSet}.<p>
*
* This representation for a connection set can be configured for an {@link NFPropertySpec} using {@link NFPropertySpec#HASH}.
*
* @see <a href="https://github.com/Netflix/netflix-graph/wiki/Compact-representations">Compact Representations</a>
*
*/
public class HashSetOrdinalSet extends OrdinalSet {
private final ByteArrayReader reader;
private int size = Integer.MIN_VALUE;
public HashSetOrdinalSet(ByteArrayReader reader) {
this.reader = reader;
}
@Override
public OrdinalIterator iterator() {
return new HashSetOrdinalIterator(reader.copy());
}
@Override
public boolean contains(int value) {
value += 1;
int offset = (Mixer.hashInt(value) & ((int)reader.length() - 1));
offset = seekBeginByte(offset);
while(reader.getByte(offset) != 0) {
int readValue = reader.getByte(offset);
offset = nextOffset(offset);
while((reader.getByte(offset) & 0x80) != 0) {
readValue <<= 7;
readValue |= reader.getByte(offset) & 0x7F;
offset = nextOffset(offset);
}
if(readValue == value)
return true;
}
return false;
}
@Override
public int size() {
if(size == Integer.MIN_VALUE)
size = countHashEntries();
return size;
}
private int seekBeginByte(int offset) {
while((reader.getByte(offset) & 0x80) != 0)
offset = nextOffset(offset);
return offset;
}
private int nextOffset(int offset) {
offset++;
if(offset >= reader.length()) {
offset = 0;
}
return offset;
}
private int countHashEntries() {
int counter = 0;
for(int i=0;i<reader.length();i++) {
byte b = reader.getByte(i);
if(b != 0 && (b & 0x80) == 0)
counter++;
}
return counter;
}
}
| 1,624 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/HashSetOrdinalIterator.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.util.ByteArrayReader;
/**
* An implementation of {@link OrdinalIterator} returned for ordinals represented as variable-byte hashed integer arrays in an {@link NFCompressedGraph}.
*
* @see HashSetOrdinalSet
*/
public class HashSetOrdinalIterator implements OrdinalIterator {
private final ByteArrayReader reader;
private final int beginOffset;
private int offset = 0;
private boolean firstValue;
public HashSetOrdinalIterator(ByteArrayReader reader) {
this.reader = reader;
seekBeginByte();
this.beginOffset = offset;
firstValue = true;
}
@Override
public int nextOrdinal() {
seekBeginByte();
if(offset == beginOffset) {
if(!firstValue)
return NO_MORE_ORDINALS;
firstValue = false;
}
int value = reader.getByte(offset);
nextOffset();
while((reader.getByte(offset) & 0x80) != 0) {
value <<= 7;
value |= reader.getByte(offset) & 0x7F;
nextOffset();
}
return value - 1;
}
@Override
public void reset() {
offset = beginOffset;
firstValue = true;
}
@Override
public OrdinalIterator copy() {
return new HashSetOrdinalIterator(reader);
}
@Override
public boolean isOrdered() {
return false;
}
private void nextOffset() {
offset++;
if(offset >= reader.length()) {
offset = 0;
}
}
private void seekBeginByte() {
while((reader.getByte(offset) & 0x80) != 0 || reader.getByte(offset) == 0)
nextOffset();
}
}
| 1,625 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/NFCompressedGraph.java
|
/*
* Copyright 2013-2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import static com.netflix.nfgraph.OrdinalIterator.EMPTY_ITERATOR;
import static com.netflix.nfgraph.OrdinalSet.EMPTY_SET;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.netflix.nfgraph.NFGraph;
import com.netflix.nfgraph.NFGraphModelHolder;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.exception.NFGraphException;
import com.netflix.nfgraph.serializer.NFCompressedGraphDeserializer;
import com.netflix.nfgraph.serializer.NFCompressedGraphSerializer;
import com.netflix.nfgraph.spec.NFGraphSpec;
import com.netflix.nfgraph.spec.NFNodeSpec;
import com.netflix.nfgraph.spec.NFPropertySpec;
import com.netflix.nfgraph.util.ByteArrayReader;
import com.netflix.nfgraph.util.ByteData;
import com.netflix.nfgraph.util.ByteSegmentPool;
import com.netflix.nfgraph.util.SegmentedByteArray;
/**
* A read-only, memory-efficient implementation of an {@link NFGraph}. The connections for all nodes in the graph
* are encoded into a single byte array. The encoding for each set will be specified as either a {@link CompactOrdinalSet} or
* {@link HashSetOrdinalSet}. If it is more efficient, the actual encoding will be a {@link BitSetOrdinalSet}.<p>
*
* The offsets into the byte array where connections for each node are encoded are held in the {@link NFCompressedGraphPointers}.
*/
public class NFCompressedGraph extends NFGraph {
private final NFCompressedGraphPointers pointers;
private final ByteData data;
private final long dataLength;
public NFCompressedGraph(NFGraphSpec spec, NFGraphModelHolder modelHolder, ByteData data, long dataLength, NFCompressedGraphPointers pointers) {
super(spec, modelHolder);
this.data = data;
this.dataLength = dataLength;
this.pointers = pointers;
}
@Override
protected int getConnection(int connectionModelIndex, String nodeType, int ordinal, String propertyName) {
ByteArrayReader reader = reader(nodeType, ordinal);
if(reader != null) {
NFPropertySpec propertySpec = pointReaderAtProperty(reader, nodeType, propertyName, connectionModelIndex);
if(propertySpec != null) {
if(propertySpec.isSingle())
return reader.readVInt();
int firstOrdinal = iterator(nodeType, reader, propertySpec).nextOrdinal();
if(firstOrdinal != OrdinalIterator.NO_MORE_ORDINALS)
return firstOrdinal;
}
}
return -1;
}
@Override
protected OrdinalSet getConnectionSet(int connectionModelIndex, String nodeType, int ordinal, String propertyName) {
ByteArrayReader reader = reader(nodeType, ordinal);
if(reader != null) {
NFPropertySpec propertySpec = pointReaderAtProperty(reader, nodeType, propertyName, connectionModelIndex);
if (propertySpec != null) {
return set(nodeType, reader, propertySpec);
}
}
return EMPTY_SET;
}
@Override
protected OrdinalIterator getConnectionIterator(int connectionModelIndex, String nodeType, int ordinal, String propertyName) {
ByteArrayReader reader = reader(nodeType, ordinal);
if(reader != null) {
NFPropertySpec propertySpec = pointReaderAtProperty(reader, nodeType, propertyName, connectionModelIndex);
if (propertySpec != null) {
return iterator(nodeType, reader, propertySpec);
}
}
return EMPTY_ITERATOR;
}
NFCompressedGraphPointers getPointers() {
return pointers;
}
private OrdinalSet set(String nodeType, ByteArrayReader reader, NFPropertySpec propertySpec) {
if(propertySpec.isSingle())
return new SingleOrdinalSet(reader.readVInt());
int size = reader.readVInt();
if(size == -1) {
int numBits = pointers.numPointers(propertySpec.getToNodeType());
int numBytes = ((numBits - 1) / 8) + 1;
reader.setRemainingBytes(numBytes);
return new BitSetOrdinalSet(reader);
}
if(size == 0)
return EMPTY_SET;
if(propertySpec.isHashed()) {
reader.setRemainingBytes(1 << (size - 1));
return new HashSetOrdinalSet(reader);
}
reader.setRemainingBytes(size);
return new CompactOrdinalSet(reader);
}
private OrdinalIterator iterator(String nodeType, ByteArrayReader reader, NFPropertySpec propertySpec) {
if(propertySpec.isSingle())
return new SingleOrdinalIterator(reader.readVInt());
int size = reader.readVInt();
if(size == -1) {
int numBits = pointers.numPointers(propertySpec.getToNodeType());
int numBytes = ((numBits - 1) / 8) + 1;
reader.setRemainingBytes(numBytes);
return new BitSetOrdinalIterator(reader);
}
if(size == 0)
return EMPTY_ITERATOR;
if(propertySpec.isHashed()) {
reader.setRemainingBytes(1 << (size - 1));
return new HashSetOrdinalIterator(reader);
}
reader.setRemainingBytes(size);
return new CompactOrdinalIterator(reader);
}
private ByteArrayReader reader(String nodeType, int ordinal) {
long pointer = pointers.getPointer(nodeType, ordinal);
if(pointer == -1)
return null;
return new ByteArrayReader(data, pointer);
}
private NFPropertySpec pointReaderAtProperty(ByteArrayReader reader, String nodeType, String propertyName, int connectionModelIndex) {
NFNodeSpec nodeSpec = graphSpec.getNodeSpec(nodeType);
for (NFPropertySpec propertySpec : nodeSpec.getPropertySpecs()) {
if (propertySpec.getName().equals(propertyName)) {
if(propertySpec.isConnectionModelSpecific())
positionForModel(reader, connectionModelIndex, propertySpec);
return propertySpec;
} else {
skipProperty(reader, propertySpec);
}
}
throw new NFGraphException("Property " + propertyName + " is undefined for node type " + nodeType);
}
private void positionForModel(ByteArrayReader reader, int connectionModelIndex, NFPropertySpec propertySpec) {
reader.setRemainingBytes(reader.readVInt());
for(int i=0;i<connectionModelIndex;i++) {
skipSingleProperty(reader, propertySpec);
}
}
private void skipProperty(ByteArrayReader reader, NFPropertySpec propertySpec) {
if(propertySpec.isConnectionModelSpecific()) {
int size = reader.readVInt();
reader.skip(size);
} else {
skipSingleProperty(reader, propertySpec);
}
}
private void skipSingleProperty(ByteArrayReader reader, NFPropertySpec propertySpec) {
if(propertySpec.isSingle()) {
reader.readVInt();
return;
}
int size = reader.readVInt();
if(size == 0)
return;
if(size == -1) {
int numBits = pointers.numPointers(propertySpec.getToNodeType());
int numBytes = ((numBits - 1) / 8) + 1;
reader.skip(numBytes);
return;
}
if(propertySpec.isHashed()) {
reader.skip(1 << (size - 1));
return;
}
reader.skip(size);
}
public void writeTo(OutputStream os) throws IOException {
NFCompressedGraphSerializer serializer = new NFCompressedGraphSerializer(graphSpec, modelHolder, pointers, data, dataLength);
serializer.serializeTo(os);
}
public static NFCompressedGraph readFrom(InputStream is) throws IOException {
return readFrom(is, null);
}
/**
* When using a {@link ByteSegmentPool}, this method will borrow arrays used to construct the NFCompressedGraph from that pool.
* <p>
* Note that because the {@link ByteSegmentPool} is NOT thread-safe, this this call is also NOT thread-safe.
* It is up to implementations to ensure that only a single update thread
* is accessing this memory pool at any given time.
*/
public static NFCompressedGraph readFrom(InputStream is, ByteSegmentPool memoryPool) throws IOException {
NFCompressedGraphDeserializer deserializer = new NFCompressedGraphDeserializer();
return deserializer.deserialize(is, memoryPool);
}
/**
* When using a {@link ByteSegmentPool}, this method will return all borrowed arrays back to that pool.
* <p>
* Note that because the {@link ByteSegmentPool} is NOT thread-safe, this this call is also NOT thread-safe.
* It is up to implementations to ensure that only a single update thread
* is accessing this memory pool at any given time.
*/
public void destroy() {
if(data instanceof SegmentedByteArray)
((SegmentedByteArray) data).destroy();
}
}
| 1,626 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/NFCompressedGraphPointers.java
|
/*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import java.util.Map;
public interface NFCompressedGraphPointers {
/**
* @return the offset into the {@link NFCompressedGraph}'s byte array for the node identified by the given type and ordinal.
*/
public long getPointer(String nodeType, int ordinal);
public int numPointers(String nodeType);
public Map<String, long[]> asMap();
}
| 1,627 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/SingleOrdinalSet.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
/**
* An implementation of {@link OrdinalSet} containing a single ordinal.
*/
public class SingleOrdinalSet extends OrdinalSet {
private final int ordinal;
public SingleOrdinalSet(int ordinal) {
this.ordinal = ordinal;
}
@Override
public boolean contains(int value) {
return ordinal == value;
}
@Override
public int[] asArray() {
return new int[] { ordinal };
}
@Override
public OrdinalIterator iterator() {
return new SingleOrdinalIterator(ordinal);
}
@Override
public int size() {
return 1;
}
}
| 1,628 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/compressed/NFCompressedGraphIntPointers.java
|
/*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.compressed;
import java.util.HashMap;
import java.util.Map;
import com.netflix.nfgraph.exception.NFGraphException;
/**
* This class holds all of the offsets into the {@link NFCompressedGraph}'s byte array.<p>
*
* This class maintains a mapping of type name to int array. For a given type, the offset in the {@link NFCompressedGraph}'s byte array
* where the connections for a given node are encoded is equal to the value of the int array for the node's type at the index for the node's ordinal.<p>
*
* It is unlikely that this class will need to be used externally.
*/
public class NFCompressedGraphIntPointers implements NFCompressedGraphPointers {
private final Map<String, int[]>pointersByOrdinal;
public NFCompressedGraphIntPointers() {
this.pointersByOrdinal = new HashMap<String, int[]>();
}
/**
* @return the offset into the {@link NFCompressedGraph}'s byte array for the node identified by the given type and ordinal.
*/
public long getPointer(String nodeType, int ordinal) {
int pointers[] = pointersByOrdinal.get(nodeType);
if(pointers == null)
throw new NFGraphException("Undefined node type: " + nodeType);
if(ordinal < pointers.length) {
if(pointers[ordinal] == -1)
return -1;
return 0xFFFFFFFFL & pointers[ordinal];
}
return -1;
}
public void addPointers(String nodeType, int pointers[]) {
pointersByOrdinal.put(nodeType, pointers);
}
public int numPointers(String nodeType) {
return pointersByOrdinal.get(nodeType).length;
}
@Override
public Map<String, long[]> asMap() {
Map<String, long[]> map = new HashMap<String, long[]>();
for(Map.Entry<String, int[]> entry : pointersByOrdinal.entrySet()) {
map.put(entry.getKey(), toLongArray(entry.getValue()));
}
return map;
}
private long[] toLongArray(int[] arr) {
long l[] = new long[arr.length];
for(int i=0;i<arr.length;i++) {
l[i] = arr[i];
}
return l;
}
}
| 1,629 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/build/NFBuildGraphOrdinalSet.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.build;
import java.util.Arrays;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
/**
* And implementation of {@link OrdinalSet} returned for connections in an {@link NFBuildGraph}.
*/
public class NFBuildGraphOrdinalSet extends OrdinalSet {
private final int ordinals[];
private final int size;
public NFBuildGraphOrdinalSet(int ordinals[], int size) {
this.ordinals = ordinals;
this.size = size;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(int value) {
for(int i=0;i<size;i++) {
if(ordinals[i] == value) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int[] asArray() {
return Arrays.copyOf(ordinals, size);
}
/**
* {@inheritDoc}
*/
@Override
public OrdinalIterator iterator() {
return new NFBuildGraphOrdinalIterator(ordinals, size);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return size;
}
}
| 1,630 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/build/NFBuildGraph.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.build;
import static com.netflix.nfgraph.NFGraphModelHolder.CONNECTION_MODEL_GLOBAL;
import com.netflix.nfgraph.NFGraph;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.compressed.NFCompressedGraph;
import com.netflix.nfgraph.compressor.NFCompressedGraphBuilder;
import com.netflix.nfgraph.spec.NFGraphSpec;
import com.netflix.nfgraph.spec.NFNodeSpec;
import com.netflix.nfgraph.spec.NFPropertySpec;
/**
* An <code>NFBuildGraph</code> is used to create a new graph. This representation of the graph data is not especially memory-efficient,
* and is intended to exist only for a short time while the {@link NFGraph} is being populated.<p>
*
* Once the graph is completely populated, it is expected that this <code>NFBuildGraph</code> will be exchanged for a memory-efficient,
* read-only {@link NFCompressedGraph} via the <code>compress()</code> method.<p>
*
* See {@link NFGraph} for an example of code which creates and populates an <code>NFBuildGraph</code>
*
*
*/
public class NFBuildGraph extends NFGraph {
private final NFBuildGraphNodeCache nodeCache;
public NFBuildGraph(NFGraphSpec graphSpec) {
super(graphSpec);
this.nodeCache = new NFBuildGraphNodeCache(graphSpec, modelHolder);
}
@Override
protected int getConnection(int connectionModelIndex, String nodeType, int ordinal, String propertyName) {
NFBuildGraphNode node = nodeCache.getNode(nodeType, ordinal);
NFPropertySpec propertySpec = getPropertySpec(nodeType, propertyName);
return node.getConnection(connectionModelIndex, propertySpec);
}
@Override
protected OrdinalIterator getConnectionIterator(int connectionModelIndex, String nodeType, int ordinal, String propertyName) {
NFBuildGraphNode node = nodeCache.getNode(nodeType, ordinal);
NFPropertySpec propertySpec = getPropertySpec(nodeType, propertyName);
return node.getConnectionIterator(connectionModelIndex, propertySpec);
}
@Override
protected OrdinalSet getConnectionSet(int connectionModelIndex, String nodeType, int ordinal, String propertyName) {
NFBuildGraphNode node = nodeCache.getNode(nodeType, ordinal);
NFPropertySpec propertySpec = getPropertySpec(nodeType, propertyName);
return node.getConnectionSet(connectionModelIndex, propertySpec);
}
/**
* Add a connection to this graph. The connection will be from the node identified by the given <code>nodeType</code> and <code>fromOrdinal</code>.
* The connection will be via the specified <code>viaProperty</code> in the {@link NFNodeSpec} for the given <code>nodeType</code>.
* The connection will be to the node identified by the given <code>toOrdinal</code>. The type of the to node is implied by the <code>viaProperty</code>.
*/
public void addConnection(String nodeType, int fromOrdinal, String viaProperty, int toOrdinal) {
addConnection(CONNECTION_MODEL_GLOBAL, nodeType, fromOrdinal, viaProperty, toOrdinal);
}
/**
* Add a connection to this graph. The connection will be in the given connection model. The connection will be from the node identified by the given
* <code>nodeType</code> and <code>fromOrdinal</code>. The connection will be via the specified <code>viaProperty</code> in the {@link NFNodeSpec} for
* the given <code>nodeType</code>. The connection will be to the node identified by the given <code>toOrdinal</code>. The type of the to node is implied
* by the <code>viaProperty</code>.
*/
public void addConnection(String connectionModel, String nodeType, int fromOrdinal, String viaPropertyName, int toOrdinal) {
NFBuildGraphNode fromNode = nodeCache.getNode(nodeType, fromOrdinal);
NFPropertySpec propertySpec = getPropertySpec(nodeType, viaPropertyName);
int connectionModelIndex = modelHolder.getModelIndex(connectionModel);
NFBuildGraphNode toNode = nodeCache.getNode(propertySpec.getToNodeType(), toOrdinal);
addConnection(fromNode, propertySpec, connectionModelIndex, toNode);
}
/**
* Returns the list of {@link com.netflix.nfgraph.build.NFBuildGraphNode}s associated with the specified
* <code>nodeType</code>.
*/
public NFBuildGraphNodeList getNodes(String nodeType) {
return nodeCache.getNodes(nodeType);
}
/**
* Creates an {@link com.netflix.nfgraph.build.NFBuildGraphNode} for <code>nodeSpec</code> and <code>ordinal</code>
* and adds it to <code>nodes</code>. If such a node exists in <code>nodes</code>, then that node is returned.
*/
public NFBuildGraphNode getOrCreateNode(NFBuildGraphNodeList nodes, NFNodeSpec nodeSpec, int ordinal) {
return nodeCache.getNode(nodes, nodeSpec, ordinal);
}
/**
* Add a connection to this graph. This method is exposed for efficiency purposes. It is more efficient than
* {@code addConnection(String connectionModel, String nodeType, int fromOrdinal, String viaPropertyName, int toOrdinal)}
* as it avoids multiple lookups for <code>fromNode</code>, <code>propertySpec</code>, <code>connectionModelIndex</code>
* and <code>toNode</code>.
*/
public void addConnection(NFBuildGraphNode fromNode, NFPropertySpec propertySpec, int connectionModelIndex, NFBuildGraphNode toNode) {
fromNode.addConnection(connectionModelIndex, propertySpec, toNode.getOrdinal());
toNode.incrementNumIncomingConnections();
}
/**
* Add a connection model, identified by the parameter <code>connectionModel</code> to this graph.<p>
*
* Building the graph may be much more efficient if each connection model is added to the graph with this method
* prior to adding any connections.<p>
*
* This operation is not necessary, but may make building the graph more efficient.
*
* Returns the "model index" used to identify the connection model internally. Passing this to
* the various {@code addConnection()} may offer a performance boost while building the graph.
*/
public int addConnectionModel(String connectionModel) {
return modelHolder.getModelIndex(connectionModel);
}
/**
* Returns the {@link NFPropertySpec} associated with the supplied node type and property name.
*/
public NFPropertySpec getPropertySpec(String nodeType, String propertyName) {
NFNodeSpec nodeSpec = graphSpec.getNodeSpec(nodeType);
NFPropertySpec propertySpec = nodeSpec.getPropertySpec(propertyName);
return propertySpec;
}
/**
* Return a {@link NFCompressedGraph} containing all connections which have been added to this <code>NFBuildGraph</code>.
*/
public NFCompressedGraph compress() {
NFCompressedGraphBuilder builder = new NFCompressedGraphBuilder(graphSpec, nodeCache, modelHolder);
return builder.buildGraph();
}
}
| 1,631 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/build/NFBuildGraphNodeList.java
|
package com.netflix.nfgraph.build;
import java.util.ArrayList;
/**
* Encapsulates an ordered list of {@link com.netflix.nfgraph.build.NFBuildGraphNode}s.
* @author ishastri
*/
public class NFBuildGraphNodeList {
private ArrayList<NFBuildGraphNode> list;
NFBuildGraphNodeList() {
list = new ArrayList<>();
}
public NFBuildGraphNode get(int ordinal) {
return list.get(ordinal);
}
boolean add(NFBuildGraphNode node) {
return list.add(node);
}
public int size() {
return list.size();
}
NFBuildGraphNode set(int ordinal, NFBuildGraphNode node) {
return list.set(ordinal, node);
}
}
| 1,632 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/build/NFBuildGraphNodeCache.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.build;
import java.util.HashMap;
import java.util.Map;
import com.netflix.nfgraph.NFGraphModelHolder;
import com.netflix.nfgraph.spec.NFGraphSpec;
import com.netflix.nfgraph.spec.NFNodeSpec;
public class NFBuildGraphNodeCache {
private final NFGraphSpec graphSpec;
private final NFGraphModelHolder buildGraphModelHolder;
private final Map<String,NFBuildGraphNodeList> nodesByOrdinal;
NFBuildGraphNodeCache(NFGraphSpec graphSpec, NFGraphModelHolder modelHolder) {
this.nodesByOrdinal = new HashMap<String, NFBuildGraphNodeList>();
this.graphSpec = graphSpec;
this.buildGraphModelHolder = modelHolder;
}
NFBuildGraphNode getNode(String nodeType, int ordinal) {
NFBuildGraphNodeList nodes = getNodes(nodeType);
NFNodeSpec nodeSpec = graphSpec.getNodeSpec(nodeType);
return getNode(nodes, nodeSpec, ordinal);
}
NFBuildGraphNode getNode(NFBuildGraphNodeList nodes, NFNodeSpec nodeSpec, int ordinal) {
while (ordinal >= nodes.size()) {
nodes.add(null);
}
NFBuildGraphNode node = nodes.get(ordinal);
if (node == null) {
node = new NFBuildGraphNode(nodeSpec, ordinal, buildGraphModelHolder.size());
nodes.set(ordinal, node);
}
return node;
}
public int numNodes(String nodeType) { return getNodes(nodeType).size(); }
public NFBuildGraphNodeList getNodes(String nodeType) {
NFBuildGraphNodeList nodes = nodesByOrdinal.get(nodeType);
if (nodes == null) {
nodes = new NFBuildGraphNodeList();
nodesByOrdinal.put(nodeType, nodes);
}
return nodes;
}
}
| 1,633 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/build/NFBuildGraphNode.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.build;
import java.util.Arrays;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.spec.NFNodeSpec;
import com.netflix.nfgraph.spec.NFPropertySpec;
public class NFBuildGraphNode {
private final NFNodeSpec nodeSpec;
private NFBuildGraphNodeConnections[] connectionModelSpecificConnections;
private final int ordinal;
private int numIncomingConnections;
NFBuildGraphNode(NFNodeSpec nodeSpec, int ordinal, int numKnownConnectionModels) {
this.nodeSpec = nodeSpec;
this.connectionModelSpecificConnections = new NFBuildGraphNodeConnections[numKnownConnectionModels];
this.ordinal = ordinal;
this.numIncomingConnections = 0;
}
public int getOrdinal() {
return ordinal;
}
public int getConnection(int connectionModelIndex, NFPropertySpec spec) {
NFBuildGraphNodeConnections connections = getConnections(connectionModelIndex);
if(connections == null)
return -1;
return connections.getConnection(spec);
}
public OrdinalSet getConnectionSet(int connectionModelIndex, NFPropertySpec spec) {
NFBuildGraphNodeConnections connections = getConnections(connectionModelIndex);
if(connections == null)
return OrdinalSet.EMPTY_SET;
return connections.getConnectionSet(spec);
}
public OrdinalIterator getConnectionIterator(int connectionModelIndex, NFPropertySpec spec) {
NFBuildGraphNodeConnections connections = getConnections(connectionModelIndex);
if(connections == null)
return OrdinalIterator.EMPTY_ITERATOR;
return connections.getConnectionIterator(spec);
}
void addConnection(int connectionModelIndex, NFPropertySpec spec, int ordinal) {
NFBuildGraphNodeConnections connections = getOrCreateConnections(connectionModelIndex);
connections.addConnection(spec, ordinal);
}
void incrementNumIncomingConnections() {
numIncomingConnections++;
}
int numIncomingConnections() {
return numIncomingConnections;
}
private NFBuildGraphNodeConnections getConnections(int connectionModelIndex) {
if(connectionModelSpecificConnections.length <= connectionModelIndex)
return null;
return connectionModelSpecificConnections[connectionModelIndex];
}
private NFBuildGraphNodeConnections getOrCreateConnections(int connectionModelIndex) {
if(connectionModelSpecificConnections.length <= connectionModelIndex)
connectionModelSpecificConnections = Arrays.copyOf(connectionModelSpecificConnections, connectionModelIndex + 1);
if(connectionModelSpecificConnections[connectionModelIndex] == null) {
connectionModelSpecificConnections[connectionModelIndex] = new NFBuildGraphNodeConnections(nodeSpec);
}
return connectionModelSpecificConnections[connectionModelIndex];
}
}
| 1,634 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/build/NFBuildGraphOrdinalIterator.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.build;
import java.util.Arrays;
import com.netflix.nfgraph.OrdinalIterator;
/**
* An implementation of {@link OrdinalIterator} returned for connections in an {@link NFBuildGraph}.
*/
public class NFBuildGraphOrdinalIterator implements OrdinalIterator {
private final int ordinals[];
private int currentPositionInList;
private int previousOrdinal = Integer.MIN_VALUE;
NFBuildGraphOrdinalIterator(int ordinals[], int size) {
this.ordinals = Arrays.copyOfRange(ordinals, 0, size);
Arrays.sort(this.ordinals);
}
private NFBuildGraphOrdinalIterator(int ordinals[]) {
this.ordinals = ordinals;
}
@Override
public int nextOrdinal() {
if(previousOrdinal == NO_MORE_ORDINALS)
return NO_MORE_ORDINALS;
int nextOrdinal = nextOrdinalInList();
while(nextOrdinal == previousOrdinal) {
nextOrdinal = nextOrdinalInList();
}
previousOrdinal = nextOrdinal;
return nextOrdinal;
}
@Override
public void reset() {
this.previousOrdinal = 0;
this.currentPositionInList = 0;
}
@Override
public OrdinalIterator copy() {
return new NFBuildGraphOrdinalIterator(ordinals);
}
@Override
public boolean isOrdered() {
return true;
}
private int nextOrdinalInList() {
if(currentPositionInList == ordinals.length)
return NO_MORE_ORDINALS;
return ordinals[currentPositionInList++];
}
}
| 1,635 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/build/NFBuildGraphNodeConnections.java
|
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nfgraph.build;
import java.util.Arrays;
import com.netflix.nfgraph.OrdinalIterator;
import com.netflix.nfgraph.OrdinalSet;
import com.netflix.nfgraph.compressed.SingleOrdinalIterator;
import com.netflix.nfgraph.compressed.SingleOrdinalSet;
import com.netflix.nfgraph.spec.NFNodeSpec;
import com.netflix.nfgraph.spec.NFPropertySpec;
/**
* Represents the connections for a node in an {@link NFBuildGraph} for a single connection model.
*
* It is unlikely that this class will need to be used externally.
*/
class NFBuildGraphNodeConnections {
private static final int EMPTY_ORDINAL_ARRAY[] = new int[0];
private final int singleValues[];
private final int multipleValues[][];
private final int multipleValueSizes[];
NFBuildGraphNodeConnections(NFNodeSpec nodeSpec) {
singleValues = new int[nodeSpec.getNumSingleProperties()];
multipleValues = new int[nodeSpec.getNumMultipleProperties()][];
multipleValueSizes = new int[nodeSpec.getNumMultipleProperties()];
Arrays.fill(singleValues, -1);
Arrays.fill(multipleValues, EMPTY_ORDINAL_ARRAY);
}
int getConnection(NFPropertySpec spec) {
if(spec.isSingle())
return singleValues[spec.getPropertyIndex()];
if(multipleValues[spec.getPropertyIndex()].length > 0)
return multipleValues[spec.getPropertyIndex()].length;
return -1;
}
OrdinalSet getConnectionSet(NFPropertySpec spec) {
if(spec.isMultiple()) {
return new NFBuildGraphOrdinalSet(multipleValues[spec.getPropertyIndex()], multipleValueSizes[spec.getPropertyIndex()]);
}
return new SingleOrdinalSet(singleValues[spec.getPropertyIndex()]);
}
OrdinalIterator getConnectionIterator(NFPropertySpec spec) {
if(spec.isMultiple()) {
return new NFBuildGraphOrdinalIterator(multipleValues[spec.getPropertyIndex()], multipleValueSizes[spec.getPropertyIndex()]);
}
return new SingleOrdinalIterator(singleValues[spec.getPropertyIndex()]);
}
void addConnection(NFPropertySpec spec, int ordinal) {
if (spec.isMultiple()) {
addMultipleProperty(spec, ordinal);
} else {
singleValues[spec.getPropertyIndex()] = ordinal;
}
}
void addMultipleProperty(NFPropertySpec spec, int ordinal) {
int values[] = multipleValues[spec.getPropertyIndex()];
int propSize = multipleValueSizes[spec.getPropertyIndex()];
if(values.length == 0) {
values = new int[2];
multipleValues[spec.getPropertyIndex()] = values;
} else if(values.length == propSize) {
values = Arrays.copyOf(values, values.length * 3 / 2);
multipleValues[spec.getPropertyIndex()] = values;
}
values[propSize] = ordinal;
multipleValueSizes[spec.getPropertyIndex()]++;
}
}
| 1,636 |
0 |
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph
|
Create_ds/netflix-graph/src/main/java/com/netflix/nfgraph/exception/NFGraphException.java
|
package com.netflix.nfgraph.exception;
import com.netflix.nfgraph.NFGraph;
/**
* This Exception is thrown when an invalid connection model, node type, or property type is specified in {@link NFGraph} API calls.
*/
public class NFGraphException extends RuntimeException {
private static final long serialVersionUID = -9177454492889434892L;
public NFGraphException(String message) {
super(message);
}
}
| 1,637 |
0 |
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/metrics/ExcludeMetricPredicateTest.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.yammer.metrics.core.MetricName;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
*
*/
public class ExcludeMetricPredicateTest {
@Test
public void exclude() {
ExcludeMetricPredicate predicate = new ExcludeMetricPredicate("my\\.package\\.MyClass.*");
// String group, String type, String name, String scope
assertFalse(predicate.matches(new MetricName("my.package", "MyClass", "some_name", "some_scope"), null));
assertTrue(predicate.matches(new MetricName("another.package", "MyClass", "some_name", "some_scope"), null));
}
@Test
public void exclude2() {
ExcludeMetricPredicate predicate = new ExcludeMetricPredicate("(kafka\\.consumer\\.FetchRequestAndResponseMetrics.*)|(.*ReplicaFetcherThread.*)|(kafka\\.server\\.FetcherLagMetrics\\..*)|(kafka\\.log\\.Log\\..*)|(kafka\\.cluster\\.Partition\\..*)");
assertFalse(predicate.matches(new MetricName("kafka.consumer", "FetchRequestAndResponseMetrics", "some_name", "some_scope"), null));
assertFalse(predicate.matches(new MetricName("kafka.server", "FetcherStats", "ReplicaFetcherThread", "some_scope"), null));
assertTrue(predicate.matches(new MetricName("kafka.server", "ReplicaManager", "IsrExpandsPerSec", "some_scope"), null));
}
}
| 1,638 |
0 |
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/metrics/StatsDReporterTest.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import java.util.EnumSet;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import com.timgroup.statsd.StatsDClient;
import com.yammer.metrics.core.Clock;
import com.yammer.metrics.core.Counter;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.core.Meter;
import com.yammer.metrics.core.Metered;
import com.yammer.metrics.core.Metric;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricProcessor;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.core.Sampling;
import com.yammer.metrics.core.Summarizable;
import com.yammer.metrics.core.Timer;
import com.yammer.metrics.reporting.AbstractPollingReporter;
import com.yammer.metrics.stats.Snapshot;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.Stubber;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class StatsDReporterTest {
private static final String METRIC_BASE_NAME = "java.lang.Object.metric";
@Mock
private Clock clock;
@Mock
private StatsDClient statsD;
private AbstractPollingReporter reporter;
private TestMetricsRegistry registry;
protected static class TestMetricsRegistry extends MetricsRegistry {
public <T extends Metric> T add(MetricName name, T metric) {
return getOrAdd(name, metric);
}
}
@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
when(clock.tick()).thenReturn(1234L);
when(clock.time()).thenReturn(5678L);
registry = new TestMetricsRegistry();
reporter = new StatsDReporter(registry,
statsD,
EnumSet.allOf(Dimension.class)
);
}
@Test
public void isTaggedTest() {
registry.add(new MetricName("kafka.common", "AppInfo", "Version", null, "kafka.common:type=AppInfo,name=Version"),
new Gauge<String>() {
public String value() {
return "0.8.2";
}
});
assertTrue(((StatsDReporter) reporter).isTagged(registry.allMetrics()));
}
protected <T extends Metric> void addMetricAndRunReporter(Callable<T> action) throws Exception {
// Invoke the callable to trigger (ie, mark()/inc()/etc) and return the metric
final T metric = action.call();
try {
// Add the metric to the registry, run the reporter and flush the result
registry.add(new MetricName(Object.class, "metric"), metric);
reporter.run();
} finally {
reporter.shutdown();
}
}
private void verifySend(String metricNameSuffix, double metricValue) {
verify(statsD).gauge(METRIC_BASE_NAME + "." + metricNameSuffix,
metricValue);
}
private void verifySend(double metricValue) {
verify(statsD).gauge(METRIC_BASE_NAME, metricValue);
}
private void verifySend(long metricValue) {
verify(statsD).gauge(METRIC_BASE_NAME, metricValue);
}
private void verifySend(String metricNameSuffix, String metricValue) {
verify(statsD).gauge(METRIC_BASE_NAME + "." + metricNameSuffix,
Double.valueOf(metricValue));
}
public void verifyTimer() {
verifySend("count", "1");
verifySend("meanRate", "2.00");
verifySend("1MinuteRate", "1.00");
verifySend("5MinuteRate", "5.00");
verifySend("15MinuteRate", "15.00");
verifySend("min", "1.00");
verifySend("max", "3.00");
verifySend("mean", "2.00");
verifySend("stddev", "1.50");
verifySend("median", "0.50");
verifySend("p75", "0.7505");
verifySend("p95", "0.9509");
verifySend("p98", "0.98096");
verifySend("p99", "0.99098");
verifySend("p999", "0.999998");
}
public void verifyMeter() {
verifySend("count", 1);
verifySend("meanRate", 2.00);
verifySend("1MinuteRate", 1.00);
verifySend("5MinuteRate", 5.00);
verifySend("15MinuteRate", 15.00);
}
public void verifyHistogram() {
verifySend("min", 1.00);
verifySend("max", 3.00);
verifySend("mean", 2.00);
verifySend("stddev", 1.50);
verifySend("median", 0.50);
verifySend("p75", "0.7505");
verifySend("p95", "0.9509");
verifySend("p98", "0.98096");
verifySend("p99", "0.99098");
verifySend("p999", "0.999998");
}
public void verifyCounter(long count) {
verifySend(count);
}
@Test
public final void counter() throws Exception {
final long count = new Random().nextInt(Integer.MAX_VALUE);
addMetricAndRunReporter(
new Callable<Counter>() {
@Override
public Counter call() throws Exception {
return createCounter(count);
}
});
verifyCounter(count);
}
@Test
public final void histogram() throws Exception {
addMetricAndRunReporter(
new Callable<Histogram>() {
@Override
public Histogram call() throws Exception {
return createHistogram();
}
});
verifyHistogram();
}
@Test
public final void meter() throws Exception {
addMetricAndRunReporter(
new Callable<Meter>() {
@Override
public Meter call() throws Exception {
return createMeter();
}
});
verifyMeter();
}
@Test
public final void timer() throws Exception {
addMetricAndRunReporter(
new Callable<Timer>() {
@Override
public Timer call() throws Exception {
return createTimer();
}
});
verifyTimer();
}
@Test
public final void longGauge() throws Exception {
final long value = 0xdeadbeef;
addMetricAndRunReporter(
new Callable<Gauge<Object>>() {
@Override
public Gauge<Object> call() throws Exception {
return createGauge(value);
}
});
verifySend(value);
}
@Test
public void stringGauge() throws Exception {
final String value = "The Metric";
addMetricAndRunReporter(
new Callable<Gauge<Object>>() {
@Override
public Gauge<Object> call() throws Exception {
return createGauge(value);
}
});
verify(statsD, never()).gauge(Matchers.anyString(), Matchers.anyDouble());
}
static Counter createCounter(long count) throws Exception {
final Counter mock = mock(Counter.class);
when(mock.count()).thenReturn(count);
return configureMatcher(mock, doAnswer(new MetricsProcessorAction() {
@Override
void delegateToProcessor(MetricProcessor<Object> processor, MetricName name, Object context) throws Exception {
processor.processCounter(name, mock, context);
}
}));
}
static Histogram createHistogram() throws Exception {
final Histogram mock = mock(Histogram.class);
setupSummarizableMock(mock);
setupSamplingMock(mock);
return configureMatcher(mock, doAnswer(new MetricsProcessorAction() {
@Override
void delegateToProcessor(MetricProcessor<Object> processor, MetricName name, Object context) throws Exception {
processor.processHistogram(name, mock, context);
}
}));
}
static Gauge<Object> createGauge(Object value) throws Exception {
@SuppressWarnings("unchecked")
final Gauge<Object> mock = mock(Gauge.class);
when(mock.value()).thenReturn(value);
return configureMatcher(mock, doAnswer(new MetricsProcessorAction() {
@Override
void delegateToProcessor(MetricProcessor<Object> processor, MetricName name, Object context) throws Exception {
processor.processGauge(name, mock, context);
}
}));
}
static Timer createTimer() throws Exception {
final Timer mock = mock(Timer.class);
when(mock.durationUnit()).thenReturn(TimeUnit.MILLISECONDS);
setupSummarizableMock(mock);
setupMeteredMock(mock);
setupSamplingMock(mock);
return configureMatcher(mock, doAnswer(new MetricsProcessorAction() {
@Override
void delegateToProcessor(MetricProcessor<Object> processor, MetricName name, Object context) throws Exception {
processor.processTimer(name, mock, context);
}
}));
}
static Meter createMeter() throws Exception {
final Meter mock = mock(Meter.class);
setupMeteredMock(mock);
return configureMatcher(mock, doAnswer(new MetricsProcessorAction() {
@Override
void delegateToProcessor(MetricProcessor<Object> processor, MetricName name, Object context) throws Exception {
processor.processMeter(name, mock, context);
}
}));
}
@SuppressWarnings("unchecked")
static <T extends Metric> T configureMatcher(T mock, Stubber stub) throws Exception {
stub.when(mock).processWith(any(MetricProcessor.class), any(MetricName.class), any());
return mock;
}
static abstract class MetricsProcessorAction implements Answer<Object> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
@SuppressWarnings("unchecked")
final MetricProcessor<Object> processor = (MetricProcessor<Object>) invocation.getArguments()[0];
final MetricName name = (MetricName) invocation.getArguments()[1];
final Object context = invocation.getArguments()[2];
delegateToProcessor(processor, name, context);
return null;
}
abstract void delegateToProcessor(MetricProcessor<Object> processor, MetricName name, Object context) throws Exception;
}
static void setupSummarizableMock(Summarizable summarizable) {
when(summarizable.min()).thenReturn(1d);
when(summarizable.max()).thenReturn(3d);
when(summarizable.mean()).thenReturn(2d);
when(summarizable.stdDev()).thenReturn(1.5d);
}
static void setupMeteredMock(Metered metered) {
when(metered.count()).thenReturn(1L);
when(metered.oneMinuteRate()).thenReturn(1d);
when(metered.fiveMinuteRate()).thenReturn(5d);
when(metered.fifteenMinuteRate()).thenReturn(15d);
when(metered.meanRate()).thenReturn(2d);
when(metered.eventType()).thenReturn("eventType");
when(metered.rateUnit()).thenReturn(TimeUnit.SECONDS);
}
static void setupSamplingMock(Sampling sampling) { //be careful how snapshot defines statistics
final double[] values = new double[1001];
for (int i = 0; i < values.length; i++) {
values[i] = i / 1000.0;
}
when(sampling.getSnapshot()).thenReturn(new Snapshot(values));
}
}
| 1,639 |
0 |
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/metrics/ParserTest.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.yammer.metrics.core.MetricName;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
*
*/
public class ParserTest {
@Test
public void testParseTagInMBeanNameWithSuffix() throws Exception {
MetricName name = new MetricName("kafka.producer",
"ProducerRequestMetrics", "ProducerRequestSize",
"clientId.group7", "kafka.producer:type=ProducerRequestMetrics,name=ProducerRequestSize,clientId=group7");
Parser p = new ParserForTagInMBeanName();
p.parse(name);
assertEquals(p.getName(), "kafka.producer.ProducerRequestMetrics.ProducerRequestSize_all");
assertArrayEquals(p.getTags(), new String[]{"clientId:group7"});
}
@Test
public void testParseTagInMBeanNameWithSuffixWithoutClientId() throws Exception {
MetricName name = new MetricName("kafka.producer",
"ProducerRequestMetrics", "ProducerRequestSize",
null, "kafka.producer:type=ProducerRequestMetrics,name=ProducerRequestSize");
Parser p = new ParserForTagInMBeanName();
p.parse(name);
assertEquals(p.getName(), "kafka.producer.ProducerRequestMetrics.ProducerRequestSize_all");
assertArrayEquals(p.getTags(), new String[]{"clientId:unknown"});
}
@Test
public void testParseTagInMBeanNameWithoutSuffix() throws Exception {
MetricName name = new MetricName("kafka.producer",
"ProducerRequestMetrics", "ProducerRequestSize",
"clientId.group7.brokerPort.9092.brokerHost.10_1_152_206",
"kafka.producer:type=ProducerRequestMetrics,name=ProducerRequestSize,clientId=group7,brokerPort=9092,brokerHost=10.1.152.206");
Parser p = new ParserForTagInMBeanName();
p.parse(name);
assertEquals(p.getName(), "kafka.producer.ProducerRequestMetrics.ProducerRequestSize");
assertArrayEquals(p.getTags(), new String[]{"clientId:group7", "brokerPort:9092", "brokerHost:10.1.152.206"});
}
@Test
public void testParseTagInMBeanNameWithoutClientId() throws Exception {
MetricName name = new MetricName("kafka.producer",
"ProducerRequestMetrics", "ProducerRequestSize",
"brokerPort.9092.brokerHost.10_1_152_206", "kafka.producer:type=ProducerRequestMetrics,name=ProducerRequestSize,brokerPort=9092,brokerHost=10.1.152.206");
Parser p = new ParserForTagInMBeanName();
p.parse(name);
assertEquals(p.getName(), "kafka.producer.ProducerRequestMetrics.ProducerRequestSize");
assertArrayEquals(p.getTags(), new String[]{"clientId:unknown", "brokerPort:9092", "brokerHost:10.1.152.206"});
}
@Test
public void testParseTagInMBeanNameWithoutSuffixForConsumer() throws Exception {
MetricName name = new MetricName("kafka.consumer",
"ZookeeperConsumerConnector", "ZooKeeperCommitsPerSec",
"clientId.group7",
"kafka.consumer:type=ZookeeperConsumerConnector,name=ZooKeeperCommitsPerSec,clientId=group7");
Parser p = new ParserForTagInMBeanName();
p.parse(name);
assertEquals(p.getName(), "kafka.consumer.ZookeeperConsumerConnector.ZooKeeperCommitsPerSec");
assertArrayEquals(p.getTags(), new String[]{"clientId:group7"});
}
@Test
public void testParseTagInMBeanNameNoTag() throws Exception {
MetricName name = new MetricName("kafka.server",
"ReplicaManager", "LeaderCount",
null, "kafka.server:type=ReplicaManager,name=LeaderCount");
Parser p = new ParserForTagInMBeanName();
p.parse(name);
assertEquals(p.getName(), "kafka.server.ReplicaManager.LeaderCount");
assertArrayEquals(p.getTags(), new String[]{});
}
@Test
public void testParseNoTag() throws Exception {
MetricName name = new MetricName("kafka.producer",
"ProducerRequestMetrics", "group7-AllBrokersProducerRequestSize");
Parser p = new ParserForNoTag();
p.parse(name);
assertEquals(p.getName(), "kafka.producer.ProducerRequestMetrics.group7-AllBrokersProducerRequestSize");
assertArrayEquals(p.getTags(), new String[]{});
}
}
| 1,640 |
0 |
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/metrics/MetricNameFormatterTest.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.yammer.metrics.core.MetricName;
import org.junit.Test;
import static com.airbnb.metrics.MetricNameFormatter.format;
import static com.airbnb.metrics.MetricNameFormatter.formatWithScope;
import static org.junit.Assert.assertEquals;
/**
*
*/
public class MetricNameFormatterTest {
@Test
public void testFormat() throws Exception {
assertEquals(
format(new MetricName("kafka.common", "AppInfo", "Version", null, "kafka.common:type=AppInfo,name=Version")),
"kafka.common.AppInfo.Version");
assertEquals(
format(new MetricName("kafka.common", "AppInfo", "Version", "my_scope", "kafka.common:type=AppInfo,name=Version")),
"kafka.common.AppInfo.Version");
}
@Test
public void testFormatWithScope() throws Exception {
assertEquals(
formatWithScope(new MetricName("kafka.common", "AppInfo", "Version", null, "kafka.common:type=AppInfo,name=Version")),
"kafka.common.AppInfo.Version");
assertEquals(
formatWithScope(new MetricName("kafka.common", "AppInfo", "Version", "", "kafka.common:type=AppInfo,name=Version")),
"kafka.common.AppInfo.Version");
assertEquals(
formatWithScope(new MetricName("kafka.common", "AppInfo", "Version", "my_scope", "kafka.common:type=AppInfo,name=Version")),
"kafka.common.AppInfo.my_scope.Version");
}
}
| 1,641 |
0 |
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/metrics/DimensionTest.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import org.junit.Test;
import java.util.EnumSet;
import java.util.Properties;
import static org.junit.Assert.*;
/**
*
*/
public class DimensionTest {
@Test
public void create_from_properties() {
String prefix = "foo.";
Properties p = new Properties();
p.setProperty(prefix + "count", "true");
p.setProperty(prefix + "meanRate", "false");
EnumSet<Dimension> dimensions = Dimension.fromProperties(p, prefix);
assertTrue(dimensions.contains(Dimension.count));
assertFalse(dimensions.contains(Dimension.meanRate));
assertEquals(Dimension.rate1m.displayName, "1MinuteRate");
}
}
| 1,642 |
0 |
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/metrics/KafkaStatsDReporterTest.java
|
package com.airbnb.metrics;
import com.timgroup.statsd.StatsDClient;
import java.util.HashMap;
import org.apache.kafka.common.Metric;
import org.apache.kafka.common.MetricName;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.verify;
public class KafkaStatsDReporterTest {
@Mock
private StatsDClient statsD;
private KafkaStatsDReporter reporter;
private StatsDMetricsRegistry registry;
@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
registry = new StatsDMetricsRegistry();
reporter = new KafkaStatsDReporter(
statsD,
registry
);
}
protected void addMetricAndRunReporter(
Metric metric,
String metricName,
String tag
) throws Exception {
try {
registry.register(metric.metricName(), new MetricInfo(metric, metricName, tag));
reporter.run();
} finally {
reporter.shutdown();
}
}
@Test
public final void sendDoubleGauge() throws Exception {
final double value = 10.11;
Metric metric = new Metric() {
@Override
public MetricName metricName() {
return new MetricName("test-metric", "group", "", new HashMap<>());
}
@Override
public double value() {
return value;
}
// This is a new method added to the `Metric` interface from Kafka v1.0.0,
// which we need for tests on later Kafka versions to pass.
public Object metricValue() {
return value;
}
};
addMetricAndRunReporter(metric, "foo", "bar");
verify(statsD).gauge(Matchers.eq("foo"), Matchers.eq(value), Matchers.eq("bar"));
}
}
| 1,643 |
0 |
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/kafka
|
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/kafka/kafka09/StatsdMetricsReporterTest.java
|
package com.airbnb.kafka.kafka09;
import com.airbnb.metrics.MetricInfo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.kafka.common.Metric;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.metrics.KafkaMetric;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class StatsdMetricsReporterTest {
private final String TEST_METRIC_NAME = "test-metric";
private final String TEST_METRIC_GROUP = "test-group";
private final String TEST_METRIC_DESCRIPTION = "This is a test metric.";
private Map<String, String> configs;
@Before
public void init() {
configs = new HashMap<String, String>();
configs.put(StatsdMetricsReporter.STATSD_HOST, "127.0.0.1");
configs.put(StatsdMetricsReporter.STATSD_PORT, "1234");
configs.put(StatsdMetricsReporter.STATSD_METRICS_PREFIX, "foo");
configs.put(StatsdMetricsReporter.STATSD_REPORTER_ENABLED, "false");
}
@Test
public void init_should_start_reporter_when_enabled() {
configs.put(StatsdMetricsReporter.STATSD_REPORTER_ENABLED, "true");
StatsdMetricsReporter reporter = new StatsdMetricsReporter();
assertFalse("reporter should not be running", reporter.isRunning());
reporter.configure(configs);
reporter.init(new ArrayList<KafkaMetric>());
assertTrue("reporter should be running once #init has been invoked", reporter.isRunning());
}
@Test
public void init_should_not_start_reporter_when_disabled() {
configs.put(StatsdMetricsReporter.STATSD_REPORTER_ENABLED, "false");
StatsdMetricsReporter reporter = new StatsdMetricsReporter();
assertFalse("reporter should not be running", reporter.isRunning());
reporter.configure(configs);
reporter.init(new ArrayList<KafkaMetric>());
assertFalse("reporter should NOT be running once #init has been invoked", reporter.isRunning());
}
@Test
public void testMetricsReporter_sameMetricNamesWithDifferentTags() {
StatsdMetricsReporter reporter = spy(new StatsdMetricsReporter());
reporter.configure(ImmutableMap.of(StatsdMetricsReporter.STATSD_REPORTER_ENABLED, "true"));
StatsDClient mockStatsDClient = mock(NonBlockingStatsDClient.class);
when(reporter.createStatsd()).thenReturn(mockStatsDClient);
KafkaMetric testMetricWithTag = generateMockKafkaMetric(TEST_METRIC_NAME, TEST_METRIC_GROUP, TEST_METRIC_DESCRIPTION, ImmutableMap.of("test-key", "test-value"));
reporter.init(ImmutableList.of(testMetricWithTag));
Assert.assertEquals(ImmutableSet.of(testMetricWithTag), getAllKafkaMetricsHelper(reporter));
KafkaMetric otherTestMetricWithTag = generateMockKafkaMetric(TEST_METRIC_NAME, TEST_METRIC_GROUP, TEST_METRIC_DESCRIPTION, ImmutableMap.of("another-test-key", "another-test-value"));
reporter.metricChange(otherTestMetricWithTag);
Assert.assertEquals(ImmutableSet.of(testMetricWithTag, otherTestMetricWithTag), getAllKafkaMetricsHelper(reporter));
reporter.underlying.run();
reporter.registry.getAllMetricInfo().forEach(info -> verify(mockStatsDClient, atLeastOnce()).gauge(info.getName(), info.getMetric().value(), info.getTags()));
}
private KafkaMetric generateMockKafkaMetric(String name, String group, String description, Map<String, String> tags) {
KafkaMetric mockMetric = mock(KafkaMetric.class);
when(mockMetric.metricName()).thenReturn(new MetricName(name, group, description, tags));
return mockMetric;
}
private static Collection<Metric> getAllKafkaMetricsHelper(StatsdMetricsReporter reporter) {
return reporter.registry.getAllMetricInfo().stream().map(MetricInfo::getMetric).collect(Collectors.toSet());
}
}
| 1,644 |
0 |
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/kafka
|
Create_ds/kafka-statsd-metrics2/src/test/java/com/airbnb/kafka/kafka08/StatsdMetricsReporterTest.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.kafka.kafka08;
import kafka.utils.VerifiableProperties;
import org.junit.Before;
import org.junit.Test;
import java.util.Properties;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
public class StatsdMetricsReporterTest {
private VerifiableProperties properties;
@Before
public void init() {
properties = createMock(VerifiableProperties.class);
expect(properties.props()).andReturn(new Properties());
expect(properties.getInt("kafka.metrics.polling.interval.secs", 10)).andReturn(11);
expect(properties.getString("external.kafka.statsd.host", "localhost")).andReturn("127.0.0.1");
expect(properties.getInt("external.kafka.statsd.port", 8125)).andReturn(1234);
expect(properties.getString("external.kafka.statsd.metrics.prefix", "")).andReturn("foo");
expect(properties.getString("external.kafka.statsd.metrics.exclude_regex",
StatsdMetricsReporter.DEFAULT_EXCLUDE_REGEX)).andReturn("foo");
expect(properties.getBoolean("external.kafka.statsd.tag.enabled", true)).andReturn(false);
}
@Test
public void mbean_name_should_match() {
String name = new StatsdMetricsReporter().getMBeanName();
assertEquals("kafka:type=com.airbnb.kafka.kafka08.StatsdMetricsReporter", name);
}
@Test
public void init_should_start_reporter_when_enabled() {
expect(properties.getBoolean("external.kafka.statsd.reporter.enabled", false)).andReturn(true);
replay(properties);
StatsdMetricsReporter reporter = new StatsdMetricsReporter();
assertFalse("reporter should not be running", reporter.isRunning());
reporter.init(properties);
assertTrue("reporter should be running once #init has been invoked", reporter.isRunning());
verify(properties);
}
@Test
public void init_should_not_start_reporter_when_disabled() {
expect(properties.getBoolean("external.kafka.statsd.reporter.enabled", false)).andReturn(false);
replay(properties);
StatsdMetricsReporter reporter = new StatsdMetricsReporter();
assertFalse("reporter should not be running", reporter.isRunning());
reporter.init(properties);
assertFalse("reporter should NOT be running once #init has been invoked", reporter.isRunning());
verify(properties);
}
}
| 1,645 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/Parser.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.yammer.metrics.core.MetricName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public abstract class Parser {
static final Logger log = LoggerFactory.getLogger(Parser.class);
protected String name;
protected String[] tags;
public String getName() {
return name;
}
public String[] getTags() {
return tags;
}
public abstract void parse(MetricName metricName);
}
| 1,646 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/StatsDMetricsRegistry.java
|
package com.airbnb.metrics;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.common.MetricName;
public class StatsDMetricsRegistry {
private final Map<MetricName, MetricInfo> metrics;
public StatsDMetricsRegistry() {
metrics = new HashMap<>();
}
public void register(MetricName metricName, MetricInfo metricInfo) {
metrics.put(metricName, metricInfo);
}
public void unregister(MetricName metricName) {
metrics.remove(metricName);
}
public Collection<MetricInfo> getAllMetricInfo() {
return metrics.values();
}
}
| 1,647 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/ParserForTagInMBeanName.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.yammer.metrics.core.MetricName;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import static com.airbnb.metrics.MetricNameFormatter.format;
/**
* Parser for kafka 0.8.2 or later version
* where the MBeanName contains tags and
* Scope will store tags as well.
*/
public class ParserForTagInMBeanName extends Parser {
public static final String SUFFIX_FOR_ALL = "_all";
public static final String[] UNKNOWN_TAG = new String[]{"clientId:unknown"};
public static final String[] EMPTY_TAG = new String[]{};
@Override
public void parse(MetricName metricName) {
Pattern p = tagRegexMap.get(metricName.getType());
if (p != null && !p.matcher(metricName.getMBeanName()).matches()) {
name = format(metricName, SUFFIX_FOR_ALL);
} else {
name = format(metricName);
}
tags = parseTags(metricName);
}
//todo update documents
private String[] parseTags(MetricName metricName) {
String[] tags = EMPTY_TAG;
if (metricName.hasScope()) {
final String name = metricName.getName();
final String mBeanName = metricName.getMBeanName();
final int idx = mBeanName.indexOf(name);
if (idx < 0) {
log.error("Cannot find name[{}] in MBeanName[{}]", name, mBeanName);
} else {
String tagStr = mBeanName.substring(idx + name.length() + 1);
if ("kafka.producer".equals(metricName.getGroup()) &&
!tagStr.contains("clientId")) {
tagStr = "clientId=unknown,".concat(tagStr);
}
if (tagStr.length() > 0) {
tags = tagStr.replace('=', ':').split(",");
}
}
} else if ("kafka.producer".equals(metricName.getGroup())) {
tags = UNKNOWN_TAG;
}
return tags;
}
public static final Map<String, Pattern> tagRegexMap = new ConcurrentHashMap<String, Pattern>();
static {
tagRegexMap.put("BrokerTopicMetrics", Pattern.compile(".*topic=.*"));
tagRegexMap.put("DelayedProducerRequestMetrics", Pattern.compile(".*topic=.*"));
tagRegexMap.put("ProducerTopicMetrics", Pattern.compile(".*topic=.*"));
tagRegexMap.put("ProducerRequestMetrics", Pattern.compile(".*brokerHost=.*"));
tagRegexMap.put("ConsumerTopicMetrics", Pattern.compile(".*topic=.*"));
tagRegexMap.put("FetchRequestAndResponseMetrics", Pattern.compile(".*brokerHost=.*"));
tagRegexMap.put("ZookeeperConsumerConnector", Pattern.compile(".*name=OwnedPartitionsCount,.*topic=.*|^((?!name=OwnedPartitionsCount).)*$"));
}
}
| 1,648 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/ParserForNoTag.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.yammer.metrics.core.MetricName;
import static com.airbnb.metrics.MetricNameFormatter.formatWithScope;
/**
* Parser for statsd not supporting tags
*/
public class ParserForNoTag extends Parser {
public static final String[] EMPTY_TAG = new String[]{};
@Override
public void parse(MetricName metricName) {
name = formatWithScope(metricName);
tags = EMPTY_TAG;
}
}
| 1,649 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/MetricNameFormatter.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.yammer.metrics.core.MetricName;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MetricNameFormatter {
static final Pattern whitespaceRegex = Pattern.compile("\\s+");
public static String formatWithScope(MetricName metricName) {
StringBuilder sb = new StringBuilder(128)
.append(metricName.getGroup())
.append('.')
.append(metricName.getType())
.append('.');
if (metricName.hasScope() && !metricName.getScope().isEmpty()) {
sb.append(metricName.getScope())
.append(".");
}
sb.append(sanitizeName(metricName.getName()));
return sb.toString();
}
public static String format(MetricName metricName) {
return format(metricName, "");
}
public static String format(MetricName metricName, String suffix) {
return new StringBuilder(128)
.append(metricName.getGroup())
.append('.')
.append(metricName.getType())
.append('.')
.append(sanitizeName(metricName.getName()))
.append(suffix)
.toString();
}
public static String sanitizeName(String name) {
Matcher m = whitespaceRegex.matcher(name);
if (m.find())
return m.replaceAll("_");
else
return name;
}
}
| 1,650 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/ExcludeMetricPredicate.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.yammer.metrics.core.Metric;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricPredicate;
import org.apache.log4j.Logger;
import java.util.regex.Pattern;
/**
*
*/
public class ExcludeMetricPredicate implements MetricPredicate {
private final Logger logger = Logger.getLogger(getClass());
final String excludeRegex;
final Pattern pattern;
public ExcludeMetricPredicate(String excludeRegex) {
this.excludeRegex = excludeRegex;
this.pattern = Pattern.compile(excludeRegex);
}
@Override
public boolean matches(MetricName name, Metric metric) {
String n = MetricNameFormatter.format(name);
boolean excluded = pattern.matcher(n).matches();
if (excluded) {
if (logger.isTraceEnabled()) {
logger.trace("Metric " + n + " is excluded");
}
}
return !excluded;
}
}
| 1,651 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/StatsDReporter.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import com.timgroup.statsd.StatsDClient;
import com.yammer.metrics.core.*;
import com.yammer.metrics.reporting.AbstractPollingReporter;
import com.yammer.metrics.stats.Snapshot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.EnumSet;
import java.util.Map;
import java.util.TreeMap;
import static com.airbnb.metrics.Dimension.*;
/**
*
*/
public class StatsDReporter extends AbstractPollingReporter implements MetricProcessor<Long> {
static final Logger log = LoggerFactory.getLogger(StatsDReporter.class);
public static final String REPORTER_NAME = "kafka-statsd-metrics";
private final StatsDClient statsd;
private final Clock clock;
private final EnumSet<Dimension> dimensions;
private MetricPredicate metricPredicate;
private boolean isTagEnabled;
private Parser parser;
public StatsDReporter(MetricsRegistry metricsRegistry,
StatsDClient statsd,
EnumSet<Dimension> metricDimensions) {
this(metricsRegistry, statsd, REPORTER_NAME, MetricPredicate.ALL, metricDimensions, true);
}
public StatsDReporter(MetricsRegistry metricsRegistry,
StatsDClient statsd,
MetricPredicate metricPredicate,
EnumSet<Dimension> metricDimensions,
boolean isTagEnabled) {
this(metricsRegistry, statsd, REPORTER_NAME, metricPredicate, metricDimensions, isTagEnabled);
}
public StatsDReporter(MetricsRegistry metricsRegistry,
StatsDClient statsd,
String reporterName,
MetricPredicate metricPredicate,
EnumSet<Dimension> metricDimensions,
boolean isTagEnabled) {
super(metricsRegistry, reporterName);
this.statsd = statsd; //exception in statsd is handled by default NO_OP_HANDLER (do nothing)
this.clock = Clock.defaultClock();
this.parser = null; //postpone set it because kafka doesn't start reporting any metrics.
this.dimensions = metricDimensions;
this.metricPredicate = metricPredicate;
this.isTagEnabled = isTagEnabled;
}
@Override
public void run() {
try {
final long epoch = clock.time() / 1000;
if (parser == null) {
createParser(getMetricsRegistry());
}
sendAllKafkaMetrics(epoch);
} catch (RuntimeException ex) {
log.error("Failed to print metrics to statsd", ex);
}
}
private void createParser(MetricsRegistry metricsRegistry) {
if (isTagEnabled) {
final boolean isMetricsTagged = isTagged(metricsRegistry.allMetrics());
if (isMetricsTagged) {
log.info("Kafka metrics are tagged");
parser = new ParserForTagInMBeanName();
} else {
parser = new ParserForNoTag();
}
} else {
parser = new ParserForNoTag();
}
}
//kafka.common.AppInfo is not reliable, sometimes, not correctly loaded.
public boolean isTagged(Map<MetricName, Metric> metrics) {
for (MetricName metricName : metrics.keySet()) {
if ("kafka.common:type=AppInfo,name=Version".equals(metricName.getMBeanName())
|| metricName.hasScope()) {
return true;
}
}
return false;
}
private void sendAllKafkaMetrics(long epoch) {
final Map<MetricName, Metric> allMetrics = new TreeMap<MetricName, Metric>(getMetricsRegistry().allMetrics());
for (Map.Entry<MetricName, Metric> entry : allMetrics.entrySet()) {
sendAMetric(entry.getKey(), entry.getValue(), epoch);
}
}
private void sendAMetric(MetricName metricName, Metric metric, long epoch) {
log.debug("MBeanName[{}], Group[{}], Name[{}], Scope[{}], Type[{}]",
metricName.getMBeanName(), metricName.getGroup(), metricName.getName(),
metricName.getScope(), metricName.getType());
if (metricPredicate.matches(metricName, metric) && metric != null) {
try {
parser.parse(metricName);
metric.processWith(this, metricName, epoch);
} catch (Exception ignored) {
log.error("Error printing regular metrics:", ignored);
}
}
}
@Override
public void processCounter(MetricName metricName, Counter counter, Long context) throws Exception {
statsd.gauge(parser.getName(), counter.count(), parser.getTags());
}
@Override
public void processMeter(MetricName metricName, Metered meter, Long epoch) {
send(meter);
}
@Override
public void processHistogram(MetricName metricName, Histogram histogram, Long context) throws Exception {
send((Summarizable) histogram);
send((Sampling) histogram);
}
@Override
public void processTimer(MetricName metricName, Timer timer, Long context) throws Exception {
send((Metered) timer);
send((Summarizable) timer);
send((Sampling) timer);
}
@Override
public void processGauge(MetricName metricName, Gauge<?> gauge, Long context) throws Exception {
final Object value = gauge.value();
final Boolean flag = isDoubleParsable(value);
if (flag == null) {
log.debug("Gauge can only record long or double metric, it is " + value.getClass());
} else if (flag.equals(true)) {
statsd.gauge(parser.getName(), new Double(value.toString()), parser.getTags());
} else {
statsd.gauge(parser.getName(), new Long(value.toString()), parser.getTags());
}
}
protected static final Dimension[] meterDims = {count, meanRate, rate1m, rate5m, rate15m};
protected static final Dimension[] summarizableDims = {min, max, mean, stddev};
protected static final Dimension[] SamplingDims = {median, p75, p95, p98, p99, p999};
private void send(Metered metric) {
double[] values = {metric.count(), metric.meanRate(), metric.oneMinuteRate(),
metric.fiveMinuteRate(), metric.fifteenMinuteRate()};
for (int i = 0; i < values.length; ++i) {
sendDouble(meterDims[i], values[i]);
}
}
protected void send(Summarizable metric) {
double[] values = {metric.min(), metric.max(), metric.mean(), metric.stdDev()};
for (int i = 0; i < values.length; ++i) {
sendDouble(summarizableDims[i], values[i]);
}
}
protected void send(Sampling metric) {
final Snapshot snapshot = metric.getSnapshot();
double[] values = {snapshot.getMedian(), snapshot.get75thPercentile(), snapshot.get95thPercentile(),
snapshot.get98thPercentile(), snapshot.get99thPercentile(), snapshot.get999thPercentile()};
for (int i = 0; i < values.length; ++i) {
sendDouble(SamplingDims[i], values[i]);
}
}
private void sendDouble(Dimension dim, double value) {
if (dimensions.contains(dim)) {
statsd.gauge(parser.getName() + "." + dim.getDisplayName(), value, parser.getTags());
}
}
private Boolean isDoubleParsable(final Object o) {
if (o instanceof Float) {
return true;
} else if (o instanceof Double) {
return true;
} else if (o instanceof Byte) {
return false;
} else if (o instanceof Short) {
return false;
} else if (o instanceof Integer) {
return false;
} else if (o instanceof Long) {
return false;
} else if (o instanceof BigInteger) {
return false;
} else if (o instanceof BigDecimal) {
return true;
}
return null;
}
}
| 1,652 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/Dimension.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.metrics;
import java.util.EnumSet;
import java.util.Map;
import java.util.Properties;
/**
*
*/
public enum Dimension { //use name itself as suffix
count("count"),
meanRate("meanRate"),
rate1m("1MinuteRate"),
rate5m("5MinuteRate"),
rate15m("15MinuteRate"),
min("min"),
max("max"),
mean("mean"),
stddev("stddev"),
median("median"),
p75("p75"),
p95("p95"),
p98("p98"),
p99("p99"),
p999("p999");
final String displayName;
public String getDisplayName() {
return displayName;
}
Dimension(String defaultValue) {
this.displayName = defaultValue;
}
public static EnumSet<Dimension> fromProperties(Properties p, String prefix) {
EnumSet<Dimension> df = EnumSet.allOf(Dimension.class);
for (Dimension k : Dimension.values()) {
String key = prefix + k.toString();
if (p.containsKey(key)) {
Boolean value = Boolean.parseBoolean(p.getProperty(key));
if (!value) {
df.remove(k);
}
}
}
return df;
}
public static EnumSet<Dimension> fromConfigs(Map<String, ?> configs, String prefix) {
EnumSet<Dimension> df = EnumSet.allOf(Dimension.class);
for (Dimension k : Dimension.values()) {
String key = prefix + k.toString();
if (configs.containsKey(key)) {
Boolean value = (Boolean) configs.get(key);
if (!value) {
df.remove(k);
}
}
}
return df;
}
}
| 1,653 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/KafkaStatsDReporter.java
|
package com.airbnb.metrics;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.timgroup.statsd.StatsDClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KafkaStatsDReporter implements Runnable {
private static final Logger log = LoggerFactory.getLogger(KafkaStatsDReporter.class);
private final ScheduledExecutorService executor;
private final StatsDClient statsDClient;
private final StatsDMetricsRegistry registry;
public KafkaStatsDReporter(
StatsDClient statsDClient,
StatsDMetricsRegistry registry
) {
this.statsDClient = statsDClient;
this.registry = registry;
this.executor = new ScheduledThreadPoolExecutor(1);
}
public void start(
long period,
TimeUnit unit
) {
executor.scheduleWithFixedDelay(this, period, period, unit);
}
public void shutdown() throws InterruptedException {
executor.shutdown();
}
private void sendAllKafkaMetrics() {
registry.getAllMetricInfo().forEach(this::sendAMetric);
}
private void sendAMetric(MetricInfo metricInfo) {
String metricName = metricInfo.getName();
String tags = metricInfo.getTags();
final Object value = metricInfo.getMetric().value();
Double val = new Double(value.toString());
if (val == Double.NEGATIVE_INFINITY || val == Double.POSITIVE_INFINITY) {
val = 0D;
}
if (tags != null) {
statsDClient.gauge(metricName, val, tags);
} else {
statsDClient.gauge(metricName, val);
}
}
@Override
public void run() {
sendAllKafkaMetrics();
}
}
| 1,654 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/MetricInfo.java
|
package com.airbnb.metrics;
import org.apache.kafka.common.Metric;
public class MetricInfo {
private final Metric metric;
private final String name;
private final String tags;
public MetricInfo(Metric metric, String name, String tags) {
this.metric = metric;
this.name = name;
this.tags = tags;
}
public Metric getMetric() {
return metric;
}
public String getName() {
return name;
}
public String getTags() {
return tags;
}
}
| 1,655 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka/kafka09/StatsdMetricsReporter.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.kafka.kafka09;
import com.airbnb.metrics.Dimension;
import com.airbnb.metrics.KafkaStatsDReporter;
import com.airbnb.metrics.MetricInfo;
import com.airbnb.metrics.StatsDMetricsRegistry;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
import com.timgroup.statsd.StatsDClientException;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.metrics.KafkaMetric;
import org.apache.kafka.common.metrics.MetricsReporter;
import org.slf4j.LoggerFactory;
public class StatsdMetricsReporter implements MetricsReporter {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(StatsdMetricsReporter.class);
public static final String REPORTER_NAME = "kafka-statsd-metrics-0.5";
public static final String STATSD_REPORTER_ENABLED = "external.kafka.statsd.reporter.enabled";
public static final String STATSD_HOST = "external.kafka.statsd.host";
public static final String STATSD_PORT = "external.kafka.statsd.port";
public static final String STATSD_METRICS_PREFIX = "external.kafka.statsd.metrics.prefix";
public static final String POLLING_INTERVAL_SECS = "kafka.metrics.polling.interval.secs";
public static final String STATSD_DIMENSION_ENABLED = "external.kafka.statsd.dimension.enabled";
private static final String METRIC_PREFIX = "kafka.";
private static final int POLLING_PERIOD_IN_SECONDS = 10;
private boolean enabled;
private final AtomicBoolean running = new AtomicBoolean(false);
private String host;
private int port;
private String prefix;
private long pollingPeriodInSeconds;
private EnumSet<Dimension> metricDimensions;
private StatsDClient statsd;
private Map<String, KafkaMetric> kafkaMetrics;
StatsDMetricsRegistry registry;
KafkaStatsDReporter underlying = null;
public boolean isRunning() {
return running.get();
}
@Override
public void init(List<KafkaMetric> metrics) {
registry = new StatsDMetricsRegistry();
kafkaMetrics = new HashMap<String, KafkaMetric>();
if (enabled) {
startReporter(POLLING_PERIOD_IN_SECONDS);
} else {
log.warn("KafkaStatsDReporter is disabled");
}
for (KafkaMetric metric : metrics) {
metricChange(metric);
}
}
private String getMetricName(final KafkaMetric metric) {
MetricName metricName = metric.metricName();
return METRIC_PREFIX + metricName.group() + "." + metricName.name();
}
@Override
public void metricChange(final KafkaMetric metric) {
String name = getMetricName(metric);
StringBuilder strBuilder = new StringBuilder();
for (String key : metric.metricName().tags().keySet()) {
strBuilder.append(key).append(":").append(metric.metricName().tags().get(key)).append(",");
}
if (strBuilder.length() > 0) {
strBuilder.deleteCharAt(strBuilder.length() - 1);
}
registry.register(metric.metricName(), new MetricInfo(metric, name, strBuilder.toString()));
log.debug("metrics name: {}", name);
}
@Override
public void metricRemoval(KafkaMetric metric) {
registry.unregister(metric.metricName());
}
@Override
public void close() {
stopReporter();
}
@Override
public void configure(Map<String, ?> configs) {
enabled = configs.containsKey(STATSD_REPORTER_ENABLED) ?
Boolean.valueOf((String) configs.get(STATSD_REPORTER_ENABLED)) : false;
host = configs.containsKey(STATSD_HOST) ?
(String) configs.get(STATSD_HOST) : "localhost";
port = configs.containsKey(STATSD_PORT) ?
Integer.valueOf((String) configs.get(STATSD_PORT)) : 8125;
prefix = configs.containsKey(STATSD_METRICS_PREFIX) ?
(String) configs.get(STATSD_METRICS_PREFIX) : "";
pollingPeriodInSeconds = configs.containsKey(POLLING_INTERVAL_SECS) ?
Integer.valueOf((String) configs.get(POLLING_INTERVAL_SECS)) : 10;
metricDimensions = Dimension.fromConfigs(configs, STATSD_DIMENSION_ENABLED);
}
public void startReporter(long pollingPeriodInSeconds) {
if (pollingPeriodInSeconds <= 0) {
throw new IllegalArgumentException("Polling period must be greater than zero");
}
synchronized (running) {
if (running.get()) {
log.warn("KafkaStatsDReporter: {} is already running", REPORTER_NAME);
} else {
statsd = createStatsd();
underlying = new KafkaStatsDReporter(statsd, registry);
underlying.start(pollingPeriodInSeconds, TimeUnit.SECONDS);
log.info(
"Started KafkaStatsDReporter: {} with host={}, port={}, polling_period_secs={}, prefix={}",
REPORTER_NAME, host, port, pollingPeriodInSeconds, prefix
);
running.set(true);
}
}
}
StatsDClient createStatsd() {
try {
return new NonBlockingStatsDClient(prefix, host, port);
} catch (StatsDClientException ex) {
log.error("KafkaStatsDReporter cannot be started");
throw ex;
}
}
private void stopReporter() {
if (!enabled) {
log.warn("KafkaStatsDReporter is disabled");
} else {
synchronized (running) {
if (running.get()) {
try {
underlying.shutdown();
} catch (InterruptedException e) {
log.warn("Stop reporter exception: {}", e);
}
statsd.stop();
running.set(false);
log.info("Stopped KafkaStatsDReporter with host={}, port={}", host, port);
} else {
log.warn("KafkaStatsDReporter is not running");
}
}
}
}
}
| 1,656 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka/kafka08/StatsdMetricsReporter.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.kafka.kafka08;
import com.airbnb.metrics.Dimension;
import com.airbnb.metrics.ExcludeMetricPredicate;
import com.airbnb.metrics.StatsDReporter;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
import com.timgroup.statsd.StatsDClientException;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.MetricPredicate;
import com.yammer.metrics.reporting.AbstractPollingReporter;
import kafka.metrics.KafkaMetricsReporter;
import kafka.utils.VerifiableProperties;
import org.slf4j.LoggerFactory;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
*
*/
public class StatsdMetricsReporter implements StatsdMetricsReporterMBean, KafkaMetricsReporter {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(StatsDReporter.class);
public static final String DEFAULT_EXCLUDE_REGEX = "(kafka\\.server\\.FetcherStats.*ConsumerFetcherThread.*)|(kafka\\.consumer\\.FetchRequestAndResponseMetrics.*)|(.*ReplicaFetcherThread.*)|(kafka\\.server\\.FetcherLagMetrics\\..*)|(kafka\\.log\\.Log\\..*)|(kafka\\.cluster\\.Partition\\..*)";
private boolean enabled;
private final AtomicBoolean running = new AtomicBoolean(false);
private String host;
private int port;
private String prefix;
private long pollingPeriodInSeconds;
private EnumSet<Dimension> metricDimensions;
private MetricPredicate metricPredicate;
private StatsDClient statsd;
private boolean isTagEnabled;
private AbstractPollingReporter underlying = null;
@Override
public String getMBeanName() {
return "kafka:type=" + getClass().getName();
}
public boolean isRunning() {
return running.get();
}
//try to make it compatible with kafka-statsd-metrics2
@Override
public synchronized void init(VerifiableProperties props) {
loadConfig(props);
if (enabled) {
log.info("Reporter is enabled and starting...");
startReporter(pollingPeriodInSeconds);
} else {
log.warn("Reporter is disabled");
}
}
private void loadConfig(VerifiableProperties props) {
enabled = props.getBoolean("external.kafka.statsd.reporter.enabled", false);
host = props.getString("external.kafka.statsd.host", "localhost");
port = props.getInt("external.kafka.statsd.port", 8125);
prefix = props.getString("external.kafka.statsd.metrics.prefix", "");
pollingPeriodInSeconds = props.getInt("kafka.metrics.polling.interval.secs", 10);
metricDimensions = Dimension.fromProperties(props.props(), "external.kafka.statsd.dimension.enabled.");
String excludeRegex = props.getString("external.kafka.statsd.metrics.exclude_regex", DEFAULT_EXCLUDE_REGEX);
if (excludeRegex != null && excludeRegex.length() != 0) {
metricPredicate = new ExcludeMetricPredicate(excludeRegex);
} else {
metricPredicate = MetricPredicate.ALL;
}
this.isTagEnabled = props.getBoolean("external.kafka.statsd.tag.enabled", true);
}
@Override
public void startReporter(long pollingPeriodInSeconds) {
if (pollingPeriodInSeconds <= 0) {
throw new IllegalArgumentException("Polling period must be greater than zero");
}
synchronized (running) {
if (running.get()) {
log.warn("Reporter is already running");
} else {
statsd = createStatsd();
underlying = new StatsDReporter(
Metrics.defaultRegistry(),
statsd,
metricPredicate,
metricDimensions,
isTagEnabled);
underlying.start(pollingPeriodInSeconds, TimeUnit.SECONDS);
log.info("Started Reporter with host={}, port={}, polling_period_secs={}, prefix={}",
host, port, pollingPeriodInSeconds, prefix);
running.set(true);
}
}
}
private StatsDClient createStatsd() {
try {
return new NonBlockingStatsDClient(
prefix, /* prefix to any stats; may be null or empty string */
host, /* common case: localhost */
port /* port */
);
} catch (StatsDClientException ex) {
log.error("Reporter cannot be started");
throw ex;
}
}
@Override
public void stopReporter() {
if (!enabled) {
log.warn("Reporter is disabled");
} else {
synchronized (running) {
if (running.get()) {
underlying.shutdown();
statsd.stop();
running.set(false);
log.info("Stopped Reporter with host={}, port={}", host, port);
} else {
log.warn("Reporter is not running");
}
}
}
}
}
| 1,657 |
0 |
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka
|
Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka/kafka08/StatsdMetricsReporterMBean.java
|
/*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airbnb.kafka.kafka08;
import kafka.metrics.KafkaMetricsReporterMBean;
/**
* @see kafka.metrics.KafkaMetricsReporterMBean: the custom reporter needs to
* additionally implement an MBean trait that extends kafka.metrics.KafkaMetricsReporterMBean
* so that the registered MBean is compliant with the standard MBean convention.
*/
public interface StatsdMetricsReporterMBean extends KafkaMetricsReporterMBean {
}
| 1,658 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslKeyExchangeException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when a key exchange exception occurs within the Message Security
* Layer.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslKeyExchangeException extends MslException {
private static final long serialVersionUID = -1272784987270064773L;
/**
* Construct a new MSL key exchange exception with the specified error.
*
* @param error the error.
*/
public MslKeyExchangeException(final MslError error) {
super(error);
}
/**
* Construct a new MSL key exchange exception with the specified error and
* details.
*
* @param error the error.
* @param details the details text.
*/
public MslKeyExchangeException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL key exchange exception with the specified error,
* details, and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslKeyExchangeException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL key exchange exception with the specified error and
* cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslKeyExchangeException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslKeyExchangeException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslKeyExchangeException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslKeyExchangeException setUserIdToken(final UserIdToken userIdToken) {
super.setUserIdToken(userIdToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserAuthenticationData(com.netflix.msl.userauth.UserAuthenticationData)
*/
@Override
public MslKeyExchangeException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
super.setUserAuthenticationData(userAuthData);
return this;
}
}
| 1,659 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when an exception occurs within the Message Security Layer.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslException extends Exception {
private static final long serialVersionUID = -2444322310603180494L;
/**
* Construct a new MSL exception with the specified error.
*
* @param error the error.
*/
public MslException(final MslError error) {
super(error.getMessage());
this.error = error;
}
/**
* Construct a new MSL exception with the specified error and details.
*
* @param error the error.
* @param details the details text.
*/
public MslException(final MslError error, final String details) {
super(error.getMessage() + " [" + details + "]");
this.error = error;
}
/**
* Construct a new MSL exception with the specified error, details, and
* cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslException(final MslError error, final String details, final Throwable cause) {
super(error.getMessage() + " [" + details + "]", cause);
this.error = error;
}
/**
* Construct a new MSL exception with the specified error and cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslException(final MslError error, final Throwable cause) {
super(error.getMessage(), cause);
this.error = error;
}
/**
* Set the entity associated with the exception, using a master token. This
* does nothing if the entity is already set.
*
* @param masterToken entity associated with the error. May be null.
* @return this.
*/
public MslException setMasterToken(final MasterToken masterToken) {
if (getMasterToken() == null && getEntityAuthenticationData() == null)
this.masterToken = masterToken;
return this;
}
/**
* Set the entity associated with the exception, using entity
* authentication data. This does nothing if the entity is already set.
*
* @param entityAuthData entity associated with the error. May be null.
* @return this.
*/
public MslException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
if (getMasterToken() == null && getEntityAuthenticationData() == null)
this.entityAuthData = entityAuthData;
return this;
}
/**
* Set the user associated with the exception, using a user ID token. This
* does nothing if the user is already set.
*
* @param userIdToken user associated with the error. May be null.
* @return this.
*/
public MslException setUserIdToken(final UserIdToken userIdToken) {
if (getUserIdToken() == null && getUserAuthenticationData() == null)
this.userIdToken = userIdToken;
return this;
}
/**
* Set the user associated with the exception, using user authentication
* data. This does nothing if the user is already set.
*
* @param userAuthData user associated with the error. May be null.
* @return this.
*/
public MslException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
if (getUserIdToken() == null && getUserAuthenticationData() == null)
this.userAuthData = userAuthData;
return this;
}
/**
* Set the message ID of the message associated with the exception. This
* does nothing if the message ID is already set.
*
* @param messageId message ID of the message associated with this error.
* @return this.
*/
public MslException setMessageId(final long messageId) {
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new IllegalArgumentException("Message ID " + messageId + " is outside the valid range.");
if (getMessageId() == null)
this.messageId = Long.valueOf(messageId);
return this;
}
/**
* @return the error.
*/
public MslError getError() {
return error;
}
/**
* Returns the master token of the entity associated with the exception.
* May be null if the entity is identified by entity authentication data or
* not applicable to the exception.
*
* @return the master token or null.
* @see #getEntityAuthenticationData()
*/
public MasterToken getMasterToken() {
if (masterToken != null)
return masterToken;
// We have to search through the stack in case there is a nested master
// token.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getMasterToken();
}
// No master token.
return null;
}
/**
* Returns the entity authentication data of the entity associated with the
* exception. May be null if the entity is identified by a master token or
* not applicable to the exception.
*
* @return the entity authentication data or null.
* @see #getMasterToken()
*/
public EntityAuthenticationData getEntityAuthenticationData() {
if (entityAuthData != null)
return entityAuthData;
// We have to search through the stack in case there is a nested entity
// authentication data.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getEntityAuthenticationData();
}
// No entity authentication data.
return null;
}
/**
* Returns the user ID token of the user associated with the exception. May
* be null if the user is identified by user authentication data or not
* applicable to the exception.
*
* @return the user ID token or null.
* @see #getUserAuthenticationData()
*/
public UserIdToken getUserIdToken() {
if (userIdToken != null)
return userIdToken;
// We have to search through the stack in case there is a nested user
// ID token.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getUserIdToken();
}
// No user ID token.
return null;
}
/**
* Returns the user authentication data of the user associated with the
* exception. May be null if the user is identified by a user ID token or
* not applicable to the exception.
*
* @return the user authentication data or null.
* @see #getUserIdToken()
*/
public UserAuthenticationData getUserAuthenticationData() {
if (userAuthData != null)
return userAuthData;
// We have to search through the stack in case there is a nested user
// authentication data.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getUserAuthenticationData();
}
// No user authentication data.
return null;
}
/**
* Returns the message ID of the message associated with the exception. May
* be null if there is no message associated or the exception was thrown
* before extracting the message ID.
*
* @return the message ID or null.
*/
public Long getMessageId() {
if (messageId != null)
return messageId;
// We have to search through the stack in case there is a nested
// message ID.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getMessageId();
}
// No message ID.
return null;
}
/** MSL error. */
private final MslError error;
/** Master token. */
private MasterToken masterToken = null;
/** Entity authentication data. */
private EntityAuthenticationData entityAuthData = null;
/** User ID token. */
private UserIdToken userIdToken = null;
/** User authentication data. */
private UserAuthenticationData userAuthData = null;
/** Message ID. */
private Long messageId = null;
}
| 1,660 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslMessageException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
/**
* Thrown when a message exception occurs within the Message Security Layer.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslMessageException extends MslException {
private static final long serialVersionUID = 8022562525891870639L;
/**
* Construct a new MSL message exception with the specified error.
*
* @param error the error.
*/
public MslMessageException(final MslError error) {
super(error);
}
/**
* Construct a new MSL message exception with the specified error and
* details.
*
* @param error the error.
* @param details the details text.
*/
public MslMessageException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL message exception with the specified error, details,
* and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslMessageException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslMessageException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslMessageException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslMessageException setUserIdToken(final UserIdToken userIdToken) {
super.setUserIdToken(userIdToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMessageId(long)
*/
@Override
public MslMessageException setMessageId(final long messageId) {
super.setMessageId(messageId);
return this;
}
}
| 1,661 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslEncodingException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when an encoding exception occurs within the Message Security Layer.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslEncodingException extends MslException {
private static final long serialVersionUID = -2295976834635986944L;
/**
* Construct a new MSL encoding exception with the specified error.
*
* @param error the error.
*/
public MslEncodingException(final MslError error) {
super(error);
}
/**
* Construct a new MSL encoding exception with the specified error and
* details.
*
* @param error the error.
* @param details the details text.
*/
public MslEncodingException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL encoding exception with the specified error,
* details, and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslEncodingException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL encoding exception with the specified error and
* cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslEncodingException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslEncodingException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslEncodingException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslEncodingException setUserIdToken(final UserIdToken userIdToken) {
super.setUserIdToken(userIdToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserAuthenticationData(com.netflix.msl.userauth.UserAuthenticationData)
*/
@Override
public MslEncodingException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
super.setUserAuthenticationData(userAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMessageId(long)
*/
@Override
public MslEncodingException setMessageId(final long messageId) {
super.setMessageId(messageId);
return this;
}
}
| 1,662 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslCryptoException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
/**
* Thrown when a crypto exception occurs within the Message Security Layer.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslCryptoException extends MslException {
private static final long serialVersionUID = -7618578454440397528L;
/**
* Construct a new MSL crypto exception with the specified error.
*
* @param error the error.
*/
public MslCryptoException(final MslError error) {
super(error);
}
/**
* Construct a new MSL crypto exception with the specified error and
* details.
*
* @param error the error.
* @param details the details text.
*/
public MslCryptoException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL crypto exception with the specified error, details,
* and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslCryptoException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL crypto exception with the specified error and cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslCryptoException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslCryptoException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslCryptoException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
}
| 1,663 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslEntityAuthException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
/**
* Thrown when an entity authentication exception occurs within the Message
* Security Layer.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslEntityAuthException extends MslException {
private static final long serialVersionUID = 5335550727677217303L;
/**
* Construct a new MSL entity authentication exception with the specified
* error.
*
* @param error the error.
*/
public MslEntityAuthException(final MslError error) {
super(error);
}
/**
* Construct a new MSL entity authentication exception with the specified
* error and details.
*
* @param error the error.
* @param details the details text.
*/
public MslEntityAuthException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL entity authentication exception with the specified
* error, details, and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslEntityAuthException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL entity authentication exception with the specified
* error and cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslEntityAuthException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslEntityAuthException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslEntityAuthException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
}
| 1,664 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslUserAuthException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when a user authentication exception occurs within the Message
* Security Layer.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslUserAuthException extends MslException {
private static final long serialVersionUID = 3836512629362408424L;
/**
* Construct a new MSL user authentication exception with the specified
* error.
*
* @param error the error.
*/
public MslUserAuthException(final MslError error) {
super(error);
}
/**
* Construct a new MSL user authentication exception with the specified
* error and details.
*
* @param error the error.
* @param details the details text.
*/
public MslUserAuthException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL user authentication exception with the specified
* error, details, and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslUserAuthException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL user authentication exception with the specified
* error and cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslUserAuthException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslUserAuthException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserAuthenticationData(com.netflix.msl.userauth.UserAuthenticationData)
*/
@Override
public MslUserAuthException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
super.setUserAuthenticationData(userAuthData);
return this;
}
}
| 1,665 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslUserIdTokenException.java
|
/**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
/**
* Thrown when there is a problem with a user ID token, but the token was
* successfully parsed.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslUserIdTokenException extends MslException {
private static final long serialVersionUID = 8796880393236563071L;
/**
* Construct a new MSL user ID token exception with the specified error and
* user ID token.
*
* @param error the error.
* @param userIdToken the user ID token. May not be null.
*/
public MslUserIdTokenException(final MslError error, final UserIdToken userIdToken) {
super(error);
setUserIdToken(userIdToken);
}
/**
* Construct a new MSL user ID token exception with the specified error,
* user ID token, and details.
*
* @param error the error.
* @param userIdToken the user ID token. May not be null.
* @param details the details text.
*/
public MslUserIdTokenException(final MslError error, final UserIdToken userIdToken, final String details) {
super(error, details);
setUserIdToken(userIdToken);
}
/**
* Construct a new MSL user ID token exception with the specified error,
* user ID token, details, and cause.
*
* @param error the error.
* @param userIdToken the user ID token. May not be null.
* @param details the details text.
* @param cause the cause.
*/
public MslUserIdTokenException(final MslError error, final UserIdToken userIdToken, final String details, final Throwable cause) {
super(error, details, cause);
setUserIdToken(userIdToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslUserIdTokenException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslUserIdTokenException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMessageId(long)
*/
@Override
public MslUserIdTokenException setMessageId(final long messageId) {
super.setMessageId(messageId);
return this;
}
}
| 1,666 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslInternalException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
/**
* Thrown when an exception occurs that should not happen except due to an
* internal error (e.g. incorrectly written code).
*
* @author Wesley Miaw <[email protected]>
*/
public class MslInternalException extends RuntimeException {
private static final long serialVersionUID = 5787827728910061805L;
/**
* Construct a new MSL internal exception with the specified detail
* message and cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public MslInternalException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Construct a new MSL internal exception with the specified detail
* message.
*
* @param message the detail message.
*/
public MslInternalException(final String message) {
super(message);
}
}
| 1,667 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslError.java
|
/**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import java.util.HashSet;
import java.util.Set;
import com.netflix.msl.MslConstants.ResponseCode;
/**
* <p>Message Security Layer error codes and descriptions.</p>
*
* <p>Errors are defined with an internal and a response error code. The
* internal error code is specific to this implementation. The response error
* codes are sent in error messages to inform the remote entity, who should use
* it to decide on the correct error handling behavior.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslError {
/** Internal error code set. */
private static final Set<Integer> internalCodes = new HashSet<Integer>();
// 0 Message Security Layer
public static final MslError MSL_PARSE_ERROR = new MslError(0, ResponseCode.FAIL, "Error parsing MSL encodable.");
public static final MslError MSL_ENCODE_ERROR = new MslError(1, ResponseCode.FAIL, "Error encoding MSL encodable.");
public static final MslError ENVELOPE_HASH_MISMATCH = new MslError(2, ResponseCode.FAIL, "Computed hash does not match envelope hash.");
public static final MslError INVALID_PUBLIC_KEY = new MslError(3, ResponseCode.FAIL, "Invalid public key provided.");
public static final MslError INVALID_PRIVATE_KEY = new MslError(4, ResponseCode.FAIL, "Invalid private key provided.");
public static final MslError PLAINTEXT_ILLEGAL_BLOCK_SIZE = new MslError(5, ResponseCode.FAIL, "Plaintext is not a multiple of the block size.");
public static final MslError PLAINTEXT_BAD_PADDING = new MslError(6, ResponseCode.FAIL, "Plaintext contains incorrect padding.");
public static final MslError CIPHERTEXT_ILLEGAL_BLOCK_SIZE = new MslError(7, ResponseCode.FAIL, "Ciphertext is not a multiple of the block size.");
public static final MslError CIPHERTEXT_BAD_PADDING = new MslError(8, ResponseCode.FAIL, "Ciphertext contains incorrect padding.");
public static final MslError ENCRYPT_NOT_SUPPORTED = new MslError(9, ResponseCode.FAIL, "Encryption not supported.");
public static final MslError DECRYPT_NOT_SUPPORTED = new MslError(10, ResponseCode.FAIL, "Decryption not supported.");
public static final MslError ENVELOPE_KEY_ID_MISMATCH = new MslError(11, ResponseCode.FAIL, "Encryption envelope key ID does not match crypto context key ID.");
public static final MslError CIPHERTEXT_ENVELOPE_PARSE_ERROR = new MslError(12, ResponseCode.FAIL, "Error parsing ciphertext envelope.");
public static final MslError CIPHERTEXT_ENVELOPE_ENCODE_ERROR = new MslError(13, ResponseCode.FAIL, "Error encoding ciphertext envelope.");
public static final MslError SIGN_NOT_SUPPORTED = new MslError(14, ResponseCode.FAIL, "Sign not supported.");
public static final MslError VERIFY_NOT_SUPPORTED = new MslError(15, ResponseCode.FAIL, "Verify not suppoprted.");
public static final MslError SIGNATURE_ERROR = new MslError(16, ResponseCode.FAIL, "Signature not initialized or unable to process data/signature.");
public static final MslError HMAC_ERROR = new MslError(17, ResponseCode.FAIL, "Error computing HMAC.");
public static final MslError ENCRYPT_ERROR = new MslError(18, ResponseCode.FAIL, "Error encrypting plaintext.");
public static final MslError DECRYPT_ERROR = new MslError(19, ResponseCode.FAIL, "Error decrypting ciphertext.");
public static final MslError INSUFFICIENT_CIPHERTEXT = new MslError(20, ResponseCode.FAIL, "Insufficient ciphertext for decryption.");
public static final MslError SESSION_KEY_CREATION_FAILURE = new MslError(21, ResponseCode.FAIL, "Error when creating session keys.");
public static final MslError INVALID_SYMMETRIC_KEY = new MslError(24, ResponseCode.FAIL, "Invalid symmetric key.");
public static final MslError INVALID_ENCRYPTION_KEY = new MslError(25, ResponseCode.FAIL, "Invalid encryption key.");
public static final MslError INVALID_HMAC_KEY = new MslError(26, ResponseCode.FAIL, "Invalid HMAC key.");
public static final MslError WRAP_NOT_SUPPORTED = new MslError(27, ResponseCode.FAIL, "Wrap not supported.");
public static final MslError UNWRAP_NOT_SUPPORTED = new MslError(28, ResponseCode.FAIL, "Unwrap not supported.");
public static final MslError UNIDENTIFIED_JWK_TYPE = new MslError(29, ResponseCode.FAIL, "Unidentified JSON web key type.");
public static final MslError UNIDENTIFIED_JWK_USAGE = new MslError(30, ResponseCode.FAIL, "Unidentified JSON web key usage.");
public static final MslError UNIDENTIFIED_JWK_ALGORITHM = new MslError(31, ResponseCode.FAIL, "Unidentified JSON web key algorithm.");
public static final MslError WRAP_ERROR = new MslError(32, ResponseCode.FAIL, "Error wrapping plaintext.");
public static final MslError UNWRAP_ERROR = new MslError(33, ResponseCode.FAIL, "Error unwrapping ciphertext.");
public static final MslError INVALID_JWK = new MslError(34, ResponseCode.FAIL, "Invalid JSON web key.");
public static final MslError INVALID_JWK_KEYDATA = new MslError(35, ResponseCode.FAIL, "Invalid JSON web key keydata.");
public static final MslError UNSUPPORTED_JWK_ALGORITHM = new MslError(36, ResponseCode.FAIL, "Unsupported JSON web key algorithm.");
public static final MslError WRAP_KEY_CREATION_FAILURE = new MslError(37, ResponseCode.FAIL, "Error when creating wrapping key.");
public static final MslError INVALID_WRAP_CIPHERTEXT = new MslError(38, ResponseCode.FAIL, "Invalid wrap ciphertext.");
public static final MslError UNSUPPORTED_JWE_ALGORITHM = new MslError(39, ResponseCode.FAIL, "Unsupported JSON web encryption algorithm.");
public static final MslError JWE_ENCODE_ERROR = new MslError(40, ResponseCode.FAIL, "Error encoding JSON web encryption header.");
public static final MslError JWE_PARSE_ERROR = new MslError(41, ResponseCode.FAIL, "Error parsing JSON web encryption header.");
public static final MslError INVALID_ALGORITHM_PARAMS = new MslError(42, ResponseCode.FAIL, "Invalid algorithm parameters.");
public static final MslError JWE_ALGORITHM_MISMATCH = new MslError(43, ResponseCode.FAIL, "JSON web encryption header algorithms mismatch.");
public static final MslError KEY_IMPORT_ERROR = new MslError(44, ResponseCode.FAIL, "Error importing key.");
public static final MslError KEY_EXPORT_ERROR = new MslError(45, ResponseCode.FAIL, "Error exporting key.");
public static final MslError DIGEST_ERROR = new MslError(46, ResponseCode.FAIL, "Error in digest.");
public static final MslError UNSUPPORTED_KEY = new MslError(47, ResponseCode.FAIL, "Unsupported key type or algorithm.");
public static final MslError UNSUPPORTED_JWE_SERIALIZATION = new MslError(48, ResponseCode.FAIL, "Unsupported JSON web encryption serialization.");
public static final MslError INVALID_WRAPPING_KEY = new MslError(51, ResponseCode.FAIL, "Invalid wrapping key.");
public static final MslError UNIDENTIFIED_CIPHERTEXT_ENVELOPE = new MslError(52, ResponseCode.FAIL, "Unidentified ciphertext envelope version.");
public static final MslError UNIDENTIFIED_SIGNATURE_ENVELOPE = new MslError(53, ResponseCode.FAIL, "Unidentified signature envelope version.");
public static final MslError UNSUPPORTED_CIPHERTEXT_ENVELOPE = new MslError(54, ResponseCode.FAIL, "Unsupported ciphertext envelope version.");
public static final MslError UNSUPPORTED_SIGNATURE_ENVELOPE = new MslError(55, ResponseCode.FAIL, "Unsupported signature envelope version.");
public static final MslError UNIDENTIFIED_CIPHERSPEC = new MslError(56, ResponseCode.FAIL, "Unidentified cipher specification.");
public static final MslError UNIDENTIFIED_ALGORITHM = new MslError(57, ResponseCode.FAIL, "Unidentified algorithm.");
public static final MslError SIGNATURE_ENVELOPE_PARSE_ERROR = new MslError(58, ResponseCode.FAIL, "Error parsing signature envelope.");
public static final MslError SIGNATURE_ENVELOPE_ENCODE_ERROR = new MslError(59, ResponseCode.FAIL, "Error encoding signature envelope.");
public static final MslError INVALID_SIGNATURE = new MslError(60, ResponseCode.FAIL, "Invalid signature.");
public static final MslError DERIVEKEY_ERROR = new MslError(61, ResponseCode.FAIL, "Error deriving key.");
public static final MslError UNIDENTIFIED_JWK_KEYOP = new MslError(62, ResponseCode.FAIL, "Unidentified JSON web key key operation.");
public static final MslError GENERATEKEY_ERROR = new MslError(63, ResponseCode.FAIL, "Error generating key.");
public static final MslError INVALID_IV = new MslError(64, ResponseCode.FAIL, "Invalid initialization vector.");
public static final MslError INVALID_CIPHERTEXT = new MslError(65, ResponseCode.FAIL, "Invalid ciphertext.");
// 1 Master Token
public static final MslError MASTERTOKEN_UNTRUSTED = new MslError(1000, ResponseCode.ENTITY_REAUTH, "Master token is not trusted.");
public static final MslError MASTERTOKEN_KEY_CREATION_ERROR = new MslError(1001, ResponseCode.ENTITY_REAUTH, "Unable to construct symmetric keys from master token.");
public static final MslError MASTERTOKEN_EXPIRES_BEFORE_RENEWAL = new MslError(1002, ResponseCode.ENTITY_REAUTH, "Master token expiration timestamp is before the renewal window opens.");
public static final MslError MASTERTOKEN_SESSIONDATA_MISSING = new MslError(1003, ResponseCode.ENTITY_REAUTH, "No master token session data found.");
public static final MslError MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_RANGE = new MslError(1004, ResponseCode.ENTITY_REAUTH, "Master token sequence number is out of range.");
public static final MslError MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(1005, ResponseCode.ENTITY_REAUTH, "Master token serial number is out of range.");
public static final MslError MASTERTOKEN_TOKENDATA_INVALID = new MslError(1006, ResponseCode.ENTITY_REAUTH, "Invalid master token data.");
public static final MslError MASTERTOKEN_SIGNATURE_INVALID = new MslError(1007, ResponseCode.ENTITY_REAUTH, "Invalid master token signature.");
public static final MslError MASTERTOKEN_SESSIONDATA_INVALID = new MslError(1008, ResponseCode.ENTITY_REAUTH, "Invalid master token session data.");
public static final MslError MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC = new MslError(1009, ResponseCode.ENTITY_REAUTH, "Master token sequence number does not have the expected value.");
public static final MslError MASTERTOKEN_TOKENDATA_MISSING = new MslError(1010, ResponseCode.ENTITY_REAUTH, "No master token data found.");
public static final MslError MASTERTOKEN_TOKENDATA_PARSE_ERROR = new MslError(1011, ResponseCode.ENTITY_REAUTH, "Error parsing master token data.");
public static final MslError MASTERTOKEN_SESSIONDATA_PARSE_ERROR = new MslError(1012, ResponseCode.ENTITY_REAUTH, "Error parsing master token session data.");
public static final MslError MASTERTOKEN_IDENTITY_REVOKED = new MslError(1013, ResponseCode.ENTITY_REAUTH, "Master token entity identity is revoked.");
public static final MslError MASTERTOKEN_REJECTED_BY_APP = new MslError(1014, ResponseCode.ENTITY_REAUTH, "Master token is rejected by the application.");
public static final MslError MASTERTOKEN_ISSUERDATA_ENCODE_ERROR = new MslError(1015, ResponseCode.FAIL, "Master token issuer data encoding error.");
// 2 User ID Token
public static final MslError USERIDTOKEN_MASTERTOKEN_MISMATCH = new MslError(2000, ResponseCode.USER_REAUTH, "User ID token master token serial number does not match master token serial number.");
public static final MslError USERIDTOKEN_NOT_DECRYPTED = new MslError(2001, ResponseCode.USER_REAUTH, "User ID token is not decrypted or verified.");
public static final MslError USERIDTOKEN_MASTERTOKEN_NULL = new MslError(2002, ResponseCode.USER_REAUTH, "User ID token requires a master token.");
public static final MslError USERIDTOKEN_EXPIRES_BEFORE_RENEWAL = new MslError(2003, ResponseCode.USER_REAUTH, "User ID token expiration timestamp is before the renewal window opens.");
public static final MslError USERIDTOKEN_USERDATA_MISSING = new MslError(2004, ResponseCode.USER_REAUTH, "No user ID token user data found.");
public static final MslError USERIDTOKEN_MASTERTOKEN_NOT_FOUND = new MslError(2005, ResponseCode.USER_REAUTH, "User ID token is bound to an unknown master token.");
public static final MslError USERIDTOKEN_MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(2006, ResponseCode.USER_REAUTH, "User ID token master token serial number is out of range.");
public static final MslError USERIDTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(2007, ResponseCode.USER_REAUTH, "User ID token serial number is out of range.");
public static final MslError USERIDTOKEN_TOKENDATA_INVALID = new MslError(2008, ResponseCode.USER_REAUTH, "Invalid user ID token data.");
public static final MslError USERIDTOKEN_SIGNATURE_INVALID = new MslError(2009, ResponseCode.USER_REAUTH, "Invalid user ID token signature.");
public static final MslError USERIDTOKEN_USERDATA_INVALID = new MslError(2010, ResponseCode.USER_REAUTH, "Invalid user ID token user data.");
public static final MslError USERIDTOKEN_IDENTITY_INVALID = new MslError(2011, ResponseCode.USER_REAUTH, "Invalid user ID token user identity.");
public static final MslError RESERVED_2012 = new MslError(2012, ResponseCode.USER_REAUTH, "The entity is not associated with the user.");
public static final MslError USERIDTOKEN_USERAUTH_DATA_MISMATCH = new MslError(2015, ResponseCode.USER_REAUTH, "The user ID token and user authentication data user identities do not match.");
public static final MslError USERIDTOKEN_TOKENDATA_MISSING = new MslError(2016, ResponseCode.USER_REAUTH, "No user ID token data found.");
public static final MslError USERIDTOKEN_TOKENDATA_PARSE_ERROR = new MslError(2017, ResponseCode.USER_REAUTH, "Error parsing user ID token data.");
public static final MslError USERIDTOKEN_USERDATA_PARSE_ERROR = new MslError(2018, ResponseCode.USER_REAUTH, "Error parsing user ID token user data.");
public static final MslError USERIDTOKEN_REVOKED = new MslError(2019, ResponseCode.USER_REAUTH, "User ID token is revoked.");
public static final MslError USERIDTOKEN_REJECTED_BY_APP = new MslError(2020, ResponseCode.USERDATA_REAUTH, "User ID token is rejected by the application.");
// 3 Service Token
public static final MslError SERVICETOKEN_MASTERTOKEN_MISMATCH = new MslError(3000, ResponseCode.FAIL, "Service token master token serial number does not match master token serial number.");
public static final MslError SERVICETOKEN_USERIDTOKEN_MISMATCH = new MslError(3001, ResponseCode.FAIL, "Service token user ID token serial number does not match user ID token serial number.");
public static final MslError SERVICETOKEN_SERVICEDATA_INVALID = new MslError(3002, ResponseCode.FAIL, "Service token data invalid.");
public static final MslError SERVICETOKEN_MASTERTOKEN_NOT_FOUND = new MslError(3003, ResponseCode.FAIL, "Service token is bound to an unknown master token.");
public static final MslError SERVICETOKEN_USERIDTOKEN_NOT_FOUND = new MslError(3004, ResponseCode.FAIL, "Service token is bound to an unknown user ID token.");
public static final MslError SERVICETOKEN_MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(3005, ResponseCode.FAIL, "Service token master token serial number is out of range.");
public static final MslError SERVICETOKEN_USERIDTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(3006, ResponseCode.FAIL, "Service token user ID token serial number is out of range.");
public static final MslError SERVICETOKEN_TOKENDATA_INVALID = new MslError(3007, ResponseCode.FAIL, "Invalid service token data.");
public static final MslError SERVICETOKEN_SIGNATURE_INVALID = new MslError(3008, ResponseCode.FAIL, "Invalid service token signature.");
public static final MslError SERVICETOKEN_TOKENDATA_MISSING = new MslError(3009, ResponseCode.FAIL, "No service token data found.");
// 4 Entity Authentication
public static final MslError UNIDENTIFIED_ENTITYAUTH_SCHEME = new MslError(4000, ResponseCode.FAIL, "Unable to identify entity authentication scheme.");
public static final MslError ENTITYAUTH_FACTORY_NOT_FOUND = new MslError(4001, ResponseCode.FAIL, "No factory registered for entity authentication scheme.");
public static final MslError X509CERT_PARSE_ERROR = new MslError(4002, ResponseCode.ENTITYDATA_REAUTH, "Error parsing X.509 certificate data.");
public static final MslError X509CERT_ENCODE_ERROR = new MslError(4003, ResponseCode.ENTITYDATA_REAUTH, "Error encoding X.509 certificate data.");
public static final MslError X509CERT_VERIFICATION_FAILED = new MslError(4004, ResponseCode.ENTITYDATA_REAUTH, "X.509 certificate verification failed.");
public static final MslError ENTITY_NOT_FOUND = new MslError(4005, ResponseCode.FAIL, "Entity not recognized.");
public static final MslError INCORRECT_ENTITYAUTH_DATA = new MslError(4006, ResponseCode.FAIL, "Entity used incorrect entity authentication data type.");
public static final MslError RSA_PUBLICKEY_NOT_FOUND = new MslError(4007, ResponseCode.ENTITYDATA_REAUTH, "RSA public key not found.");
public static final MslError UNSUPPORTED_ENTITYAUTH_DATA = new MslError(4023, ResponseCode.FAIL, "Unsupported entity authentication data.");
public static final MslError ENTITY_REVOKED = new MslError(4025, ResponseCode.FAIL, "Entity is revoked.");
public static final MslError ENTITY_REJECTED_BY_APP = new MslError(4026, ResponseCode.ENTITYDATA_REAUTH, "Entity is rejected by the application.");
public static final MslError X509CERT_EXPIRED = new MslError(4028, ResponseCode.ENTITYDATA_REAUTH, "X.509 certificate is expired.");
public static final MslError X509CERT_NOT_YET_VALID = new MslError(4029, ResponseCode.ENTITYDATA_REAUTH, "X.509 certificate is not yet valid.");
public static final MslError X509CERT_INVALID = new MslError(4030, ResponseCode.ENTITYDATA_REAUTH, "X.509 certificate is invalid.");
public static final MslError RSA_PRIVATEKEY_NOT_FOUND = new MslError(4031, ResponseCode.ENTITYDATA_REAUTH, "RSA private key not found.");
public static final MslError ENTITYAUTH_MASTERTOKEN_NOT_DECRYPTED = new MslError(4032, ResponseCode.FAIL, "Entity authentication data master token is not decrypted or verified.");
public static final MslError ENTITYAUTH_SIGNATURE_INVALID = new MslError(4033, ResponseCode.ENTITYDATA_REAUTH, "Invalid entity authentication data siganture.");
public static final MslError ENTITYAUTH_CIPHERTEXT_INVALID = new MslError(4034, ResponseCode.ENTITYDATA_REAUTH, "Invalid entity authentication data ciphertext.");
public static final MslError ENTITYAUTH_VERIFICATION_FAILED = new MslError(4035, ResponseCode.ENTITYDATA_REAUTH, "Entity authentication data signature verification failed.");
public static final MslError ENTITYAUTH_MASTERTOKEN_INVALID = new MslError(4036, ResponseCode.FAIL, "Invalid entity authentication data master token.");
public static final MslError ECC_PUBLICKEY_NOT_FOUND = new MslError(4037, ResponseCode.ENTITYDATA_REAUTH, "ECC public key not found.");
public static final MslError ECC_PRIVATEKEY_NOT_FOUND = new MslError(4038, ResponseCode.ENTITYDATA_REAUTH, "ECC private key not found.");
// 5 User Authentication
public static final MslError UNIDENTIFIED_USERAUTH_SCHEME = new MslError(5003, ResponseCode.FAIL, "Unable to identify user authentication scheme.");
public static final MslError USERAUTH_FACTORY_NOT_FOUND = new MslError(5004, ResponseCode.FAIL, "No factory registered for user authentication scheme.");
public static final MslError EMAILPASSWORD_BLANK = new MslError(5005, ResponseCode.USERDATA_REAUTH, "Email or password is blank.");
public static final MslError EMAILPASSWORD_INCORRECT = new MslError(5007, ResponseCode.USERDATA_REAUTH, "Email or password is incorrect.");
public static final MslError UNSUPPORTED_USERAUTH_DATA = new MslError(5008, ResponseCode.FAIL, "Unsupported user authentication data.");
public static final MslError USERAUTH_USERIDTOKEN_INVALID = new MslError(5011, ResponseCode.USERDATA_REAUTH, "User authentication data user ID token is invalid.");
public static final MslError UNIDENTIFIED_USERAUTH_MECHANISM = new MslError(5013, ResponseCode.FAIL, "Unable to identify user authentication mechanism.");
public static final MslError UNSUPPORTED_USERAUTH_MECHANISM = new MslError(5014, ResponseCode.FAIL, "Unsupported user authentication mechanism.");
public static final MslError USERAUTH_MASTERTOKEN_MISSING = new MslError(5016, ResponseCode.USERDATA_REAUTH, "User authentication required master token is missing.");
public static final MslError USERAUTH_USERIDTOKEN_NOT_DECRYPTED = new MslError(5021, ResponseCode.USERDATA_REAUTH, "User authentication data user ID token is not decrypted or verified.");
public static final MslError USERAUTH_MASTERTOKEN_INVALID = new MslError(5024, ResponseCode.USERDATA_REAUTH, "User authentication data master token is invalid.");
public static final MslError USERAUTH_MASTERTOKEN_NOT_DECRYPTED = new MslError(5025, ResponseCode.USERDATA_REAUTH, "User authentication data master token is not decrypted or verified.");
public static final MslError USERAUTH_USERIDTOKEN_MISSING = new MslError(5030, ResponseCode.USERDATA_REAUTH, "User authentication required user ID token is missing.");
public static final MslError USERAUTH_ENTITY_MISMATCH = new MslError(5032, ResponseCode.USERDATA_REAUTH, "User authentication data does not match entity identity.");
public static final MslError USERAUTH_ENTITY_INCORRECT_DATA = new MslError(5033, ResponseCode.FAIL, "Entity used incorrect user authentication data type.");
public static final MslError USER_REJECTED_BY_APP = new MslError(5037, ResponseCode.USERDATA_REAUTH, "User is rejected by the application.");
public static final MslError USERIDTOKEN_IDENTITY_NOT_ASSOCIATED_WITH_ENTITY = new MslError(5040, ResponseCode.USERDATA_REAUTH, "The entity is not associated with the user.");
public static final MslError USERAUTH_ENTITYUSER_INCORRECT_DATA = new MslError(5041, ResponseCode.USERDATA_REAUTH, "Entity and user combination used incorrect user authentication data type.");
public static final MslError USERAUTH_VERIFICATION_FAILED = new MslError(5042, ResponseCode.USERDATA_REAUTH, "User authentication data signature verification failed.");
public static final MslError USERAUTH_USERIDTOKEN_REVOKE_CHECK_ERROR = new MslError(5043, ResponseCode.USERDATA_REAUTH, "User ID token could not be checked for revocation.");
// 6 Message
public static final MslError UNSUPPORTED_COMPRESSION = new MslError(6000, ResponseCode.FAIL, "Unsupported compression algorithm.");
public static final MslError COMPRESSION_ERROR = new MslError(6001, ResponseCode.FAIL, "Error compressing data.");
public static final MslError UNCOMPRESSION_ERROR = new MslError(6002, ResponseCode.FAIL, "Error uncompressing data.");
public static final MslError MESSAGE_ENTITY_NOT_FOUND = new MslError(6003, ResponseCode.FAIL, "Message header entity authentication data or master token not found.");
public static final MslError PAYLOAD_MESSAGE_ID_MISMATCH = new MslError(6004, ResponseCode.FAIL, "Payload chunk message ID does not match header message ID .");
public static final MslError PAYLOAD_SEQUENCE_NUMBER_MISMATCH = new MslError(6005, ResponseCode.FAIL, "Payload chunk sequence number does not match expected sequence number.");
public static final MslError PAYLOAD_VERIFICATION_FAILED = new MslError(6006, ResponseCode.FAIL, "Payload chunk payload signature verification failed.");
public static final MslError MESSAGE_DATA_MISSING = new MslError(6007, ResponseCode.FAIL, "No message data found.");
public static final MslError MESSAGE_FORMAT_ERROR = new MslError(6008, ResponseCode.FAIL, "Malformed message data.");
public static final MslError MESSAGE_VERIFICATION_FAILED = new MslError(6009, ResponseCode.FAIL, "Message header/error data signature verification failed.");
public static final MslError HEADER_DATA_MISSING = new MslError(6010, ResponseCode.FAIL, "No header data found.");
public static final MslError PAYLOAD_DATA_MISSING = new MslError(6011, ResponseCode.FAIL, "No payload data found in non-EOM payload chunk.");
public static final MslError PAYLOAD_DATA_CORRUPT = new MslError(6012, ResponseCode.FAIL, "Corrupt payload data found in non-EOM payload chunk.");
public static final MslError UNIDENTIFIED_COMPRESSION = new MslError(6013, ResponseCode.FAIL, "Unidentified compression algorithm.");
public static final MslError MESSAGE_EXPIRED = new MslError(6014, ResponseCode.EXPIRED, "Message expired and not renewable or missing key request data. Rejected.");
public static final MslError MESSAGE_ID_OUT_OF_RANGE = new MslError(6015, ResponseCode.FAIL, "Message ID is is out of range.");
public static final MslError INTERNAL_CODE_NEGATIVE = new MslError(6016, ResponseCode.FAIL, "Error header internal code is negative.");
public static final MslError UNEXPECTED_RESPONSE_MESSAGE_ID = new MslError(6017, ResponseCode.FAIL, "Unexpected response message ID. Possible replay.");
public static final MslError RESPONSE_REQUIRES_ENCRYPTION = new MslError(6018, ResponseCode.KEYX_REQUIRED, "Message response requires encryption.");
public static final MslError PAYLOAD_SEQUENCE_NUMBER_OUT_OF_RANGE = new MslError(6019, ResponseCode.FAIL, "Payload chunk sequence number is out of range.");
public static final MslError PAYLOAD_MESSAGE_ID_OUT_OF_RANGE = new MslError(6020, ResponseCode.FAIL, "Payload chunk message ID is out of range.");
public static final MslError MESSAGE_REPLAYED = new MslError(6021, ResponseCode.REPLAYED, "Non-replayable message replayed.");
public static final MslError INCOMPLETE_NONREPLAYABLE_MESSAGE = new MslError(6022, ResponseCode.FAIL, "Non-replayable message sent without a master token.");
public static final MslError HEADER_SIGNATURE_INVALID = new MslError(6023, ResponseCode.FAIL, "Invalid Header signature.");
public static final MslError HEADER_DATA_INVALID = new MslError(6024, ResponseCode.FAIL, "Invalid header data.");
public static final MslError PAYLOAD_INVALID = new MslError(6025, ResponseCode.FAIL, "Invalid payload.");
public static final MslError PAYLOAD_SIGNATURE_INVALID = new MslError(6026, ResponseCode.FAIL, "Invalid payload signature.");
public static final MslError RESPONSE_REQUIRES_MASTERTOKEN = new MslError(6027, ResponseCode.KEYX_REQUIRED, "Message response requires a master token.");
public static final MslError RESPONSE_REQUIRES_USERIDTOKEN = new MslError(6028, ResponseCode.USER_REAUTH, "Message response requires a user ID token.");
public static final MslError REQUEST_REQUIRES_USERAUTHDATA = new MslError(6029, ResponseCode.FAIL, "User-associated message requires user authentication data.");
public static final MslError UNEXPECTED_MESSAGE_SENDER = new MslError(6030, ResponseCode.FAIL, "Message sender is not the master token entity.");
public static final MslError NONREPLAYABLE_MESSAGE_REQUIRES_MASTERTOKEN = new MslError(6031, ResponseCode.FAIL, "Non-replayable message requires a master token.");
public static final MslError NONREPLAYABLE_ID_OUT_OF_RANGE = new MslError(6032, ResponseCode.FAIL, "Non-replayable message non-replayable ID is out of range.");
public static final MslError MESSAGE_SERVICETOKEN_MISMATCH = new MslError(6033, ResponseCode.FAIL, "Service token master token or user ID token serial number does not match the message token serial numbers.");
public static final MslError MESSAGE_PEER_SERVICETOKEN_MISMATCH = new MslError(6034, ResponseCode.FAIL, "Peer service token master token or user ID token serial number does not match the message peer token serial numbers.");
public static final MslError RESPONSE_REQUIRES_INTEGRITY_PROTECTION = new MslError(6035, ResponseCode.KEYX_REQUIRED, "Message response requires integrity protection.");
public static final MslError HANDSHAKE_DATA_MISSING = new MslError(6036, ResponseCode.FAIL, "Handshake message is not renewable or does not contain key request data.");
public static final MslError MESSAGE_RECIPIENT_MISMATCH = new MslError(6037, ResponseCode.FAIL, "Message recipient does not match local identity.");
public static final MslError MESSAGE_ENTITYDATABASED_VERIFICATION_FAILED = new MslError(6038, ResponseCode.ENTITYDATA_REAUTH, "Message header entity-based signature verification failed.");
public static final MslError MESSAGE_MASTERTOKENBASED_VERIFICATION_FAILED = new MslError(6039, ResponseCode.ENTITY_REAUTH, "Message header master token-based signature verification failed.");
public static final MslError MESSAGE_REPLAYED_UNRECOVERABLE = new MslError(6040, ResponseCode.ENTITY_REAUTH, "Non-replayable message replayed with a sequence number that is too far out of sync to recover.");
public static final MslError UNEXPECTED_LOCAL_MESSAGE_SENDER = new MslError(6041, ResponseCode.FAIL, "Message sender is equal to the local entity.");
public static final MslError UNENCRYPTED_MESSAGE_WITH_USERAUTHDATA = new MslError(6042, ResponseCode.FAIL, "User authentication data included in unencrypted message header.");
public static final MslError MESSAGE_SENDER_MISMATCH = new MslError(6043, ResponseCode.FAIL, "Message sender entity identity does not match expected identity.");
public static final MslError MESSAGE_EXPIRED_NOT_RENEWABLE = new MslError(6044, ResponseCode.EXPIRED, "Message expired and not renewable. Rejected.");
public static final MslError MESSAGE_EXPIRED_NO_KEYREQUEST_DATA = new MslError(6045, ResponseCode.EXPIRED, "Message expired and missing key request data. Rejected.");
// 7 Key Exchange
public static final MslError UNIDENTIFIED_KEYX_SCHEME = new MslError(7000, ResponseCode.FAIL, "Unable to identify key exchange scheme.");
public static final MslError KEYX_FACTORY_NOT_FOUND = new MslError(7001, ResponseCode.FAIL, "No factory registered for key exchange scheme.");
public static final MslError KEYX_REQUEST_NOT_FOUND = new MslError(7002, ResponseCode.FAIL, "No key request found matching header key response data.");
public static final MslError UNIDENTIFIED_KEYX_KEY_ID = new MslError(7003, ResponseCode.FAIL, "Unable to identify key exchange key ID.");
public static final MslError UNSUPPORTED_KEYX_KEY_ID = new MslError(7004, ResponseCode.FAIL, "Unsupported key exchange key ID.");
public static final MslError UNIDENTIFIED_KEYX_MECHANISM = new MslError(7005, ResponseCode.FAIL, "Unable to identify key exchange mechanism.");
public static final MslError UNSUPPORTED_KEYX_MECHANISM = new MslError(7006, ResponseCode.FAIL, "Unsupported key exchange mechanism.");
public static final MslError KEYX_RESPONSE_REQUEST_MISMATCH = new MslError(7007, ResponseCode.FAIL, "Key exchange response does not match request.");
public static final MslError KEYX_PRIVATE_KEY_MISSING = new MslError(7008, ResponseCode.FAIL, "Key exchange private key missing.");
public static final MslError UNKNOWN_KEYX_PARAMETERS_ID = new MslError(7009, ResponseCode.FAIL, "Key exchange parameters ID unknown or invalid.");
public static final MslError KEYX_MASTER_TOKEN_MISSING = new MslError(7010, ResponseCode.FAIL, "Master token required for key exchange is missing.");
public static final MslError KEYX_INVALID_PUBLIC_KEY = new MslError(7011, ResponseCode.FAIL, "Key exchange public key is invalid.");
public static final MslError KEYX_PUBLIC_KEY_MISSING = new MslError(7012, ResponseCode.FAIL, "Key exchange public key missing.");
public static final MslError KEYX_WRAPPING_KEY_MISSING = new MslError(7013, ResponseCode.FAIL, "Key exchange wrapping key missing.");
public static final MslError KEYX_WRAPPING_KEY_ID_MISSING = new MslError(7014, ResponseCode.FAIL, "Key exchange wrapping key ID missing.");
public static final MslError KEYX_INVALID_WRAPPING_KEY = new MslError(7015, ResponseCode.FAIL, "Key exchange wrapping key is invalid.");
public static final MslError KEYX_INCORRECT_DATA = new MslError(7016, ResponseCode.FAIL, "Entity used incorrect key exchange data type.");
public static final MslError KEYX_INCORRECT_MECHANISM = new MslError(7017, ResponseCode.FAIL, "Entity used incorrect key exchange mecahnism.");
public static final MslError KEYX_DERIVATION_KEY_MISSING = new MslError(7018, ResponseCode.FAIL, "Key exchange derivation key missing.");
public static final MslError KEYX_INVALID_ENCRYPTION_KEY = new MslError(7019, ResponseCode.FAIL, "Key exchange encryption key is invalid.");
public static final MslError KEYX_INVALID_HMAC_KEY = new MslError(7020, ResponseCode.FAIL, "Key exchange HMAC key is invalid.");
public static final MslError KEYX_INVALID_WRAPDATA = new MslError(7021, ResponseCode.FAIL, "Key exchange wrap data is invalid.");
public static final MslError UNSUPPORTED_KEYX_SCHEME = new MslError(7022, ResponseCode.FAIL, "Unsupported key exchange scheme.");
public static final MslError KEYX_IDENTITY_NOT_FOUND = new MslError(7023, ResponseCode.FAIL, "Key exchange identity not found.");
// 9 Internal Errors
public static final MslError INTERNAL_EXCEPTION = new MslError(9000, ResponseCode.TRANSIENT_FAILURE, "Internal exception.");
public static final MslError MSL_COMMS_FAILURE = new MslError(9001, ResponseCode.FAIL, "Error communicating with MSL entity.");
public static final MslError NONE = new MslError(9999, ResponseCode.FAIL, "Special unit test error.");
/** Internal error code base value. */
private static final int BASE = 100000;
/**
* Construct a MSL error with the specified internal and response error
* codes and message.
*
* @param internalCode internal error code.
* @param responseCode response error code.
* @param msg developer-consumable error message.
*/
protected MslError(final int internalCode, final ResponseCode responseCode, final String msg) {
// Check for duplicates.
synchronized (internalCodes) {
if (internalCodes.contains(internalCode))
throw new MslInternalException("Duplicate MSL error definition for error code " + internalCode + ".");
internalCodes.add(internalCode);
}
this.internalCode = MslError.BASE + internalCode;
this.responseCode = responseCode;
this.msg = msg;
}
/**
* @return the internal error code.
*/
public int getInternalCode() {
return internalCode;
}
/**
* @return the response error code.
*/
public ResponseCode getResponseCode() {
return responseCode;
}
/**
* @return the error message.
*/
public String getMessage() {
return msg;
}
/**
* @param o the reference object with which to compare.
* @return true if the internal code and response code are equal.
* @see #hashCode()
*/
@Override
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof MslError)) return false;
final MslError that = (MslError)o;
return this.internalCode == that.internalCode &&
this.responseCode == that.responseCode;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Integer.valueOf(internalCode).hashCode() ^ responseCode.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MslError{" + internalCode + "," + responseCode.intValue() + "," + msg + "}";
}
/** Internal error code. */
private final int internalCode;
/** Response error code. */
private final ResponseCode responseCode;
/** Error message. */
private final String msg;
}
| 1,668 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslErrorResponseException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
/**
* <p>Thrown when an exception occurs while attempting to create and send an
* automatically generated error response.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslErrorResponseException extends Exception {
private static final long serialVersionUID = 3844789699705189994L;
/**
* <p>Construct a new MSL error response exception with the specified detail
* message, cause, and the original exception thrown by the request that
* prompted an automatic error response.</p>
*
* <p>The detail message should describe the error that triggered the
* automatically generated error response.</p>
*
* @param message the detail message.
* @param cause the cause.
* @param requestCause the original request exception.
*/
public MslErrorResponseException(final String message, final Throwable cause, final Throwable requestCause) {
super(message, cause);
this.requestCause = requestCause;
}
/**
* @return the exception thrown by the request that prompted the error
* response.
*/
public Throwable getRequestCause() {
return requestCause;
}
/** The original exception thrown by the request. */
private final Throwable requestCause;
}
| 1,669 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslConstants.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import java.nio.charset.Charset;
import java.util.Set;
/**
* Message security layer constants.
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class MslConstants {
/** RFC-4627 defines UTF-8 as the default encoding. */
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
/** Maximum long integer value (2^53 limited by JavaScript). */
public static final long MAX_LONG_VALUE = 9007199254740992L;
/**
* The maximum number of MSL messages (requests sent or responses received)
* to allow before giving up. Six exchanges, or twelve total messages,
* should be sufficient to capture all possible error recovery and
* handshake requirements in both trusted network and peer-to-peer modes.
*/
public static final int MAX_MESSAGES = 12;
/** Compression algorithm. */
public static enum CompressionAlgorithm {
// In order of most preferred to least preferred.
/** GZIP */
GZIP,
/** LZW */
LZW;
/**
* Returns the most preferred compression algorithm from the provided
* set of algorithms.
*
* @param algos the set of algorithms to choose from.
* @return the most preferred compression algorithm or {@code null} if
* the algorithm set is empty.
*/
public static CompressionAlgorithm getPreferredAlgorithm(final Set<CompressionAlgorithm> algos) {
// Enum.values() returns the values in declaration order which will
// be the preferred order as promised above.
final CompressionAlgorithm preferredAlgos[] = CompressionAlgorithm.values();
for (int i = 0; i < preferredAlgos.length && algos.size() > 0; ++i) {
final CompressionAlgorithm preferredAlgo = preferredAlgos[i];
if (algos.contains(preferredAlgo))
return preferredAlgo;
}
return null;
}
}
/** Encryption algorithms. */
public static enum EncryptionAlgo {
/** AES */
AES,
;
/**
* @param value the string value of the encryption algorithm.
* @return the encryption algorithm associated with the string value.
* @throws IllegalArgumentException if the value is unknown.
*/
public static EncryptionAlgo fromString(final String value) {
return EncryptionAlgo.valueOf(EncryptionAlgo.class, value);
}
/**
* Returns the string value of this encryption algorithm. This will be
* equal to the Java standard algorithm name and is suitable for use
* with the JCE interfaces.
*
* @return the Java standard algorithm name for this encryption
* algorithm.
*/
@Override
public String toString() {
return name();
}
}
/** Cipher specifications. */
public static enum CipherSpec {
/** AES/CBC/PKCS5Padding */
AES_CBC_PKCS5Padding,
/** AESWrap */
AESWrap,
/** RSA/ECB/PKCS1Padding */
RSA_ECB_PKCS1Padding,
;
/** AES/CBC/PKCS5Padding string value. */
private static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";
/** RSA/ECB/PCKS1Padding string value. */
private static final String RSA_ECB_PKCS1PADDING = "RSA/ECB/PKCS1Padding";
/**
* @param value the string value of the cipher specification.
* @return the cipher specification associated with the string value.
* @throws IllegalArgumentException if the value is unknown.
*/
public static CipherSpec fromString(final String value) {
if (AES_CBC_PKCS5PADDING.equals(value))
return AES_CBC_PKCS5Padding;
if (RSA_ECB_PKCS1PADDING.equals(value))
return RSA_ECB_PKCS1Padding;
return CipherSpec.valueOf(CipherSpec.class, value);
}
/**
* Returns the string value of this cipher specification. This will be
* equal to the Java standard algorithm name and is suitable for use
* with the JCE interfaces.
*
* @return the Java standard algortihm name for this cipher
* specification.
*/
@Override
public String toString() {
switch (this) {
case AES_CBC_PKCS5Padding:
return AES_CBC_PKCS5PADDING;
case RSA_ECB_PKCS1Padding:
return RSA_ECB_PKCS1PADDING;
default:
return name();
}
}
}
/** Signature algorithms. */
public static enum SignatureAlgo {
/** HmacSHA256 */
HmacSHA256,
/** SHA256withRSA */
SHA256withRSA,
/** AESCmac. */
AESCmac,
;
/**
* @param value the string value of the signature algorithm.
* @return the signature algorithm associated with the string value.
* @throws IllegalArgumentException if the value is unknown.
*/
public static SignatureAlgo fromString(final String value) {
return SignatureAlgo.valueOf(SignatureAlgo.class, value);
}
/**
* Returns the string value of this signature algorithm. This will be
* equal to the Java standard algorithm name and is suitable for use
* with the JCE interfaces.
*
* @return the Java standard algortihm name for this signature
* algorithm.
*/
@Override
public String toString() {
return name();
}
}
/** Error response codes. */
public static enum ResponseCode {
/** The message is erroneous and will continue to fail if retried. */
FAIL(1),
/** The message is expected to succeed if retried after a delay. */
TRANSIENT_FAILURE(2),
/** The message is expected to succeed post entity re-authentication. */
ENTITY_REAUTH(3),
/** The message is expected to succeed post user re-authentication. */
USER_REAUTH(4),
/** The message is expected to succeed post key exchange. */
KEYX_REQUIRED(5),
/** The message is expected to succeed with new entity authentication data. */
ENTITYDATA_REAUTH(6),
/** The message is expected to succeed with new user authentication data. */
USERDATA_REAUTH(7),
/** The message is expected to succeed if retried with a renewed master token or renewable message. */
EXPIRED(8),
/** The non-replayable message is expected to succeed if retried with the newest master token. */
REPLAYED(9),
/** The message is expected to succeed with new user authentication data containing a valid single-sign-on token. */
SSOTOKEN_REJECTED(10),
;
/**
* @return the response code corresponding to the integer value.
* @throws IllegalArgumentException if the integer value does not map
* onto a response code.
*/
public static ResponseCode valueOf(final int code) {
for (final ResponseCode value : ResponseCode.values()) {
if (value.intValue() == code)
return value;
}
throw new IllegalArgumentException("Unknown response code value " + code + ".");
}
/**
* Create a new response code with the specified integer value.
*
* @param code the integer value for the response code.
*/
private ResponseCode(final int code) {
this.code = code;
}
/**
* @return the integer value of the response code.
*/
public int intValue() {
return code;
}
/** The response code value. */
private final int code;
}
}
| 1,670 |
0 |
Create_ds/msl/core/src/main/java/com/netflix
|
Create_ds/msl/core/src/main/java/com/netflix/msl/MslMasterTokenException.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when there is a problem with a master token, but the token was
* successfully parsed.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslMasterTokenException extends MslException {
private static final long serialVersionUID = -3151662441952286016L;
/**
* Construct a new MSL master token exception with the specified error and
* master token.
*
* @param error the error.
* @param masterToken the master token. May be null.
*/
public MslMasterTokenException(final MslError error, final MasterToken masterToken) {
super(error);
setMasterToken(masterToken);
}
/**
* Construct a new MSL master token exception with the specified error and
* master token.
*
* @param error the error.
* @param masterToken the master token. May be null.
* @param cause the exception that triggered this exception being thrown
*/
public MslMasterTokenException(final MslError error, final MasterToken masterToken, final Throwable cause) {
super(error, cause);
setMasterToken(masterToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslMasterTokenException setUserIdToken(final UserIdToken userIdToken) {
super.setUserIdToken(userIdToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserAuthenticationData(com.netflix.msl.userauth.UserAuthenticationData)
*/
@Override
public MslMasterTokenException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
super.setUserAuthenticationData(userAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMessageId(long)
*/
@Override
public MslMasterTokenException setMessageId(final long messageId) {
super.setMessageId(messageId);
return this;
}
}
| 1,671 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/NullCryptoContext.java
|
/**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
/**
* A crypto context where encryption/decryption are no-ops, signatures are
* empty, and verification always returns true.
*
* @author Wesley Miaw <[email protected]>
*/
public class NullCryptoContext extends ICryptoContext {
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return new byte[0];
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
return true;
}
}
| 1,672 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/CryptoCache.java
|
/**
* Copyright (c) 2013-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
/**
* <p>The crypto context cache provides a thread-local cache of cipher and
* signature objects.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class CryptoCache {
private static class ThreadLocalMap<T> extends ThreadLocal<Map<String, T>> {
@Override
protected Map<String, T> initialValue() {
return new HashMap<String, T>();
}
}
/** Cache of transforms onto ciphers. */
private static ThreadLocal<Map<String,Cipher>> cipherCache = new ThreadLocalMap<>();
/** Cache of algorithms onto signatures. */
private static ThreadLocal<Map<String,Signature>> signatureCache = new ThreadLocalMap<>();
/** Cache of algorithms onto message digests. */
private static ThreadLocal<Map<String,MessageDigest>> digestCache = new ThreadLocalMap<>();
/** Cache of algorithms onto MACs. */
private static ThreadLocal<Map<String,Mac>> macCache = new ThreadLocalMap<>();
/** Cache of algorithms onto key factories. */
private static ThreadLocal<Map<String,KeyFactory>> keyFactoryCache = new ThreadLocalMap<>();
/** Cache of algorithms onto key agreements. */
private static ThreadLocal<Map<String,KeyAgreement>> keyAgreementCache = new ThreadLocalMap<>();
/** Cache of algorithms onto key pair generators. */
private static ThreadLocal<Map<String,KeyPairGenerator>> keyPairGeneratorCache = new ThreadLocalMap<>();
/**
* Returns a {@code Cipher} object that implements the specified transform.
*
* @param transform encrypt/decrypt transform.
* @return the cipher instance.
* @throws NoSuchAlgorithmException if transformation is null, empty, in an
* invalid format, or if no Provider supports a CipherSpi
* implementation for the specified algorithm.
* @throws NoSuchPaddingException if transformation contains a padding
* scheme that is not available.
* @see #resetCipher(String)
*/
public static Cipher getCipher(final String transform) throws NoSuchAlgorithmException, NoSuchPaddingException {
final Map<String,Cipher> ciphers = cipherCache.get();
if (!ciphers.containsKey(transform)) {
final Cipher cipher = Cipher.getInstance(transform);
ciphers.put(transform, cipher);
}
return ciphers.get(transform);
}
/**
* Resets the {@code Cipher} object that implements the specified transform.
* This method must be called if the cipher throws an exception to ensure
* a clean cipher is returned from the next call to
* {@link #getCipher(String)}.
*
* @param transform encrypt/decrypt transform.
* @see #getCipher(String)
*/
public static void resetCipher(final String transform) {
final Map<String,Cipher> ciphers = cipherCache.get();
ciphers.remove(transform);
}
/**
* Returns a {@code Signature} object that implements the specified
* algorithm.
*
* @param algorithm the sign/verify algorithm.
* @return the signature instance.
* @throws NoSuchAlgorithmException if no Provider supports a Signature
* implementation for the specified algorithm.
*/
public static Signature getSignature(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,Signature> signatures = signatureCache.get();
if (!signatures.containsKey(algorithm)) {
final Signature signature = Signature.getInstance(algorithm);
signatures.put(algorithm, signature);
}
return signatures.get(algorithm);
}
/**
* Returns a {@code MessageDigest} object that implements the specified
* algorithm.
*
* @param algorithm the digest algorithm.
* @return the message digest instance.
* @throws NoSuchAlgorithmException if no Provider supports a MessageDigest
* implementation for the specified algorithm.
*/
public static MessageDigest getMessageDigest(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,MessageDigest> digests = digestCache.get();
if (!digests.containsKey(algorithm)) {
final MessageDigest digest = MessageDigest.getInstance(algorithm);
digests.put(algorithm, digest);
}
return digests.get(algorithm);
}
/**
* Returns a {@code Mac} object that implements the specified algorithm.
*
* @param algorithm the MAC algorithm.
* @return the MAC instance.
* @throws NoSuchAlgorithmException if no Provider supports a Mac
* implementation for the specified algorithm.
*/
public static Mac getMac(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,Mac> macs = macCache.get();
if (!macs.containsKey(algorithm)) {
final Mac mac = Mac.getInstance(algorithm);
macs.put(algorithm, mac);
}
return macs.get(algorithm);
}
/**
* Returns a {@code KeyFactory} object that implements the specified
* algorithm.
*
* @param algorithm the key factory algorithm.
* @return the key factory instance.
* @throws NoSuchAlgorithmException if no Provider supports a KeyFactory
* implementation for the specified algorithm.
*/
public static KeyFactory getKeyFactory(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,KeyFactory> factories = keyFactoryCache.get();
if (!factories.containsKey(algorithm)) {
final KeyFactory factory = KeyFactory.getInstance(algorithm);
factories.put(algorithm, factory);
}
return factories.get(algorithm);
}
/**
* Returns a {@code KeyAgreement} object that implements the specified
* algorithm.
*
* @param algorithm the key agreement algorithm.
* @return the key agreement instance.
* @throws NoSuchAlgorithmException if no Provider supports a KeyAgreement
* implementation for the specified algorithm.
*/
public static KeyAgreement getKeyAgreement(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,KeyAgreement> agreements = keyAgreementCache.get();
if (!agreements.containsKey(algorithm)) {
final KeyAgreement agreement = KeyAgreement.getInstance(algorithm);
agreements.put(algorithm, agreement);
}
return agreements.get(algorithm);
}
/**
* Returns a {@code KeyPairGenerator} object that implements the specified
* algorithm.
*
* @param algorithm the key pair generator algorithm.
* @return the key pair generator instance.
* @throws NoSuchAlgorithmException if no Provider supports a
* KeyPairGenerator implementation for the specified algorithm.
*/
public static KeyPairGenerator getKeyPairGenerator(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,KeyPairGenerator> generators = keyPairGeneratorCache.get();
if (!generators.containsKey(algorithm)) {
final KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm);
generators.put(algorithm, generator);
}
return generators.get(algorithm);
}
}
| 1,673 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/ClientMslCryptoContext.java
|
/**
* Copyright (c) 2013-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
/**
* This class should be used by trusted network clients for the primary crypto
* context used for master tokens and user ID tokens. It always fails to verify
* and its other operations are no-ops.
*
* @author Wesley Miaw <[email protected]>
* @see com.netflix.msl.util.MslContext#getMslCryptoContext()
*/
public class ClientMslCryptoContext extends ICryptoContext {
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
// This should never be called.
throw new MslInternalException("Wrap is unsupported by the MSL token crypto context.");
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
// This should never be called.
throw new MslInternalException("Unwrap is unsupported by the MSL token crypto context.");
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return new byte[0];
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
return false;
}
}
| 1,674 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/AsymmetricCryptoContext.java
|
/**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
/**
* An asymmetric crypto context performs encrypt/decrypt and sign/verify using
* a public/private key pair. Wrap/unwrap are unsupported.
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class AsymmetricCryptoContext extends ICryptoContext {
/** Null transform or algorithm. */
protected static final String NULL_OP = "nullOp";
/**
* <p>Create a new asymmetric crypto context using the provided public and
* private keys and named encrypt/decrypt transform and sign/verify
* algorithm.</p>
*
* <p>If there is no private key, decryption and signing is unsupported.</p>
*
* <p>If there is no public key, encryption and verification is
* unsupported.</p>
*
* <p>If {@code #NULL_OP} is specified for the transform then encrypt/
* decrypt operations will return the data unmodified even if the key is
* null. Otherwise the operation is unsupported if the key is null.</p>
*
* <p>If {@code #NULL_OP} is specified for the algorithm then sign/verify
* will return an empty signature and always pass verification even if the
* key is null. Otherwise the operation is unsupported if the key is
* null.</p>
*
* @param id the key pair identity.
* @param privateKey the private key used for signing. May be null.
* @param publicKey the public key used for verifying. May be null.
* @param transform encrypt/decrypt transform.
* @param params encrypt/decrypt algorithm parameters. May be null.
* @param algo sign/verify algorithm.
*/
protected AsymmetricCryptoContext(final String id, final PrivateKey privateKey, final PublicKey publicKey, final String transform, final AlgorithmParameterSpec params, final String algo) {
this.id = id;
this.privateKey = privateKey;
this.publicKey = publicKey;
this.transform = transform;
this.params = params;
this.algo = algo;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (NULL_OP.equals(transform))
return data;
if (publicKey == null)
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED, "no public key");
Throwable reset = null;
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(transform);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, params);
final byte[] ciphertext = cipher.doFinal(data);
// Return encryption envelope byte representation.
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(id, null, ciphertext);
return envelope.toMslEncoding(encoder, format);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final MslEncoderException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_ENCODE_ERROR, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(transform);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (NULL_OP.equals(transform))
return data;
if (privateKey == null)
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED, "no private key");
Throwable reset = null;
try {
// Reconstitute encryption envelope.
final MslObject encryptionEnvelopeMo = encoder.parseObject(data);
final MslCiphertextEnvelope encryptionEnvelope = new MslCiphertextEnvelope(encryptionEnvelopeMo, MslCiphertextEnvelope.Version.V1);
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(transform);
cipher.init(Cipher.DECRYPT_MODE, privateKey, params);
return cipher.doFinal(encryptionEnvelope.getCiphertext());
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PRIVATE_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
} catch (final MslEncoderException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR, e);
} catch (final MslEncodingException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR, e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(transform);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.WRAP_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.UNWRAP_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (NULL_OP.equals(algo))
return new byte[0];
if (privateKey == null)
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "no private key.");
try {
final Signature sig = CryptoCache.getSignature(algo);
sig.initSign(privateKey);
sig.update(data);
final byte[] signature = sig.sign();
// Return the signature envelope byte representation.
return new MslSignatureEnvelope(signature).getBytes(encoder, format);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid signature algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_PRIVATE_KEY, e);
} catch (final SignatureException e) {
throw new MslCryptoException(MslError.SIGNATURE_ERROR, e);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_ENCODE_ERROR, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
if (NULL_OP.equals(algo))
return true;
if (publicKey == null)
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "no public key.");
try {
// Reconstitute the signature envelope.
final MslSignatureEnvelope envelope = MslSignatureEnvelope.parse(signature, encoder);
final Signature sig = CryptoCache.getSignature(algo);
sig.initVerify(publicKey);
sig.update(data);
return sig.verify(envelope.getSignature());
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid signature algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, e);
} catch (final SignatureException e) {
throw new MslCryptoException(MslError.SIGNATURE_ERROR, e);
} catch (final MslEncodingException e) {
throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_PARSE_ERROR, e);
}
}
/** Key pair identity. */
protected final String id;
/** Encryption/decryption cipher. */
protected final PrivateKey privateKey;
/** Sign/verify signature. */
protected final PublicKey publicKey;
/** Encryption/decryption transform. */
private final String transform;
/** Encryption/decryption algorithm parameters. */
private final AlgorithmParameterSpec params;
/** Sign/verify algorithm. */
private final String algo;
}
| 1,675 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/EccCryptoContext.java
|
/**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* An ECC crypto context performs ECIES encryption/decryption or SHA-1 with
* ECDSA sign/verify using a public/private ECC key pair.
*
* @author Wesley Miaw <[email protected]>
*/
public class EccCryptoContext extends AsymmetricCryptoContext {
/** ECC crypto context mode. .*/
public static enum Mode {
ENCRYPT_DECRYPT,
SIGN_VERIFY
};
/**
* <p>Create a new ECC crypto context using the provided public and private
* keys.</p>
*
* <p>If there is no private key, decryption and signing is unsupported.</p>
*
* <p>If there is no public key, encryption and verification is
* unsupported.</p>
*
* @param id the key pair identity.
* @param privateKey the private key used for signing. May be null.
* @param publicKey the public key used for verifying. May be null.
* @param mode crypto context mode.
*/
public EccCryptoContext(final String id, final PrivateKey privateKey, final PublicKey publicKey, final Mode mode) {
super(id, privateKey, publicKey, Mode.ENCRYPT_DECRYPT.equals(mode) ? "ECIES" : NULL_OP, null, Mode.SIGN_VERIFY.equals(mode) ? "SHA256withECDSA" : NULL_OP);
}
}
| 1,676 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/SessionCryptoContext.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import javax.crypto.SecretKey;
import com.netflix.msl.MslError;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* This is a convenience class for constructing a symmetric crypto context from
* a MSL session master token.
*
* @author Wesley Miaw <[email protected]>
*/
public class SessionCryptoContext extends SymmetricCryptoContext {
/**
* <p>Construct a new session crypto context from the provided master
* token.</p>
*
* @param ctx MSL context.
* @param masterToken the master token.
* @throws MslMasterTokenException if the master token is not trusted.
*/
public SessionCryptoContext(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException {
this(ctx, masterToken, masterToken.getIdentity(), masterToken.getEncryptionKey(), masterToken.getSignatureKey());
if (!masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
}
/**
* <p>Construct a new session crypto context from the provided master token.
* The entity identity and keys are assumed to be the same as what is
* inside the master token, which may be untrusted.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be untrusted.
* @param identity entity identity. May be {@code null}.
* @param encryptionKey encryption key.
* @param hmacKey HMAC key.
*/
public SessionCryptoContext(final MslContext ctx, final MasterToken masterToken, final String identity, final SecretKey encryptionKey, final SecretKey hmacKey) {
super(ctx, (identity != null) ? identity + "_" + masterToken.getSequenceNumber() : Long.toString(masterToken.getSequenceNumber()), encryptionKey, hmacKey, null);
}
}
| 1,677 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/JsonWebEncryptionCryptoContext.java
|
/**
* Copyright (c) 2013-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslArray;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslEncoderUtils;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* <p>This key exchange crypto context provides an implementation of the JSON
* web encryption algorithm as defined in
* <a href="http://tools.ietf.org/html/draft-ietf-mose-json-web-encryption-08">JSON Web Encryption</a>.
* It supports a limited subset of the algorithms.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class JsonWebEncryptionCryptoContext extends ICryptoContext {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** JSON key recipients. */
private static final String KEY_RECIPIENTS = "recipients";
/** JSON key header. */
private static final String KEY_HEADER = "header";
/** JSON key encrypted key. */
private static final String KEY_ENCRYPTED_KEY = "encrypted_key";
/** JSON key integrity value. */
private static final String KEY_INTEGRITY_VALUE = "integrity_value";
/** JSON key initialization vector. */
private static final String KEY_INITIALIZATION_VECTOR = "initialization_vector";
/** JSON key ciphertext. */
private static final String KEY_CIPHERTEXT = "ciphertext";
/** JSON key wrap algorithm. */
private static final String KEY_ALGORITHM = "alg";
/** JSON key encryption algorithm. */
private static final String KEY_ENCRYPTION = "enc";
/** AES-128 GCM authentication tag length in bits. */
private static final int A128_GCM_AT_LENGTH = 128;
/** AES-128 GCM key length in bytes. */
private static final int A128_GCM_KEY_LENGTH = 16;
/** AES-128 GCM initialization vector length in bytes. */
private static final int A128_GCM_IV_LENGTH = 12;
/** AES-256 GCM authentication tag length in bits. */
private static final int A256_GCM_AT_LENGTH = 128;
/** AES-256 GCM key length in bytes. */
private static final int A256_GCM_KEY_LENGTH = 32;
/** AES-256 GCM initialization vector length in bytes. */
private static final int A256_GCM_IV_LENGTH = 12;
/** Supported content encryption key encryption algorithms. */
private static enum Algorithm {
/** RSAES-OAEP */
RSA_OAEP("RSA-OAEP"),
/** AES-128 Key Wrap */
A128KW("A128KW");
/**
* @param name JSON Web Encryption algorithm name.
*/
private Algorithm(final String name) {
this.name = name;
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return name;
}
/**
* @param name JSON Web Encryption algorithm name.
* @return the algorithm.
* @throws IllegalArgumentException if the algorithm name is unknown.
*/
public static Algorithm fromString(final String name) {
for (final Algorithm algo : values()) {
if (algo.toString().equals(name))
return algo;
}
throw new IllegalArgumentException("Algorithm " + name + " is unknown.");
}
/** JSON Web Encryption algorithm name. */
private final String name;
}
/**
* The Content Encryption Key crypto context is used to encrypt/decrypt the
* randomly generated content encryption key.
*/
public static abstract class CekCryptoContext extends ICryptoContext {
/**
* Create a new content encryption key crypto context with the
* specified content encryption key encryption algorithm.
*
* @param algo content encryption key encryption algorithm.
*/
protected CekCryptoContext(final Algorithm algo) {
this.algo = algo;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.WRAP_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.UNWRAP_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED);
}
/**
* @return the content encryption key encryption algorithm.
*/
Algorithm getAlgorithm() {
return algo;
}
/** Content encryption key encryption algorithm. */
private final Algorithm algo;
}
/**
* RSA-OAEP encrypt/decrypt of the content encryption key.
*/
public static class RsaOaepCryptoContext extends CekCryptoContext {
/** RSA-OAEP cipher transform. */
private static final String RSA_OAEP_TRANSFORM = "RSA/ECB/OAEPPadding";
/**
* <p>Create a new RSA crypto context for encrypt/decrypt using the
* provided public and private keys. All other operations are
* unsupported.</p>
*
* <p>If there is no private key decryption is unsupported.</p>
*
* <p>If there is no public key encryption is unsupported.</p>
*
* @param privateKey the private key. May be null.
* @param publicKey the public key. May be null.
*/
public RsaOaepCryptoContext(final PrivateKey privateKey, final PublicKey publicKey) {
super(Algorithm.RSA_OAEP);
this.privateKey = privateKey;
this.publicKey = publicKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (publicKey == null)
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED, "no public key");
Throwable reset = null;
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(RSA_OAEP_TRANSFORM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, OAEPParameterSpec.DEFAULT);
return cipher.doFinal(data);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(RSA_OAEP_TRANSFORM);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (privateKey == null)
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED, "no private key");
Throwable reset = null;
try {
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(RSA_OAEP_TRANSFORM);
cipher.init(Cipher.DECRYPT_MODE, privateKey, OAEPParameterSpec.DEFAULT);
return cipher.doFinal(data);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PRIVATE_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(RSA_OAEP_TRANSFORM);
}
}
/** Encryption/decryption cipher. */
protected final PrivateKey privateKey;
/** Sign/verify signature. */
protected final PublicKey publicKey;
}
/**
* AES key wrap encrypt/decrypt of the content encryption key.
*/
public static class AesKwCryptoContext extends CekCryptoContext {
/** AES key wrap cipher transform. */
private static final String A128_KW_TRANSFORM = "AESWrap";
/**
* Create a new AES key wrap crypto context with the provided secret
* key.
*
* @param key AES secret key.
*/
public AesKwCryptoContext(final SecretKey key) {
super(Algorithm.A128KW);
if (!key.getAlgorithm().equals(JcaAlgorithm.AESKW))
throw new IllegalArgumentException("Secret key must be an " + JcaAlgorithm.AESKW + " key.");
this.key = key;
this.cryptoContext = null;
}
/**
* Create a new AES key wrap crypto context backed by the provided
* AES crypto context.
*
* @param cryptoContext AES crypto context.
*/
public AesKwCryptoContext(final ICryptoContext cryptoContext) {
super(Algorithm.A128KW);
this.key = null;
this.cryptoContext = cryptoContext;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
// If a secret key is provided use it.
if (key != null) {
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(A128_KW_TRANSFORM);
cipher.init(Cipher.WRAP_MODE, key);
// TODO: The key spec algorithm should be based on the JWE
// encryption algorithm. Right now that is always AES-GCM.
final Key secretKey = new SecretKeySpec(data, "AES");
return cipher.wrap(secretKey);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Invalid content encryption key provided.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
}
}
// Otherwise use the backing crypto context.
return cryptoContext.wrap(data, encoder, format);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
// If a secret key is provided use it.
if (key != null) {
try {
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(A128_KW_TRANSFORM);
cipher.init(Cipher.UNWRAP_MODE, key);
return cipher.unwrap(data, "AES", Cipher.SECRET_KEY).getEncoded();
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
}
}
// Otherwise use the backing crypto context.
return cryptoContext.unwrap(data, encoder);
}
/** AES secret key. */
private final SecretKey key;
/** AES crypto context. */
private final ICryptoContext cryptoContext;
}
/** Supported plaintext encryption algorithms. */
public static enum Encryption {
/** AES-128 GCM */
A128GCM,
/** AES-256 GCM */
A256GCM,
}
/** Support serialization formats. */
public static enum Format {
/**
* <a href="http://tools.ietf.org/html/draft-mones-mose-jwe-json-serialization-04">JSON Web Encryption JSON Serialization (JWE-JS)</a>
*/
JWE_JS,
/**
* <a href="http://tools.ietf.org/html/draft-ietf-mose-json-web-encryption-08">JSON Web Encryption Compact Serialization</a>
*/
JWE_CS
}
/**
* Create a new JSON web encryption crypto context with the provided
* content encryption key crypto context and specified plaintext encryption
* algorithm.
*
* @param ctx MSL context.
* @param cryptoContext content encryption key crypto context.
* @param enc plaintext encryption algorithm.
* @param format serialization format.
*/
public JsonWebEncryptionCryptoContext(final MslContext ctx, final CekCryptoContext cryptoContext, final Encryption enc, final Format format) {
this.ctx = ctx;
this.cekCryptoContext = cryptoContext;
this.algo = cryptoContext.getAlgorithm();
this.enc = enc;
this.format = format;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
// Create the header.
final byte[] header;
try {
final MslObject headerMo = encoder.createObject();
headerMo.put(KEY_ALGORITHM, algo.toString());
headerMo.put(KEY_ENCRYPTION, enc.name());
header = encoder.encodeObject(headerMo, MslEncoderFormat.JSON);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.JWE_ENCODE_ERROR, e);
}
// Determine algorithm byte lengths.
final int keylen, ivlen, atlen;
if (Encryption.A128GCM.equals(enc)) {
keylen = A128_GCM_KEY_LENGTH;
ivlen = A128_GCM_IV_LENGTH;
atlen = A128_GCM_AT_LENGTH;
} else if (Encryption.A256GCM.equals(enc)) {
keylen = A256_GCM_KEY_LENGTH;
ivlen = A256_GCM_IV_LENGTH;
atlen = A256_GCM_AT_LENGTH;
} else {
throw new MslCryptoException(MslError.UNSUPPORTED_JWE_ALGORITHM, enc.name());
}
// Generate the key and IV.
final Random random = ctx.getRandom();
final byte[] key = new byte[keylen];
random.nextBytes(key);
final KeyParameter cek = new KeyParameter(key);
final byte[] iv = new byte[ivlen];
random.nextBytes(iv);
// Encrypt the CEK.
final byte[] ecek = cekCryptoContext.encrypt(cek.getKey(), encoder, MslEncoderFormat.JSON);
// Base64-encode the data.
final String headerB64 = MslEncoderUtils.b64urlEncode(header);
final String ecekB64 = MslEncoderUtils.b64urlEncode(ecek);
final String ivB64 = MslEncoderUtils.b64urlEncode(iv);
// Create additional authenticated data.
final String aad = headerB64 + "." + ecekB64 + "." + ivB64;
// TODO: AES-GCM is not available via the JCE.
//
// Create and initialize the cipher for encryption.
final GCMBlockCipher plaintextCipher = new GCMBlockCipher(new AESEngine());
final AEADParameters params = new AEADParameters(cek, atlen, iv, aad.getBytes(UTF_8));
plaintextCipher.init(true, params);
// Encrypt the plaintext.
final byte[] ciphertextATag;
try {
final int clen = plaintextCipher.getOutputSize(data.length);
ciphertextATag = new byte[clen];
// Encrypt the plaintext and get the resulting ciphertext length
// which will be used for the authentication tag offset.
final int offset = plaintextCipher.processBytes(data, 0, data.length, ciphertextATag, 0);
// Append the authentication tag.
plaintextCipher.doFinal(ciphertextATag, offset);
} catch (final IllegalStateException e) {
throw new MslCryptoException(MslError.WRAP_ERROR, e);
} catch (final InvalidCipherTextException e) {
throw new MslInternalException("Invalid ciphertext not expected when encrypting.", e);
}
// Split the result into the ciphertext and authentication tag.
final byte[] ciphertext = Arrays.copyOfRange(ciphertextATag, 0, ciphertextATag.length - atlen/Byte.SIZE);
final byte[] at = Arrays.copyOfRange(ciphertextATag, ciphertext.length, ciphertextATag.length);
// Base64-encode the ciphertext and authentication tag.
final String ciphertextB64 = MslEncoderUtils.b64urlEncode(ciphertext);
final String atB64 = MslEncoderUtils.b64urlEncode(at);
// Envelope the data.
switch (this.format) {
case JWE_CS:
{
final String serialization = aad + "." + ciphertextB64 + "." + atB64;
return serialization.getBytes(UTF_8);
}
case JWE_JS:
{
try {
// Create recipients array.
final MslArray recipients = encoder.createArray();
final MslObject recipient = encoder.createObject();
recipient.put(KEY_HEADER, headerB64);
recipient.put(KEY_ENCRYPTED_KEY, ecekB64);
recipient.put(KEY_INTEGRITY_VALUE, atB64);
recipients.put(-1, recipient);
// Create JSON serialization.
final MslObject serialization = encoder.createObject();
serialization.put(KEY_RECIPIENTS, recipients);
serialization.put(KEY_INITIALIZATION_VECTOR, ivB64);
serialization.put(KEY_CIPHERTEXT, ciphertextB64);
return encoder.encodeObject(serialization, MslEncoderFormat.JSON);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.JWE_ENCODE_ERROR, e);
}
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_JWE_SERIALIZATION, format.name());
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
// Parse the serialization.
final String serialization = new String(data, UTF_8);
final String headerB64, ecekB64, ivB64;
final byte[] ciphertext, at;
if (data[0] == '{') {
try {
final MslObject serializationMo = encoder.parseObject(data);
ivB64 = serializationMo.getString(KEY_INITIALIZATION_VECTOR);
ciphertext = MslEncoderUtils.b64urlDecode(serializationMo.getString(KEY_CIPHERTEXT));
// TODO: For now, we only support one recipient.
final MslArray recipients = serializationMo.getMslArray(KEY_RECIPIENTS);
if (recipients.size() < 1)
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization);
final MslObject recipient = recipients.getMslObject(0, encoder);
headerB64 = recipient.getString(KEY_HEADER);
ecekB64 = recipient.getString(KEY_ENCRYPTED_KEY);
at = MslEncoderUtils.b64urlDecode(recipient.getString(KEY_INTEGRITY_VALUE));
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization, e);
}
} else {
// Separate the compact serialization.
final String[] parts = serialization.split("\\.");
if (parts.length != 5)
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization);
// Extract the data from the serialization.
headerB64 = parts[0];
ecekB64 = parts[1];
ivB64 = parts[2];
ciphertext = MslEncoderUtils.b64urlDecode(parts[3]);
at = MslEncoderUtils.b64urlDecode(parts[4]);
}
// Decode header, encrypted content encryption key, and IV.
final byte[] headerBytes = MslEncoderUtils.b64urlDecode(headerB64);
final byte[] ecek = MslEncoderUtils.b64urlDecode(ecekB64);
final byte[] iv = MslEncoderUtils.b64urlDecode(ivB64);
// Verify data.
if (headerBytes == null || headerBytes.length == 0 ||
ecek == null || ecek.length == 0 ||
iv == null || iv.length == 0 ||
ciphertext == null || ciphertext.length == 0 ||
at == null || at.length == 0)
{
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization);
}
// Reconstruct and parse the header.
final String header = new String(headerBytes, UTF_8);
final Algorithm algo;
final Encryption enc;
try {
final MslObject headerMo = encoder.parseObject(headerBytes);
final String algoName = headerMo.getString(KEY_ALGORITHM);
try {
algo = Algorithm.fromString(algoName);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, algoName, e);
}
final String encName = headerMo.getString(KEY_ENCRYPTION);
try {
enc = Encryption.valueOf(encName);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, encName, e);
}
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, header, e);
}
// Confirm header matches.
if (!this.algo.equals(algo) || !this.enc.equals(enc))
throw new MslCryptoException(MslError.JWE_ALGORITHM_MISMATCH, header);
// Decrypt the CEK.
final KeyParameter cek;
try {
final byte[] cekBytes = cekCryptoContext.decrypt(ecek, encoder);
cek = new KeyParameter(cekBytes);
} catch (final ArrayIndexOutOfBoundsException e) {
// Thrown if the encrypted content encryption key is an invalid
// length.
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
}
// Create additional authenticated data.
final String aad = headerB64 + "." + ecekB64 + "." + ivB64;
// Determine algorithm byte lengths.
final int keylen, atlen;
if (Encryption.A128GCM.equals(enc)) {
keylen = A128_GCM_KEY_LENGTH;
atlen = A128_GCM_AT_LENGTH;
} else if (Encryption.A256GCM.equals(enc)) {
keylen = A256_GCM_KEY_LENGTH;
atlen = A256_GCM_AT_LENGTH;
} else {
throw new MslCryptoException(MslError.UNSUPPORTED_JWE_ALGORITHM, enc.name());
}
// Verify algorithm parameters.
if (cek.getKey().length != keylen)
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, "content encryption key length: " + cek.getKey().length);
if (at.length != atlen / Byte.SIZE)
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, "authentication tag length: " + at.length);
// TODO: AES-GCM is not available via the JCE.
//
// Create and initialize the cipher for decryption.
final GCMBlockCipher plaintextCipher = new GCMBlockCipher(new AESEngine());
final AEADParameters params = new AEADParameters(cek, atlen, iv, aad.getBytes(UTF_8));
plaintextCipher.init(false, params);
// Decrypt the ciphertext.
try {
// Reconstruct the ciphertext and authentication tag.
final byte[] ciphertextAtag = Arrays.copyOf(ciphertext, ciphertext.length + at.length);
System.arraycopy(at, 0, ciphertextAtag, ciphertext.length, at.length);
final int plen = plaintextCipher.getOutputSize(ciphertextAtag.length);
final byte[] plaintext = new byte[plen];
// Decrypt the ciphertext and get the resulting plaintext length
// which will be used for the authentication tag offset.
final int offset = plaintextCipher.processBytes(ciphertextAtag, 0, ciphertextAtag.length, plaintext, 0);
// Verify the authentication tag.
plaintextCipher.doFinal(plaintext, offset);
return plaintext;
} catch (final IllegalStateException e) {
throw new MslCryptoException(MslError.UNWRAP_ERROR, e);
} catch (final InvalidCipherTextException e) {
throw new MslCryptoException(MslError.UNWRAP_ERROR, e);
} catch (final ArrayIndexOutOfBoundsException e) {
// Thrown if the ciphertext is an invalid length.
throw new MslCryptoException(MslError.UNWRAP_ERROR, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED);
}
/** MSL context. */
private final MslContext ctx;
/** Content encryption key crypto context. */
private final ICryptoContext cekCryptoContext;
/** Wrap algorithm. */
private final Algorithm algo;
/** Encryption algorithm. */
private final Encryption enc;
/** Serialization format. */
private final Format format;
}
| 1,678 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/ICryptoContext.java
|
/**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.msg.ErrorHeader;
/**
* A generic cryptographic context suitable for encryption/decryption,
* wrap/unwrap, and sign/verify operations.
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class ICryptoContext {
/**
* Encrypts some data.
*
* @param data the plaintext.
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the ciphertext.
* @throws MslCryptoException if there is an error encrypting the data.
*/
public abstract byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException;
/**
* Decrypts some data.
*
* @param data the ciphertext.
* @param encoder MSL encoder factory.
* @return the plaintext.
* @throws MslCryptoException if there is an error decrypting the data.
*/
public abstract byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException;
/**
* Wraps some data.
*
* @param data the plaintext.
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the wrapped data.
* @throws MslCryptoException if there is an error wrapping the data.
*/
public abstract byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException;
/**
* Unwraps some data.
*
* @param data the wrapped data.
* @param encoder MSL encoder factory.
* @return the plaintext.
* @throws MslCryptoException if there is an error unwrapping the data.
*/
public abstract byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException;
/**
* Computes the signature for some data. The signature may not be a
* signature proper, but the name suits the concept.
*
* @param data the data.
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the signature.
* @throws MslCryptoException if there is an error computing the signature.
*/
public abstract byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException;
/**
* Computes the signature for some data. This form of the sign method
* accepts an additional MSL ErrorHeader object that can be used as
* operational context when signing errors. The default implementation
* below ignores that parameter, but subclasses can provide an override.
*
* @param data the data.
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @param errorHeader MSL ErrorHeader instance
* @return the signature.
* @throws MslCryptoException if there is an error computing the signature.
*/
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format, ErrorHeader errorHeader) throws MslCryptoException {
return sign(data, encoder, format);
}
/**
* Verifies the signature for some data. The signature may not be a
* signature proper, but the name suits the concept.
*
* @param data the data.
* @param signature the signature.
* @param encoder MSL encoder factory.
* @return true if the data is verified, false if validation fails.
* @throws MslCryptoException if there is an error verifying the signature.
*/
public abstract boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException;
}
| 1,679 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/RsaCryptoContext.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.spec.OAEPParameterSpec;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.util.MslContext;
/**
* <p>An RSA crypto context supports RSA/ECB/OAEPPadding or RSA/ECB/PKCS#1
* encryption/decryption, or SHA-256 with RSA sign/verify.</p>
*
* <p>The {@link OAEPParameterSpec#DEFAULT} parameters are used for OAEP
* encryption and decryption.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class RsaCryptoContext extends AsymmetricCryptoContext {
/** RSA crypto context algorithm. .*/
public static enum Mode {
/** RSA-OAEP encrypt/decrypt */
ENCRYPT_DECRYPT_OAEP,
/** RSA PKCS#1 encrypt/decrypt */
ENCRYPT_DECRYPT_PKCS1,
/** RSA-KEM wrap/unwrap */
WRAP_UNWRAP,
/** RSA-SHA256 sign/verify */
SIGN_VERIFY
};
/**
* <p>Create a new RSA crypto context for encrypt/decrypt and sign/verify
* using the provided public and private keys. The crypto context algorithm
* identifies the operations to enable. All other operations are no-ops and
* return the data unmodified.</p>
*
* <p>If there is no private key, decryption and signing is unsupported.</p>
*
* <p>If there is no public key, encryption and verification is
* unsupported.</p>
*
* @param ctx MSL context.
* @param id the key pair identity.
* @param privateKey the private key. May be null.
* @param publicKey the public key. May be null.
* @param algo crypto context algorithm.
*/
public RsaCryptoContext(final MslContext ctx, final String id, final PrivateKey privateKey, final PublicKey publicKey, final Mode algo) {
super(id, privateKey, publicKey,
Mode.ENCRYPT_DECRYPT_PKCS1.equals(algo) ? "RSA/ECB/PKCS1Padding" : (Mode.ENCRYPT_DECRYPT_OAEP.equals(algo) ? "RSA/ECB/OAEPPadding" : NULL_OP),
Mode.ENCRYPT_DECRYPT_OAEP.equals(algo) ? OAEPParameterSpec.DEFAULT : null,
Mode.SIGN_VERIFY.equals(algo) ? "SHA256withRSA" : NULL_OP);
if (algo == Mode.WRAP_UNWRAP)
throw new MslInternalException("Wrap/unwrap unsupported.");
}
}
| 1,680 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/MslSignatureEnvelope.java
|
/**
* Copyright (c) 2013-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslConstants.SignatureAlgo;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>MSL signature envelopes contain all of the information necessary for
* verifying data using a known key.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslSignatureEnvelope {
/** Key version. */
private final static String KEY_VERSION = "version";
/** Key algorithm. */
private final static String KEY_ALGORITHM = "algorithm";
/** Key signature. */
private final static String KEY_SIGNATURE = "signature";
/** Versions. */
public static enum Version {
/**
* <p>Version 1.</p>
*
* {@code signature}
*
* <p>The signature is represented as raw bytes.</p>
*/
V1,
/**
* <p>Version 2.</p>
*
* {@code {
* "#mandatory" : [ "version", "algorithm", "signature" ],
* "version" : "number",
* "algorithm" : "string",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code version} is the number '2'</li>
* <li>{@code algorithm} is one of the recognized signature algorithms</li>
* <li>{@code signature} is the signature</li>
* </ul>
*
* <p>Supported algorithms:
* <table>
* <tr><th>Algorithm</th><th>Description</th>
* <tr><td>HmacSHA256</td><td>HMAC w/SHA-256</td></tr>
* <tr><td>SHA256withRSA</td><td>RSA signature w/SHA-256</td></tr>
* <tr><td>AESCmac</td><td>AES CMAC</td></tr>
* </table></p>
*/
V2;
/**
* @param version the integer value of this version.
* @return the version identified by the integer value.
* @throws IllegalArgumentException if the version is unknown.
*/
public static Version valueOf(final int version) {
switch (version) {
case 1: return V1;
case 2: return V2;
default: throw new IllegalArgumentException("Unknown signature envelope version.");
}
}
/**
* @return the integer value of this version.
*/
public int intValue() {
switch (this) {
case V1: return 1;
case V2: return 2;
default: throw new MslInternalException("No integer value defined for version " + this + ".");
}
}
}
/**
* Create a new version 1 signature envelope with the provided signature.
*
* @param signature the signature.
*/
public MslSignatureEnvelope(final byte[] signature) {
this.version = Version.V1;
this.algorithm = null;
this.signature = signature;
}
/**
* Create a new version 2 signature envelope with the provided data.
*
* @param algorithm the signature algorithm.
* @param signature the signature.
*/
public MslSignatureEnvelope(final SignatureAlgo algorithm, final byte[] signature) {
this.version = Version.V2;
this.algorithm = algorithm;
this.signature = signature;
}
/**
* Create a new signature envelope for the specified version from the
* provided envelope bytes.
*
* @param ctx MSL context.
* @param envelope the raw envelope bytes.
* @param version the envelope version.
* @return the envelope.
* @throws MslCryptoException if there is an error processing the signature
* envelope.
* @throws MslEncodingException if there is an error parsing the envelope.
* @see #getBytes(MslEncoderFactory, MslEncoderFormat)
*/
public static MslSignatureEnvelope parse(final MslContext ctx, final byte[] envelope, final Version version) throws MslCryptoException, MslEncodingException {
// Parse envelope.
switch (version) {
case V1:
return new MslSignatureEnvelope(envelope);
case V2:
try {
// We expect the byte representation to be a MSL object.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject envelopeMo = encoder.parseObject(envelope);
// Verify version.
try {
final Version v = Version.valueOf(envelopeMo.getInt(KEY_VERSION));
if (!Version.V2.equals(v))
throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + envelopeMo);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_SIGNATURE_ENVELOPE, "signature envelope " + envelopeMo, e);
}
// Grab algorithm.
final SignatureAlgo algorithm;
try {
algorithm = SignatureAlgo.fromString(envelopeMo.getString(KEY_ALGORITHM));
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_ALGORITHM, "signature envelope " + envelopeMo, e);
}
// Grab signature.
final byte[] signature = envelopeMo.getBytes(KEY_SIGNATURE);
// Return the envelope.
return new MslSignatureEnvelope(algorithm, signature);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "signature envelope " + Base64.encode(envelope), e);
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + Base64.encode(envelope));
}
}
/**
* Create a new signature envelope from the provided envelope bytes.
*
* @param envelope the raw envelope bytes.
* @param encoder MSL encoder factory.
* @return the envelope.
* @throws MslCryptoException if there is an error processing the signature
* envelope.
* @throws MslEncodingException if there is an error parsing the envelope.
* @see #getBytes(MslEncoderFactory, MslEncoderFormat)
*/
public static MslSignatureEnvelope parse(final byte[] envelope, final MslEncoderFactory encoder) throws MslCryptoException, MslEncodingException {
// Attempt to convert this to a MSL object.
MslObject envelopeMo;
try {
// If this is a MSL object, we expect the byte representation to be
// decodable.
envelopeMo = encoder.parseObject(envelope);
} catch (final MslEncoderException e) {
envelopeMo = null;
}
// Determine the envelope version.
//
// If there is no MSL object, or there is no version field (as the
// binary signature may coincidentally parse into a MSL object), then
// this is a version 1 envelope.
Version version;
if (envelopeMo == null || !envelopeMo.has(KEY_VERSION)) {
version = Version.V1;
} else {
try {
version = Version.valueOf(envelopeMo.getInt(KEY_VERSION));
} catch (final MslEncoderException e) {
// There is a possibility that this is a version 1 envelope.
version = Version.V1;
} catch (final IllegalArgumentException e) {
// There is a possibility that this is a version 1 envelope.
version = Version.V1;
}
}
// Parse envelope.
switch (version) {
case V1:
return new MslSignatureEnvelope(envelope);
case V2:
try {
final SignatureAlgo algorithm = SignatureAlgo.fromString(envelopeMo.getString(KEY_ALGORITHM));
final byte[] signature = envelopeMo.getBytes(KEY_SIGNATURE);
return new MslSignatureEnvelope(algorithm, signature);
} catch (final MslEncoderException e) {
// It is extremely unlikely but possible that this is a
// version 1 envelope.
return new MslSignatureEnvelope(envelope);
} catch (final IllegalArgumentException e) {
// It is extremely unlikely but possible that this is a
// version 1 envelope.
return new MslSignatureEnvelope(envelope);
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + Base64.encode(envelope));
}
}
/**
* @return the signature algorithm. May be null.
*/
public SignatureAlgo getAlgorithm() {
return algorithm;
}
/**
* @return the signature.
*/
public byte[] getSignature() {
return signature;
}
/** Envelope version. */
private final Version version;
/** Algorithm. */
private final SignatureAlgo algorithm;
/** Signature. */
private final byte[] signature;
/**
* Returns the signature envelope in byte form.
*
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the byte representation of the signature envelope.
* @throws MslEncoderException if there is an error encoding the envelope.
* @throws MslInternalException if the envelope version is not supported.
*/
public byte[] getBytes(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
switch (version) {
case V1:
return signature;
case V2:
final MslObject mo = encoder.createObject();
mo.put(KEY_VERSION, version.intValue());
mo.put(KEY_ALGORITHM, algorithm.name());
mo.put(KEY_SIGNATURE, signature);
return encoder.encodeObject(mo, format);
default:
throw new MslInternalException("Signature envelope version " + version + " encoding unsupported.");
}
}
}
| 1,681 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/MslCiphertextEnvelope.java
|
/**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslConstants.CipherSpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.Base64;
/**
* MSL ciphertext envelopes contain all of the information necessary for
* decrypting ciphertext using a known key.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslCiphertextEnvelope implements MslEncodable {
/** Key version. */
private final static String KEY_VERSION = "version";
/** Key key ID. */
private final static String KEY_KEY_ID = "keyid";
/** Key cipherspec. */
private final static String KEY_CIPHERSPEC = "cipherspec";
/** Key initialization vector. */
private final static String KEY_IV = "iv";
/** Key ciphertext. */
private final static String KEY_CIPHERTEXT = "ciphertext";
/** Key SHA-256. */
private final static String KEY_SHA256 = "sha256";
/** Versions. */
public static enum Version {
/**
* <p>Version 1.</p>
*
* {@code {
* "#mandatory" : [ "keyid", "iv", "ciphertext", "sha256" ],
* "keyid" : "string",
* "iv" : "binary",
* "ciphertext" : "binary",
* "sha256" : "binary",
* }} where:
* <ul>
* <li>{@code keyid} is the encryption key ID</li>
* <li>{@code iv} is the initialization vector</li>
* <li>{@code ciphertext} is the ciphertext</li>
* <li>{@code sha256} is the SHA-256 of the encryption envelope</li>
* </ul>
*
* <p>The SHA-256 is computed over the concatenation of {@code key ID ||
* IV || ciphertext}.</p>
*/
V1,
/**
* <p>Version 2.</p>
*
* {@code {
* "#mandatory" : [ "version", "cipherspec", "ciphertext" ],
* "version" : "number",
* "cipherspec" : "string",
* "iv" : "binary",
* "ciphertext" : "binary",
* }} where:
* <ul>
* <li>{@code version} is the number '2'</li>
* <li>{@code cipherspec} is one of the recognized cipher specifications</li>
* <li>{@code iv} is the optional initialization vector</li>
* <li>{@code ciphertext} is the ciphertext</li>
* </ul>
*
* <p>Supported cipher specifications:
* <table>
* <tr><th>Cipher Spec</th><th>Description</th></tr>
* <tr><td>AES/CBC/PKCS5Padding</td><td>AES CBC w/PKCS#5 Padding</td></tr>
* </table></p>
*/
V2;
/**
* @param version the integer value of this version.
* @return the version identified by the integer value.
* @throws IllegalArgumentException if the version is unknown.
*/
public static Version valueOf(final int version) {
switch (version) {
case 1: return V1;
case 2: return V2;
default: throw new IllegalArgumentException("Unknown ciphertext envelope version " + version + ".");
}
}
/**
* @return the integer value of this version.
*/
public int intValue() {
switch (this) {
case V1: return 1;
case V2: return 2;
default: throw new MslInternalException("No integer value defined for version " + this + ".");
}
}
}
/**
* Determines the envelope version of the given MSL object.
*
* @param mo the MSL object.
* @return the envelope version.
* @throws MslCryptoException if the envelope version is not recognized.
*/
private static Version getVersion(final MslObject mo) throws MslCryptoException {
try {
final int v = mo.getInt(KEY_VERSION);
return Version.valueOf(v);
} catch (final MslEncoderException e) {
// If anything fails to parse, treat this as a version 1 envelope.
return Version.V1;
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_CIPHERTEXT_ENVELOPE, "ciphertext envelope " + mo, e);
}
}
/**
* Create a new version 1 ciphertext envelope with the provided data.
*
* @param keyId the key identifier.
* @param iv the initialization vector. May be null.
* @param ciphertext the ciphertext.
*/
public MslCiphertextEnvelope(final String keyId, final byte[] iv, final byte[] ciphertext) {
this.version = Version.V1;
this.keyId = keyId;
this.cipherSpec = null;
this.iv = iv;
this.ciphertext = ciphertext;
}
/**
* Create a new version 2 ciphertext envelope with the provided data.
*
* @param cipherSpec the cipher specification.
* @param iv the initialization vector. May be null.
* @param ciphertext the ciphertext.
*/
public MslCiphertextEnvelope(final CipherSpec cipherSpec, final byte[] iv, final byte[] ciphertext) {
this.version = Version.V2;
this.keyId = null;
this.cipherSpec = cipherSpec;
this.iv = iv;
this.ciphertext = ciphertext;
}
/**
* Create a new encryption envelope from the provided MSL object.
*
* @param mo the MSL object.
* @throws MslCryptoException if there is an error processing the
* encryption envelope.
* @throws MslEncodingException if there is an error parsing the data.
*/
public MslCiphertextEnvelope(final MslObject mo) throws MslCryptoException, MslEncodingException {
this(mo, getVersion(mo));
}
/**
* Create a new encryption envelope of the specified version from the
* provided MSL object.
*
* @param mo the MSL object.
* @param version the envelope version.
* @throws MslCryptoException if there is an error processing the
* encryption envelope.
* @throws MslEncodingException if there is an error parsing the data.
*/
public MslCiphertextEnvelope(final MslObject mo, final Version version) throws MslCryptoException, MslEncodingException {
// Parse envelope.
switch (version) {
case V1:
try {
this.version = Version.V1;
this.keyId = mo.getString(KEY_KEY_ID);
this.cipherSpec = null;
this.iv = (mo.has(KEY_IV)) ? mo.getBytes(KEY_IV) : null;
this.ciphertext = mo.getBytes(KEY_CIPHERTEXT);
mo.getBytes(KEY_SHA256);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "ciphertext envelope " + mo, e);
}
break;
case V2:
try {
final int v = mo.getInt(KEY_VERSION);
this.version = Version.valueOf(v);
if (!Version.V2.equals(this.version))
throw new MslCryptoException(MslError.UNIDENTIFIED_CIPHERTEXT_ENVELOPE, "ciphertext envelope " + mo.toString());
this.keyId = null;
try {
this.cipherSpec = CipherSpec.fromString(mo.getString(KEY_CIPHERSPEC));
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_CIPHERSPEC, "ciphertext envelope " + mo, e);
}
this.iv = (mo.has(KEY_IV)) ? mo.getBytes(KEY_IV) : null;
this.ciphertext = mo.getBytes(KEY_CIPHERTEXT);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "ciphertext envelope " + mo, e);
}
break;
default:
throw new MslCryptoException(MslError.UNSUPPORTED_CIPHERTEXT_ENVELOPE, "ciphertext envelope version " + version);
}
}
/**
* @return the encryption key ID. May be null.
*/
public String getKeyId() {
return keyId;
}
/**
* @return the ciphser specification. May be null.
*/
public CipherSpec getCipherSpec() {
return cipherSpec;
}
/**
* @return the initialization vector. May be null.
*/
public byte[] getIv() {
return iv;
}
/**
* @return the ciphertext.
*/
public byte[] getCiphertext() {
return ciphertext;
}
/** Envelope version. */
private final Version version;
/** Key identifier. */
private final String keyId;
/** Cipher specification. */
private CipherSpec cipherSpec;
/** Optional initialization vector. */
private final byte[] iv;
/** Ciphertext. */
private final byte[] ciphertext;
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
switch (version) {
case V1:
mo.put(KEY_KEY_ID, keyId);
if (iv != null) mo.put(KEY_IV, iv);
mo.put(KEY_CIPHERTEXT, ciphertext);
mo.put(KEY_SHA256, Base64.decode("AA=="));
break;
case V2:
mo.put(KEY_VERSION, version.intValue());
mo.put(KEY_CIPHERSPEC, cipherSpec.toString());
if (iv != null) mo.put(KEY_IV, iv);
mo.put(KEY_CIPHERTEXT, ciphertext);
break;
default:
throw new MslEncoderException("Ciphertext envelope version " + version + " encoding unsupported.");
}
return encoder.encodeObject(mo, format);
}
}
| 1,682 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/JcaAlgorithm.java
|
/**
* Copyright (c) 2013 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
/**
* <p>JCE standard algorithm name constants.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class JcaAlgorithm {
/** AES. */
public static final String AES = "AES";
/** HMAC-SHA256. */
public static final String HMAC_SHA256 = "HmacSHA256";
/** AES key wrap. */
public static final String AESKW = "AES";
/** CMAC. */
public static final String AES_CMAC = "AESCmac";
}
| 1,683 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/JsonWebKey.java
|
/**
* Copyright (c) 2013-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslArray;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslEncoderUtils;
import com.netflix.msl.io.MslObject;
/**
* This class implements the JSON web key structure as defined in
* <a href="http://tools.ietf.org/html/draft-ietf-mose-json-web-key-08">JSON Web Key</a>.
*
* @author Wesley Miaw <[email protected]>
*/
public class JsonWebKey implements MslEncodable {
/** JSON key key type. */
private static final String KEY_TYPE = "kty";
/** JSON key usage. */
private static final String KEY_USAGE = "use";
/** JSON key key operations. */
private static final String KEY_KEY_OPS = "key_ops";
/** JSON key algorithm. */
private static final String KEY_ALGORITHM = "alg";
/** JSON key extractable. */
private static final String KEY_EXTRACTABLE = "extractable";
/** JSON key key ID. */
private static final String KEY_KEY_ID = "kid";
// RSA keys.
/** JSON key modulus. */
private static final String KEY_MODULUS = "n";
/** JSON key public exponent. */
private static final String KEY_PUBLIC_EXPONENT = "e";
/** JSON key private exponent. */
private static final String KEY_PRIVATE_EXPONENT = "d";
// Symmetric keys.
/** JSON key key. */
private static final String KEY_KEY = "k";
/** Supported key types. */
public static enum Type {
/** RSA */
rsa,
/** Octet Sequence */
oct,
}
/** Supported key usages. */
public static enum Usage {
/** Sign/verify. */
sig,
/** Encrypt/decrypt. */
enc,
/** Wrap/unwrap. */
wrap,
}
/** Supported key operations. */
public static enum KeyOp {
sign,
verify,
encrypt,
decrypt,
wrapKey,
unwrapKey,
deriveKey,
deriveBits
}
/** Supported key algorithms. */
public static enum Algorithm {
/** HMAC-SHA256 */
HS256("HS256"),
/** RSA PKCS#1 v1.5 */
RSA1_5("RSA1_5"),
/** RSA OAEP */
RSA_OAEP("RSA-OAEP"),
/** AES-128 Key Wrap */
A128KW("A128KW"),
/** AES-128 CBC */
A128CBC("A128CBC");
/**
* @param name JSON Web Algorithm name.
*/
private Algorithm(final String name) {
this.name = name;
}
/**
* @return the Java Cryptography Architecture standard algorithm name
* for this JSON Web Algorithm.
*/
public String getJcaAlgorithmName() {
switch (this) {
case HS256:
return "HmacSHA256";
case RSA1_5:
case RSA_OAEP:
return "RSA";
case A128KW:
case A128CBC:
return "AES";
default:
throw new MslInternalException("No JCA standard algorithm name defined for " + this + ".");
}
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return name;
}
/**
* @param name JSON Web Algorithm name.
* @return the algorithm.
* @throws IllegalArgumentException if the algorithm name is unknown.
*/
public static Algorithm fromString(final String name) {
for (final Algorithm algo : values()) {
if (algo.toString().equals(name))
return algo;
}
throw new IllegalArgumentException("Algorithm " + name + " is unknown.");
}
/** JSON Web Algorithm name. */
private final String name;
}
/**
* Returns the big integer in big-endian format without any leading sign
* bits.
*
* @param bi the big integer.
* @return the big integer in big-endian form.
*/
private static byte[] bi2bytes(final BigInteger bi) {
final byte[] bib = bi.toByteArray();
final int len = (int)Math.ceil((double)bi.bitLength() / Byte.SIZE);
return Arrays.copyOfRange(bib, bib.length - len, bib.length);
}
/**
* Create a new JSON web key for an RSA public/private key pair with the
* specified attributes. At least one of the public key or private key must
* be encoded.
*
* @param usage key usage. May be null.
* @param algo key algorithm. May be null.
* @param extractable true if the key is extractable.
* @param id key ID. May be null.
* @param publicKey RSA public key. May be null.
* @param privateKey RSA private key. May be null.
* @throws MslInternalException if both keys are null or the algorithm
* is incompatible.
*/
public JsonWebKey(final Usage usage, final Algorithm algo, final boolean extractable, final String id, final RSAPublicKey publicKey, final RSAPrivateKey privateKey) {
if (publicKey == null && privateKey == null)
throw new MslInternalException("At least one of the public key or private key must be provided.");
if (algo != null) {
switch (algo) {
case RSA1_5:
case RSA_OAEP:
break;
default:
throw new MslInternalException("The algorithm must be an RSA algorithm.");
}
}
this.type = Type.rsa;
this.usage = usage;
this.keyOps = null;
this.algo = algo;
this.extractable = extractable;
this.id = id;
this.keyPair = new KeyPair(publicKey, privateKey);
this.key = null;
this.secretKey = null;
}
/**
* Create a new JSON web key for a symmetric key with the specified
* attributes.
*
* @param usage key usage. May be null.
* @param algo key algorithm. May be null.
* @param extractable true if the key is extractable.
* @param id key ID. May be null.
* @param secretKey symmetric key.
* @throws MslInternalException if the usage or algorithm is incompatible.
*/
public JsonWebKey(final Usage usage, final Algorithm algo, final boolean extractable, final String id, final SecretKey secretKey) {
if (algo != null) {
switch (algo) {
case HS256:
case A128KW:
case A128CBC:
break;
default:
throw new MslInternalException("The algorithm must be a symmetric key algorithm.");
}
}
this.type = Type.oct;
this.usage = usage;
this.keyOps = null;
this.algo = algo;
this.extractable = extractable;
this.id = id;
this.keyPair = null;
this.key = secretKey.getEncoded();
this.secretKey = secretKey;
}
/**
* Create a new JSON web key for an RSA public/private key pair with the
* specified attributes. At least one of the public key or private key must
* be encoded.
*
* @param keyOps key operations. May be null.
* @param algo key algorithm. May be null.
* @param extractable true if the key is extractable.
* @param id key ID. May be null.
* @param publicKey RSA public key. May be null.
* @param privateKey RSA private key. May be null.
* @throws MslInternalException if both keys are null or the algorithm
* is incompatible.
*/
public JsonWebKey(final Set<KeyOp> keyOps, final Algorithm algo, final boolean extractable, final String id, final RSAPublicKey publicKey, final RSAPrivateKey privateKey) {
if (publicKey == null && privateKey == null)
throw new MslInternalException("At least one of the public key or private key must be provided.");
if (algo != null) {
switch (algo) {
case RSA1_5:
case RSA_OAEP:
break;
default:
throw new MslInternalException("The algorithm must be an RSA algorithm.");
}
}
this.type = Type.rsa;
this.usage = null;
this.keyOps = (keyOps != null) ? Collections.unmodifiableSet(keyOps) : null;
this.algo = algo;
this.extractable = extractable;
this.id = id;
this.keyPair = new KeyPair(publicKey, privateKey);
this.key = null;
this.secretKey = null;
}
/**
* Create a new JSON web key for a symmetric key with the specified
* attributes.
*
* @param keyOps key operations. May be null.
* @param algo key algorithm. May be null.
* @param extractable true if the key is extractable.
* @param id key ID. May be null.
* @param secretKey symmetric key.
* @throws MslInternalException if the usage or algorithm is incompatible.
*/
public JsonWebKey(final Set<KeyOp> keyOps, final Algorithm algo, final boolean extractable, final String id, final SecretKey secretKey) {
if (algo != null) {
switch (algo) {
case HS256:
case A128KW:
case A128CBC:
break;
default:
throw new MslInternalException("The algorithm must be a symmetric key algorithm.");
}
}
this.type = Type.oct;
this.usage = null;
this.keyOps = (keyOps != null) ? Collections.unmodifiableSet(keyOps) : null;
this.algo = algo;
this.extractable = extractable;
this.id = id;
this.keyPair = null;
this.key = secretKey.getEncoded();
this.secretKey = secretKey;
}
/**
* Create a new JSON web key from the provided MSL object.
*
* @param jsonMo JSON web key MSL object.
* @throws MslCryptoException if the key type is unknown.
* @throws MslEncodingException if there is an error parsing the data.
*/
public JsonWebKey(final MslObject jsonMo) throws MslCryptoException, MslEncodingException {
// Parse JSON object.
final String typeName, usageName, algoName;
final Set<String> keyOpsNames;
try {
typeName = jsonMo.getString(KEY_TYPE);
usageName = jsonMo.has(KEY_USAGE) ? jsonMo.getString(KEY_USAGE) : null;
if (jsonMo.has(KEY_KEY_OPS)) {
keyOpsNames = new HashSet<String>();
final MslArray ma = jsonMo.getMslArray(KEY_KEY_OPS);
for (int i = 0; i < ma.size(); ++i)
keyOpsNames.add(ma.getString(i));
} else {
keyOpsNames = null;
}
algoName = jsonMo.has(KEY_ALGORITHM) ? jsonMo.getString(KEY_ALGORITHM) : null;
extractable = jsonMo.has(KEY_EXTRACTABLE) ? jsonMo.getBoolean(KEY_EXTRACTABLE) : false;
id = jsonMo.has(KEY_KEY_ID) ? jsonMo.getString(KEY_KEY_ID) : null;
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "jwk " + jsonMo, e);
}
// Set values.
try {
type = Type.valueOf(typeName);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_JWK_TYPE, typeName, e);
}
try {
usage = (usageName != null) ? Usage.valueOf(usageName) : null;
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_JWK_USAGE, usageName, e);
}
if (keyOpsNames != null) {
final Set<KeyOp> keyOps = EnumSet.noneOf(KeyOp.class);
for (final String keyOpName : keyOpsNames) {
try {
keyOps.add(KeyOp.valueOf(keyOpName));
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_JWK_KEYOP, usageName, e);
}
}
this.keyOps = Collections.unmodifiableSet(keyOps);
} else {
this.keyOps = null;
}
try {
algo = (algoName != null) ? Algorithm.fromString(algoName) : null;
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_JWK_ALGORITHM, algoName, e);
}
// Reconstruct keys.
try {
// Handle symmetric keys.
if (type == Type.oct) {
key = MslEncoderUtils.b64urlDecode(jsonMo.getString(KEY_KEY));
if (key == null || key.length == 0)
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, "symmetric key is empty");
secretKey = (algo != null) ? new SecretKeySpec(key, algo.getJcaAlgorithmName()) : null;
keyPair = null;
}
// Handle public/private keys (RSA only).
else {
key = null;
final KeyFactory factory = CryptoCache.getKeyFactory("RSA");
// Grab the modulus.
final byte[] n = MslEncoderUtils.b64urlDecode(jsonMo.getString(KEY_MODULUS));
if (n == null || n.length == 0)
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, "modulus is empty");
final BigInteger modulus = new BigInteger(1, n);
// Reconstruct the public key if it exists.
final PublicKey publicKey;
if (jsonMo.has(KEY_PUBLIC_EXPONENT)) {
final byte[] e = MslEncoderUtils.b64urlDecode(jsonMo.getString(KEY_PUBLIC_EXPONENT));
if (e == null || e.length == 0)
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, "public exponent is empty");
final BigInteger exponent = new BigInteger(1, e);
final KeySpec pubkeySpec = new RSAPublicKeySpec(modulus, exponent);
publicKey = factory.generatePublic(pubkeySpec);
} else {
publicKey = null;
}
// Reconstruct the private key if it exists.
final PrivateKey privateKey;
if (jsonMo.has(KEY_PRIVATE_EXPONENT)) {
final byte[] d = MslEncoderUtils.b64urlDecode(jsonMo.getString(KEY_PRIVATE_EXPONENT));
if (d == null || d.length == 0)
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, "private exponent is empty");
final BigInteger exponent = new BigInteger(1, d);
final KeySpec privkeySpec = new RSAPrivateKeySpec(modulus, exponent);
privateKey = factory.generatePrivate(privkeySpec);
} else {
privateKey = null;
}
// Make sure there is at least one key.
if (publicKey == null && privateKey == null)
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "no public or private key");
keyPair = new KeyPair(publicKey, privateKey);
secretKey = null;
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, e);
} catch (final NoSuchAlgorithmException e) {
throw new MslCryptoException(MslError.UNSUPPORTED_JWK_ALGORITHM, e);
} catch (final InvalidKeySpecException e) {
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, e);
}
}
/**
* @return the key type.
*/
public Type getType() {
return type;
}
/**
* @return the permitted key usage or null if not specified.
*/
public Usage getUsage() {
return usage;
}
/**
* @return the permitted key operations or null if not specified.
*/
public Set<KeyOp> getKeyOps() {
return keyOps;
}
/**
* @return the key algorithm or null if not specified.
*/
public Algorithm getAlgorithm() {
return algo;
}
/**
* @return true if the key is allowed to be extracted.
*/
public boolean isExtractable() {
return extractable;
}
/**
* @return the key ID or null if not specified.
*/
public String getId() {
return id;
}
/**
* Returns the stored RSA key pair if the JSON web key type is RSA. The
* public or private key may be null if only one of the pair is stored in
* this JSON web key.
*
* @return the stored RSA key pair or null if the type is not RSA.
*/
public KeyPair getRsaKeyPair() {
return keyPair;
}
/**
* Returns the stored symmetric key if the JSON web key type is OCT and an
* algorithm was specified. Because Java {@code SecretKey} requires a known
* algorithm when it is constructed, the key material may be present when
* this method returns {@code null}.
*
* @return the stored symmetric key or null if the type is not OCT or no
* algorithm was specified.
* @see #getSecretKey(String)
*/
public SecretKey getSecretKey() {
return secretKey;
}
/**
* Returns the stored symmetric key if the JSON web key type is OCT. The
* returned key algorithm will be the one specified by the JSON web key
* algorithm. If no JSON web key algorithm was specified the provided
* algorithm will be used instead.
*
* @param algorithm the symmetric key algorithm to use if one was not
* specified in the JSON web key.
* @return the stored symmetric key or null if the type is not OCT.
* @throws MslCryptoException if the key cannot be constructed.
* @see #getSecretKey()
*/
public SecretKey getSecretKey(final String algorithm) throws MslCryptoException {
// Return the stored symmetric key if it already exists.
if (secretKey != null)
return secretKey;
// Otherwise construct the secret key.
if (key == null)
return null;
try {
return new SecretKeySpec(key, algorithm);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) {
try {
final MslObject mo = encoder.createObject();
// Encode key attributes.
mo.put(KEY_TYPE, type.name());
if (usage != null) mo.put(KEY_USAGE, usage.name());
if (keyOps != null) {
final MslArray keyOpsMa = encoder.createArray();
for (final KeyOp op : keyOps)
keyOpsMa.put(-1, op.name());
mo.put(KEY_KEY_OPS, keyOpsMa);
}
if (algo != null) mo.put(KEY_ALGORITHM, algo.toString());
mo.put(KEY_EXTRACTABLE, extractable);
if (id != null) mo.put(KEY_KEY_ID, id);
// Encode symmetric keys.
if (type == Type.oct) {
mo.put(KEY_KEY, MslEncoderUtils.b64urlEncode(key));
}
// Encode public/private keys (RSA only).
else {
final RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
final RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
// Encode modulus.
final BigInteger modulus = (publicKey != null) ? publicKey.getModulus() : privateKey.getModulus();
final byte[] n = bi2bytes(modulus);
mo.put(KEY_MODULUS, MslEncoderUtils.b64urlEncode(n));
// Encode public key.
if (publicKey != null) {
final BigInteger exponent = publicKey.getPublicExponent();
final byte[] e = bi2bytes(exponent);
mo.put(KEY_PUBLIC_EXPONENT, MslEncoderUtils.b64urlEncode(e));
}
// Encode private key.
if (privateKey != null) {
final BigInteger exponent = privateKey.getPrivateExponent();
final byte[] d = bi2bytes(exponent);
mo.put(KEY_PRIVATE_EXPONENT, MslEncoderUtils.b64urlEncode(d));
}
}
// Return the result.
//
// We will always encode as JSON.
return encoder.encodeObject(mo, MslEncoderFormat.JSON);
} catch (final MslEncoderException e) {
throw new MslInternalException("Error encoding " + this.getClass().getName() + ".", e);
}
}
/** Key type. */
private final Type type;
/** Key usages. */
private final Usage usage;
/** Key operations. */
private final Set<KeyOp> keyOps;
/** Key algorithm. */
private final Algorithm algo;
/** Extractable. */
private final boolean extractable;
/** Key ID. */
private final String id;
/** RSA key pair. May be null. */
private final KeyPair keyPair;
/** Symmetric key raw bytes. May be null. */
private final byte[] key;
/** Symmetric key. May be null. */
private final SecretKey secretKey;
}
| 1,684 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/SymmetricCryptoContext.java
|
/**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.params.KeyParameter;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslUtils;
/**
* A symmetric crypto context performs AES-128 encryption/decryption, AES-128
* key wrap/unwrap, and HMAC-SHA256 or AES-CMAC sign/verify.
*
* @author Wesley Miaw <[email protected]>
*/
public class SymmetricCryptoContext extends ICryptoContext {
/** AES encryption cipher algorithm. */
private static final String AES_ALGO = "AES";
/** AES encryption cipher algorithm. */
private static final String AES_TRANSFORM = AES_ALGO + "/CBC/PKCS5Padding";
/** AES encryption initial value size in bytes. */
private static final int AES_IV_SIZE = 16;
/** HMAC SHA-256 algorithm. */
private static final String HMAC_SHA256_ALGO = "HmacSHA256";
/** AES key wrap cipher algorithm. */
private static final String AESKW_ALGO = "AES";
/** AES key wrap cipher transform. */
private static final String AESKW_TRANSFORM = AESKW_ALGO + "/ECB/NoPadding";
/** AES key wrap block size in bytes. */
private static final int AESKW_BLOCK_SIZE = 8;
/** Key wrap initial value. */
private static final byte[] AESKW_AIV = { (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6 };
/**
* @param bytes number of bytes to return.
* @param w the value.
* @return the specified number of most significant (big-endian) bytes of
* the value.
*/
private static byte[] msb(final int bytes, final byte[] w) {
final byte[] msb = new byte[bytes];
System.arraycopy(w, 0, msb, 0, bytes);
return msb;
}
/**
* @param bytes number of bytes to return.
* @param w the value.
* @return the specified number of least significant (big-endian) bytes of
* the value.
*/
private static byte[] lsb(final int bytes, final byte[] w) {
final int offset = w.length - bytes;
final byte[] lsb = new byte[bytes];
for (int i = 0; i < bytes; ++i)
lsb[i] = w[offset + i];
return lsb;
}
/**
* Modifies the provided byte array by XOR'ing it with the provided value.
* The byte array is processed in big-endian order.
*
* @param b 8-byte value that will be modified.
* @param t the 64-bit value to XOR the value with.
*/
private static void xor(final byte[] b, final long t) {
b[0] ^= t >>> 56;
b[1] ^= t >>> 48;
b[2] ^= t >>> 40;
b[3] ^= t >>> 32;
b[4] ^= t >>> 24;
b[5] ^= t >>> 16;
b[6] ^= t >>> 8;
b[7] ^= t;
}
/**
* <p>Create a new symmetric crypto context using the provided keys.</p>
*
* <p>If there is no encryption key, encryption and decryption is
* unsupported.</p>
*
* <p>If there is no signature key, signing and verification is
* unsupported.</p>
*
* <p>If there is no wrapping key, wrap and unwrap is unsupported.</p>
*
* @param ctx MSL context.
* @param id the key set identity.
* @param encryptionKey the key used for encryption/decryption.
* @param signatureKey the key used for HMAC or CMAC computation.
* @param wrappingKey the key used for wrap/unwrap. */
public SymmetricCryptoContext(final MslContext ctx, final String id, final SecretKey encryptionKey, final SecretKey signatureKey, final SecretKey wrappingKey) {
if (encryptionKey != null && !encryptionKey.getAlgorithm().equals(JcaAlgorithm.AES))
throw new IllegalArgumentException("Encryption key must be an " + JcaAlgorithm.AES + " key.");
if (signatureKey != null &&
!signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256) &&
!signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC))
{
throw new IllegalArgumentException("Encryption key must be an " + JcaAlgorithm.HMAC_SHA256 + " or " + JcaAlgorithm.AES_CMAC + " key.");
}
if (wrappingKey != null && !wrappingKey.getAlgorithm().equals(JcaAlgorithm.AESKW))
throw new IllegalArgumentException("Encryption key must be an " + JcaAlgorithm.AESKW + " key.");
this.ctx = ctx;
this.id = id;
this.encryptionKey = encryptionKey;
this.signatureKey = signatureKey;
this.wrappingKey = wrappingKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (encryptionKey == null)
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED, "no encryption/decryption key");
try {
// Generate IV.
final Random random = ctx.getRandom();
final byte[] iv = new byte[AES_IV_SIZE];
random.nextBytes(iv);
// Encrypt plaintext.
final byte[] ciphertext;
if (data.length != 0) {
final Cipher cipher = CryptoCache.getCipher(AES_TRANSFORM);
final AlgorithmParameterSpec params = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, params);
ciphertext = cipher.doFinal(data);
} else {
ciphertext = new byte[0];
}
// Return encryption envelope byte representation.
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(id, iv, ciphertext);
return envelope.toMslEncoding(encoder, format);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_ENCRYPTION_KEY, e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
} catch (final BadPaddingException e) {
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_ENCODE_ERROR, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (encryptionKey == null)
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED, "no encryption/decryption key");
try {
// Reconstitute encryption envelope.
final MslObject encryptionEnvelopeMo = encoder.parseObject(data);
final MslCiphertextEnvelope encryptionEnvelope = new MslCiphertextEnvelope(encryptionEnvelopeMo, MslCiphertextEnvelope.Version.V1);
// Decrypt ciphertext.
final byte[] ciphertext = encryptionEnvelope.getCiphertext();
if (ciphertext.length == 0)
return new byte[0];
final byte[] iv = encryptionEnvelope.getIv();
final Cipher cipher = CryptoCache.getCipher(AES_TRANSFORM);
final AlgorithmParameterSpec params = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, encryptionKey, params);
return cipher.doFinal(ciphertext);
} catch (final ArrayIndexOutOfBoundsException e) {
throw new MslCryptoException(MslError.INSUFFICIENT_CIPHERTEXT, e);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR, e);
} catch (final MslEncodingException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR, e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_ENCRYPTION_KEY, e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (wrappingKey == null)
throw new MslCryptoException(MslError.WRAP_NOT_SUPPORTED, "no wrap/unwrap key");
if (data.length % 8 != 0)
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "data.length " + data.length);
// Compute alternate initial value.
byte[] a = AESKW_AIV.clone();
final byte[] r = data.clone();
try {
final Cipher cipher = CryptoCache.getCipher(AESKW_TRANSFORM);
cipher.init(Cipher.ENCRYPT_MODE, wrappingKey);
// Initialize variables.
final int n = r.length / AESKW_BLOCK_SIZE;
// Calculate intermediate values.
for (int j = 0; j < 6; ++j) {
for (int i = 1; i <= n; ++i) {
byte[] r_i = Arrays.copyOfRange(r, (i - 1) * AESKW_BLOCK_SIZE, i * AESKW_BLOCK_SIZE);
final byte[] ar_i = Arrays.copyOf(a, a.length + r_i.length);
System.arraycopy(r_i, 0, ar_i, a.length, r_i.length);
final byte[] b = cipher.doFinal(ar_i);
a = msb(AESKW_BLOCK_SIZE, b);
final long t = (n * j) + i;
xor(a, t);
r_i = lsb(AESKW_BLOCK_SIZE, b);
System.arraycopy(r_i, 0, r, (i - 1) * AESKW_BLOCK_SIZE, AESKW_BLOCK_SIZE);
}
}
// Output results.
final byte[] c = new byte[a.length + r.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(r, 0, c, a.length, r.length);
return c;
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_WRAPPING_KEY, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is no padding", e);
} catch (final BadPaddingException e) {
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (wrappingKey == null)
throw new MslCryptoException(MslError.UNWRAP_NOT_SUPPORTED, "no wrap/unwrap key");
if (data.length % 8 != 0)
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, "data.length " + data.length);
try {
final Cipher cipher = CryptoCache.getCipher(AESKW_TRANSFORM);
cipher.init(Cipher.DECRYPT_MODE, wrappingKey);
byte[] a = Arrays.copyOf(data, AESKW_BLOCK_SIZE);
final byte[] r = Arrays.copyOfRange(data, a.length, data.length);
final int n = (data.length - AESKW_BLOCK_SIZE) / AESKW_BLOCK_SIZE;
// Calculate intermediate values.
for (int j = 5; j >= 0; --j) {
for (int i = n; i >= 1; --i) {
final long t = (n * j) + i;
xor(a, t);
byte[] r_i = Arrays.copyOfRange(r, (i - 1) * AESKW_BLOCK_SIZE, i * AESKW_BLOCK_SIZE);
final byte[] ar_i = Arrays.copyOf(a, a.length + r_i.length);
System.arraycopy(r_i, 0, ar_i, a.length, r_i.length);
final byte[] b = cipher.doFinal(ar_i);
a = msb(AESKW_BLOCK_SIZE, b);
r_i = lsb(AESKW_BLOCK_SIZE, b);
System.arraycopy(r_i, 0, r, (i - 1) * AESKW_BLOCK_SIZE, AESKW_BLOCK_SIZE);
}
}
// Output results.
if (MslUtils.safeEquals(a, AESKW_AIV) && r.length % AESKW_BLOCK_SIZE == 0)
return r;
throw new MslCryptoException(MslError.UNWRAP_ERROR, "initial value " + Arrays.toString(a));
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_WRAPPING_KEY, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (signatureKey == null)
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "No signature key.");
try {
// Compute the xMac.
final byte[] xmac;
if (signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256)) {
final Mac mac = CryptoCache.getMac(HMAC_SHA256_ALGO);
mac.init(signatureKey);
xmac = mac.doFinal(data);
} else if (signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC)) {
final CipherParameters params = new KeyParameter(signatureKey.getEncoded());
final BlockCipher aes = new AESEngine();
final CMac mac = new CMac(aes);
mac.init(params);
mac.update(data, 0, data.length);
xmac = new byte[mac.getMacSize()];
mac.doFinal(xmac, 0);
} else {
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "Unsupported algorithm.");
}
// Return the signature envelope byte representation.
return new MslSignatureEnvelope(xmac).getBytes(encoder, format);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid MAC algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_HMAC_KEY, e);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_ENCODE_ERROR, e);
}
}
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
if (signatureKey == null)
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "No signature key.");
try {
// Reconstitute the signature envelope.
final MslSignatureEnvelope envelope = MslSignatureEnvelope.parse(signature, encoder);
// Compute the xMac.
final byte[] xmac;
if (signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256)) {
final Mac mac = CryptoCache.getMac(HMAC_SHA256_ALGO);
mac.init(signatureKey);
xmac = mac.doFinal(data);
} else if (signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC)) {
final CipherParameters params = new KeyParameter(signatureKey.getEncoded());
final BlockCipher aes = new AESEngine();
final CMac mac = new CMac(aes);
mac.init(params);
mac.update(data, 0, data.length);
xmac = new byte[mac.getMacSize()];
mac.doFinal(xmac, 0);
} else {
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "Unsupported algorithm.");
}
// Compare the computed hash to the provided signature.
return MslUtils.safeEquals(xmac, envelope.getSignature());
} catch (final MslEncodingException e) {
throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_PARSE_ERROR, e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid MAC algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_HMAC_KEY, e);
}
}
/** MSL context. */
protected final MslContext ctx;
/** Key set identity. */
protected final String id;
/** Encryption/decryption key. */
protected final SecretKey encryptionKey;
/** Signature key. */
protected final SecretKey signatureKey;
/** Wrapping key. */
protected final SecretKey wrappingKey;
}
| 1,685 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/Base64.java
|
/**
* Copyright (c) 2016 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.regex.Pattern;
/**
* <p>Base64 encoder/decoder. Can be configured with a backing
* implementation.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class Base64 {
/** Whitespace regular expression. */
private static final String WHITESPACE_REGEX = "\\s";
/** Base64 validation regular expression. */
private static final Pattern BASE64_PATTERN = Pattern.compile("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$");
/**
* <p>Validates that a string is a valid Base64 encoding. This uses a
* regular expression to perform the check. The empty string is also
* considered valid. All whitespace is ignored.</p>
*
* @param s the string to validate.
* @return true if the string is a valid Base64 encoding.
*/
public static boolean isValidBase64(final String s) {
final String sanitized = s.replaceAll(WHITESPACE_REGEX, "");
return BASE64_PATTERN.matcher(sanitized).matches();
}
/**
* <p>A Base64 encoder/decoder implementation. Implementations must be
* thread-safe.</p>
*/
public static interface Base64Impl {
/**
* <p>Base64 encodes binary data.</p>
*
* @param b the binary data.
* @return the Base64-encoded binary data.
*/
public String encode(final byte[] b);
/**
* <p>Decodes a Base64-encoded string into its binary form.</p>
*
* @param s the Base64-encoded string.
* @return the binary data.
* @throws IllegalArgumentException if the argument is not a valid
* Base64-encoded string. The empty string is considered valid.
* @see Base64#isValidBase64(String)
*/
public byte[] decode(final String s);
}
/**
* Set the backing implementation.
*
* @param impl the backing implementation.
* @throws NullPointerException if the implementation is {@code null}.
*/
public static void setImpl(final Base64Impl impl) {
if (impl == null)
throw new NullPointerException("Base64 implementation cannot be null.");
Base64.impl = impl;
}
/**
* <p>Base64 encodes binary data.</p>
*
* @param b the binary data.
* @return the Base64-encoded binary data.
*/
public static String encode(final byte[] b) {
return impl.encode(b);
}
/**
* <p>Decodes a Base64-encoded string into its binary form.</p>
*
* @param s the Base64-encoded string.
* @return the binary data.
* @throws IllegalArgumentException if the argument is not a valid Base64-
* encoded string.
*/
public static byte[] decode(final String s) {
// Delegate validation of the argument to the implementation.
return impl.decode(s);
}
/** The backing implementation. */
private static Base64Impl impl = new Base64Secure();
}
| 1,686 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/Base64Jaxb.java
|
/**
* Copyright (c) 2016 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import javax.xml.bind.DatatypeConverter;
import com.netflix.msl.util.Base64.Base64Impl;
/**
* <p>Base64 encoder/decoder implementation that uses the JAXB {@link DatatypeConverter}
*
* @author Wesley Miaw <[email protected]>
*/
public class Base64Jaxb implements Base64Impl {
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#encode(byte[])
*/
@Override
public String encode(final byte[] b) {
return DatatypeConverter.printBase64Binary(b);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#decode(java.lang.String)
*/
@Override
public byte[] decode(final String s) {
if (!Base64.isValidBase64(s))
throw new IllegalArgumentException("Invalid Base64 encoded string: " + s);
return DatatypeConverter.parseBase64Binary(s);
}
}
| 1,687 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/MslUtils.java
|
/**
* Copyright (c) 2013-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.Random;
import com.netflix.msl.MslConstants;
/**
* Utility methods.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslUtils {
/**
* Safely compares two byte arrays to prevent timing attacks.
*
* @param a first array for the comparison.
* @param b second array for the comparison.
* @return true if the arrays are equal, false if they are not.
*/
public static boolean safeEquals(final byte[] a, final byte[] b) {
if (a.length != b.length)
return false;
int result = 0;
for (int i = 0; i < a.length; ++i)
result |= a[i] ^ b[i];
return result == 0;
}
/**
* Return true if the number is a non-negative power of two. Zero is
* considered a power of two and will return true.
*
* @param n the number to test.
* @return true if the number is a non-negative power of two.
*/
private static boolean isPowerOf2(final long n) {
// If the number is a power of two, a binary AND operation between
// the number and itself minus one will equal zero.
if (n < 0) return false;
if (n == 0) return true;
return (n & (n - 1)) == 0;
}
/**
* Returns a random number between zero and the maximum long value as
* defined by {@link MslConstants#MAX_LONG_VALUE}, inclusive.
*
* @param ctx MSL context.
* @return a random number between zero and the maximum long value,
* inclusive.
*/
public static long getRandomLong(final MslContext ctx) {
// If the maximum long value is a power of 2, then we can perform a
// bitmask on the randomly generated long value to restrict to our
// target number space.
final boolean isPowerOf2 = MslUtils.isPowerOf2(MslConstants.MAX_LONG_VALUE);
// Generate the random value.
final Random r = ctx.getRandom();
long n = -1;
do {
n = r.nextLong();
// Perform a bitmask if permitted, which will force this loop
// to exit immediately.
if (isPowerOf2)
n &= (MslConstants.MAX_LONG_VALUE - 1);
} while (n < 0 || n > MslConstants.MAX_LONG_VALUE);
// Return the random value.
return n;
}
}
| 1,688 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/MslStore.java
|
/**
* Copyright (c) 2012-2020 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.Set;
import com.netflix.msl.MslException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
/**
* <p>The Message Security Layer store manages the local store of master tokens
* identifying the local entity, user ID tokens identifying local users, and
* all service tokens issued by the local entity or remote entities. It also
* provides methods for identifying the tokens that should be included in a
* message and accessing crypto contexts associated with master tokens.<p>
*
* <p>Applications may wish to ensure the store contains only the newest master
* token and user ID tokens for the known users at application startup and
* shutdown.</p>
*
* <p>Implementations must be thread-safe.</p>
*
* @see MslContext
* @author Wesley Miaw <[email protected]>
*/
public interface MslStore {
/**
* Save a master token and its associated crypto context. This replaces any
* existing association. Passing in a null crypto context is the same as
* calling {@link #removeCryptoContext(MasterToken)}.
*
* @param masterToken the master token.
* @param cryptoContext the crypto context. May be null.
*/
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext);
/**
* Return the newest saved master token in this store.
*
* @return the newest saved master token or null.
*/
public MasterToken getMasterToken();
/**
* Return the next non-replayable ID of the provided master token.
*
* The initial number is one (1). Each call to this function should return
* the next largest number. The next largest number after
* {@link com.netflix.msl.MslConstants#MAX_LONG_VALUE} is zero (0).
*
* @return the next non-replayable ID.
*/
public long getNonReplayableId(final MasterToken masterToken);
/**
* Return the crypto context associated with the provided master token.
*
* @param masterToken the master token.
* @return the crypto context for the master token or null if not found.
*/
public ICryptoContext getCryptoContext(final MasterToken masterToken);
/**
* Remove a master token and its associated crypto context. This also
* removes any stored user ID tokens and service tokens that are no longer
* bound to a known master token.
*
* @param masterToken the master token.
*/
public void removeCryptoContext(final MasterToken masterToken);
/**
* Removes all master tokens and crypto contexts and bound user ID tokens
* and their bound service tokens.
*/
public void clearCryptoContexts();
/**
* Add a user ID token to the store, replacing any existing user ID token
* of the same user. The local user ID has no meeting external to the
* store.
*
* @param userId local user ID.
* @param userIdToken the user ID token.
* @throws MslException if the user ID token is not bound to any stored
* master token.
*/
public void addUserIdToken(final String userId, final UserIdToken userIdToken) throws MslException;
/**
* Returns the user ID token, if any, for the specified local user ID.
*
* @param userId local user ID.
* @return the user ID token for the local user ID or null.
*/
public UserIdToken getUserIdToken(final String userId);
/**
* Remove a user ID token. This also removes any service tokens no longer
* bound to a known user ID token.
*
* @param userIdToken the user ID token.
*/
public void removeUserIdToken(final UserIdToken userIdToken);
/**
* Removes all user ID tokens and user ID token bound service tokens.
*/
public void clearUserIdTokens();
/**
* <p>Add a set of service tokens to the store.</p>
*
* <p>Either all or none of the provided service tokens will be added.</p>
*
* @param tokens the service tokens.
* @throws MslException if a service token is master token bound to a
* master token not found in the store or if a service token is
* user ID token bound to a user ID token not found in the store.
*/
public void addServiceTokens(final Set<ServiceToken> tokens) throws MslException;
/**
* <p>Return the set of service tokens that are applicable to the provided
* pair of master token and user ID token. The base set consists of the
* service tokens that are not bound to any master token or user ID
* token.</p>
*
* <p>If a master token is provided, the service tokens that are bound to
* the master token and not bound to any user ID token are also
* provided.</p>
*
* <p>If a master token and user ID token is provided, the service tokens
* that are bound to both the master token and user ID token are also
* provided.</p>
*
* @param masterToken the master token. May be null.
* @param userIdToken the user ID token. May be null.
* @return the set of service tokens applicable to the message.
* @throws MslException if the user ID token is not bound to the master
* token or a user ID token is provided without also providing a
* master token.
*/
public Set<ServiceToken> getServiceTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslException;
/**
* <p>Remove all service tokens matching all the specified parameters. A
* null value for the master token or user ID token restricts removal to
* tokens that are not bound to a master token or not bound to a user ID
* token respectively.</p>
*
* <p>For example, if a name and master token is provided, only tokens with
* that name, bound to that master token, and not bound to a user ID token
* are removed. If only a user ID token is provided, all tokens bound to
* that user ID token are removed.</p>
*
* <p>If no parameters are provided, no tokens are removed.</p>
*
* @param name service token name. May be null.
* @param masterToken master token. May be null.
* @param userIdToken user ID token. May be null.
* @throws MslException if the user ID token is not bound to the master
* token.
*/
public void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException;
/**
* Removes all service tokens.
*/
public void clearServiceTokens();
}
| 1,689 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/Base64Secure.java
|
/**
* Copyright (c) 2016-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.nio.charset.StandardCharsets;
import com.netflix.msl.util.Base64.Base64Impl;
/**
* <p>Base64 encoder/decoder implementation that strictly enforces the validity
* of the encoding and does not exit early if an error is encountered.
* Whitespace (space, tab, newline, carriage return) are skipped.</p>
*
* <p>Based upon {@link javax.xml.bind.DatatypeConverter}.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class Base64Secure implements Base64Impl {
/** The encode map. */
private static final char[] ENCODE_MAP = initEncodeMap();
/** The decode map. */
private static final byte[] DECODE_MAP = initDecodeMap();
/** Tab character value. */
private static final byte TAB = 9;
/** Newline character value. */
private static final byte NEWLINE = 10;
/** Carriage return character value. */
private static final byte CARRIAGE_RETURN = 13;
/** Space character value. */
private static final byte SPACE = 32;
/** Padding character sentinel value. */
private static final byte PADDING = 127;
/**
* @return the 64-character Base64 encode map.
*/
private static char[] initEncodeMap() {
final char[] map = new char[64];
for (int i = 0; i < 26; i++)
map[i] = (char)('A' + i);
for (int i = 26; i < 52; i++)
map[i] = (char)('a' + (i - 26));
for (int i = 52; i < 62; i++)
map[i] = (char)('0' + (i - 52));
map[62] = '+';
map[63] = '/';
return map;
}
/**
* @return the 128-byte Base64 decode map.
*/
private static byte[] initDecodeMap() {
final byte[] map = new byte[128];
for (int i = 0; i < 128; i++)
map[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
map[i] = (byte)(i - 'A');
for (int i = 'a'; i <= 'z'; i++)
map[i] = (byte)(i - 'a' + 26);
for (int i = '0'; i <= '9'; i++)
map[i] = (byte)(i - '0' + 52);
map['+'] = 62;
map['/'] = 63;
map['='] = PADDING;
return map;
}
/**
* @param i the value to encode.
* @return the character the value maps onto.
*/
private static char encode(final int i) {
return ENCODE_MAP[i & 0x3F];
}
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#encode(byte[])
*/
@Override
public String encode(final byte[] b) {
// Allocate the character buffer.
final char[] buf = new char[((b.length + 2) / 3) * 4];
int ptr = 0;
// Encode elements until there are only 1 or 2 left.
int remaining = b.length;
int i;
for (i = 0; remaining >= 3; remaining -= 3, i += 3) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i] & 0x3) << 4) | ((b[i+1] >> 4) & 0xF));
buf[ptr++] = encode(((b[i + 1] & 0xF) << 2) | ((b[i + 2] >> 6) & 0x3));
buf[ptr++] = encode(b[i + 2] & 0x3F);
}
// If there is one final element...
if (remaining == 1) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i]) & 0x3) << 4);
buf[ptr++] = '=';
buf[ptr++] = '=';
}
// If there are two final elements...
else if (remaining == 2) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i] & 0x3) << 4) | ((b[i + 1] >> 4) & 0xF));
buf[ptr++] = encode((b[i + 1] & 0xF) << 2);
buf[ptr++] = '=';
}
// Return the encoded string.
return new String(buf);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#decode(java.lang.String)
*/
@Override
public byte[] decode(final String s) {
// Flag to remember if we've encountered an invalid character or have
// reached the end of the string prematurely.
boolean invalid = false;
// Convert string to ISO 8859-1 bytes.
final byte[] sb = s.getBytes(StandardCharsets.ISO_8859_1);
// Allocate the destination buffer, which may be too large due to
// whitespace.
final int strlen = sb.length;
final int outlen = strlen * 3 / 4;
final byte[] out = new byte[outlen];
int o = 0;
// Convert each quadruplet to three bytes.
final byte[] quadruplet = new byte[4];
int q = 0;
boolean lastQuad = false;
for (int i = 0; i < strlen; ++i) {
final byte c = sb[i];
// Ensure the character is not "negative".
if (c < 0) {
invalid = true;
continue;
}
// Lookup the character in the decoder map.
final byte b = DECODE_MAP[c];
// Skip invalid characters.
if (b == -1) {
// Flag invalid for non-whitespace.
if (c != SPACE && c != TAB && c != NEWLINE && c != CARRIAGE_RETURN)
invalid = true;
continue;
}
// If we already saw the last quadruplet, we shouldn't see anymore.
if (lastQuad)
invalid = true;
// Append value to quadruplet.
quadruplet[q++] = b;
// If the quadruplet is full, append it to the destination buffer.
if (q == 4) {
// If the quadruplet starts with padding, flag invalid.
if (quadruplet[0] == PADDING || quadruplet[1] == PADDING)
invalid = true;
// If the quadruplet ends with padding, this better be the last
// quadruplet.
if (quadruplet[2] == PADDING || quadruplet[3] == PADDING)
lastQuad = true;
// Decode into the destination buffer.
out[o++] = (byte)((quadruplet[0] << 2) | (quadruplet[1] >> 4));
if (quadruplet[2] != PADDING)
out[o++] = (byte)((quadruplet[1] << 4) | (quadruplet[2] >> 2));
if (quadruplet[3] != PADDING)
out[o++] = (byte)((quadruplet[2] << 6) | (quadruplet[3]));
// Reset the quadruplet index.
q = 0;
}
}
// If the quadruplet is not empty, flag invalid.
if (q != 0)
invalid = true;
// If invalid throw an exception.
if (invalid)
throw new IllegalArgumentException("Invalid Base64 encoded string: " + s);
// Always copy the destination buffer into the return buffer to
// maintain consistent runtime.
final byte[] ret = new byte[o];
System.arraycopy(out, 0, ret, 0, o);
return ret;
}
}
| 1,690 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/NullAuthenticationUtils.java
|
/**
* Copyright (c) 2016 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationScheme;
/**
* <p>An authentication utilities implementation where all operations are
* permitted.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class NullAuthenticationUtils implements AuthenticationUtils {
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isEntityRevoked(java.lang.String)
*/
@Override
public boolean isEntityRevoked(final String identity) {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.entityauth.EntityAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final EntityAuthenticationScheme scheme) {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.userauth.UserAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final UserAuthenticationScheme scheme) {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.tokens.MslUser, com.netflix.msl.userauth.UserAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final MslUser user, final UserAuthenticationScheme scheme) {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.keyx.KeyExchangeScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final KeyExchangeScheme scheme) {
return true;
}
}
| 1,691 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/MslCompression.java
|
/**
* Copyright (c) 2017-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.io.LZWInputStream;
import com.netflix.msl.io.LZWOutputStream;
/**
* <p>Data compression and uncompression. Can be configured with a backing
* implementation.</p>
*
* <p>This class is thread-safe.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslCompression {
/** Registered compression implementations. */
private static Map<CompressionAlgorithm,CompressionImpl> impls = new ConcurrentHashMap<CompressionAlgorithm,CompressionImpl>();
/** Maximum deflate ratio. Volatile should be good enough. */
private static volatile int maxDeflateRatio = 200;
/**
* <p>A data compression implementation. Implementations must be thread-
* safe.</p>
*/
public static interface CompressionImpl {
/**
* <p>Compress the provided data.</p>
*
* @param data the data to compress.
* @return the compressed data. May also return {@code null} if the
* compressed data would exceed the original data size.
* @throws IOException if there is an error compressing the data.
*/
public byte[] compress(final byte[] data) throws IOException;
/**
* <p>Uncompress the provided data.</p>
*
* <p>If the uncompressed data ever exceeds the maximum deflate ratio
* then uncompression must abort and an exception thrown.</p>
*
* @param data the data to uncompress.
* @param maxDeflateRatio the maximum deflate ratio.
* @return the uncompressed data.
* @throws IOException if there is an error uncompressing the data or
* if the ratio of uncompressed data to the compressed data
* ever exceeds the specified deflate ratio.
*/
public byte[] uncompress(final byte[] data, final int maxDeflateRatio) throws IOException;
}
/**
* Default GZIP compression implementation.
*/
private static class GzipCompressionImpl implements CompressionImpl {
/* (non-Javadoc)
* @see com.netflix.msl.util.MslCompression.CompressionImpl#compress(byte[])
*/
@Override
public byte[] compress(final byte[] data) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
final GZIPOutputStream gzos = new GZIPOutputStream(baos);
try {
gzos.write(data);
} finally {
gzos.close();
}
return baos.toByteArray();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslCompression.CompressionImpl#uncompress(byte[], int)
*/
@Override
public byte[] uncompress(final byte[] data, final int maxDeflateRatio) throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(data);
final GZIPInputStream gzis = new GZIPInputStream(bais);
try {
final byte[] buffer = new byte[data.length];
final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
while (buffer.length > 0) {
// Uncompress.
final int bytesRead = gzis.read(buffer);
if (bytesRead == -1) break;
// Check if the deflate ratio has been exceeded.
if (baos.size() + bytesRead > maxDeflateRatio * data.length)
throw new IOException("Deflate ratio " + maxDeflateRatio + " exceeded. Aborting uncompression.");
// Save the uncompressed data for return.
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
} finally {
gzis.close();
}
}
}
/**
* Default LZW compression implementation.
*/
private static class LzwCompressionImpl implements CompressionImpl {
/* (non-Javadoc)
* @see com.netflix.msl.util.MslCompression.CompressionImpl#compress(byte[])
*/
@Override
public byte[] compress(final byte[] data) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
final LZWOutputStream lzwos = new LZWOutputStream(baos);
try {
lzwos.write(data);
} finally {
lzwos.close();
}
return baos.toByteArray();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslCompression.CompressionImpl#uncompress(byte[], int)
*/
@Override
public byte[] uncompress(final byte[] data, final int maxDeflateRatio) throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(data);
final LZWInputStream lzwis = new LZWInputStream(bais);
try {
final byte[] buffer = new byte[data.length];
final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
while (buffer.length > 0) {
// Uncompress.
final int bytesRead = lzwis.read(buffer);
if (bytesRead == -1) break;
// Check if the deflate ratio has been exceeded.
if (baos.size() + bytesRead > maxDeflateRatio * data.length)
throw new IOException("Deflate ratio " + maxDeflateRatio + " exceeded. Aborting uncompression.");
// Save the uncompressed data for return.
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
} finally {
lzwis.close();
}
}
}
static {
MslCompression.register(CompressionAlgorithm.GZIP, new GzipCompressionImpl());
MslCompression.register(CompressionAlgorithm.LZW, new LzwCompressionImpl());
}
/**
* <p>Register a compression algorithm implementation. Pass {@code null} to
* remove an implementation.</p>
*
* @param algo the compression algorithm.
* @param impl the data compression implementation. May be {@code null}.
*/
public static void register(final CompressionAlgorithm algo, final CompressionImpl impl) {
if (impl == null)
impls.remove(algo);
else
impls.put(algo, impl);
}
/**
* <p>Sets the maximum deflate ratio used during uncompression. If the
* ratio is exceeded uncompression will abort.</p>
*
* @param deflateRatio the maximum deflate ratio.
* @throws IllegalArgumentException if the specified ratio is less than
* one.
*/
public static void setMaxDeflateRatio(final int deflateRatio) {
if (deflateRatio < 1)
throw new IllegalArgumentException("The maximum deflate ratio must be at least one.");
MslCompression.maxDeflateRatio = deflateRatio;
}
/**
* Compress the provided data using the specified compression algorithm.
*
* @param compressionAlgo the compression algorithm.
* @param data the data to compress.
* @return the compressed data or null if the compressed data would be larger than the
* uncompressed data.
* @throws MslException if there is an error compressing the data.
*/
public static byte[] compress(final CompressionAlgorithm compressionAlgo, final byte[] data) throws MslException {
final CompressionImpl impl = impls.get(compressionAlgo);
if (impl == null)
throw new MslException(MslError.UNSUPPORTED_COMPRESSION, compressionAlgo.name());
try {
final byte[] compressed = impl.compress(data);
return (compressed != null && compressed.length < data.length) ? compressed : null;
} catch (final IOException e) {
throw new MslException(MslError.COMPRESSION_ERROR, "algo " + compressionAlgo.name(), e);
}
}
/**
* Uncompress the provided data using the specified compression algorithm.
*
* @param compressionAlgo the compression algorithm.
* @param data the data to uncompress.
* @return the uncompressed data.
* @throws MslException if there is an error uncompressing the data.
*/
public static byte[] uncompress(final CompressionAlgorithm compressionAlgo, final byte[] data) throws MslException {
final CompressionImpl impl = impls.get(compressionAlgo);
if (impl == null)
throw new MslException(MslError.UNSUPPORTED_COMPRESSION, compressionAlgo.name());
try {
return impl.uncompress(data, maxDeflateRatio);
} catch (final IOException e) {
throw new MslException(MslError.UNCOMPRESSION_ERROR, "algo " + compressionAlgo.name(), e);
}
}
}
| 1,692 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/SimpleMslStore.java
|
/**
* Copyright (c) 2012-2020 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
/**
* <p>A simple MSL store that maintains state.</p>
*
* <p>This class is thread-safe.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleMslStore implements MslStore {
/**
* Increments the provided non-replayable ID by 1, wrapping around to zero
* if the provided value is equal to {@link MslConstants#MAX_LONG_VALUE}.
*
* @param id the non-replayable ID to increment.
* @return the non-replayable ID + 1.
* @throws MslInternalException if the provided non-replayable ID is out of
* range.
*/
private static long incrementNonReplayableId(final long id) {
if (id < 0 || id > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Non-replayable ID " + id + " is outside the valid range.");
return (id == MslConstants.MAX_LONG_VALUE) ? 0 : id + 1;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#setCryptoContext(com.netflix.msl.tokens.MasterToken, com.netflix.msl.crypto.ICryptoContext)
*/
@Override
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext) {
if (cryptoContext == null)
removeCryptoContext(masterToken);
else
cryptoContexts.put(masterToken, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getMasterToken()
*/
@Override
public MasterToken getMasterToken() {
MasterToken masterToken = null;
for (final MasterToken storedMasterToken : cryptoContexts.keySet()) {
if (masterToken == null || storedMasterToken.isNewerThan(masterToken))
masterToken = storedMasterToken;
}
return masterToken;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getNonReplayableId(com.netflix.msl.tokens.MasterToken)
*/
@Override
public synchronized long getNonReplayableId(final MasterToken masterToken) {
// Return the next largest non-replayable ID, or 1 if there is none.
final long serialNumber = masterToken.getSerialNumber();
final long currentId = (nonReplayableIds.containsKey(serialNumber))
? nonReplayableIds.get(serialNumber)
: 0;
final long nextId = incrementNonReplayableId(currentId);
nonReplayableIds.put(serialNumber, nextId);
return nextId;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getCryptoContext(com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MasterToken masterToken) {
return cryptoContexts.get(masterToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeCryptoContext(com.netflix.msl.tokens.MasterToken)
*/
@Override
public synchronized void removeCryptoContext(final MasterToken masterToken) {
// We must perform the removal operations in reverse-dependency order.
// This ensures the store is in the correct state, allowing all logical
// and safety checks to pass.
//
// First any bound user ID tokens are removed (which first removes any
// service tokens bound to those user ID tokens), then bound service
// tokens, and finally the non-replayable ID and crypto context and
// master token pair.
if (cryptoContexts.containsKey(masterToken)) {
// Look for a second master token with the same serial number. If
// there is one, then just remove this master token and its crypto
// context but do not remove any bound user ID tokens, service
// tokens, or the non-replayable ID as those are still associated
// with the master token that remains.
final long serialNumber = masterToken.getSerialNumber();
for (final MasterToken token : cryptoContexts.keySet()) {
if (!token.equals(masterToken) && token.getSerialNumber() == serialNumber) {
cryptoContexts.remove(masterToken);
return;
}
}
// Remove bound user ID tokens and service tokens.
for (final UserIdToken userIdToken : userIdTokens.values()) {
if (userIdToken.isBoundTo(masterToken))
removeUserIdToken(userIdToken);
}
try {
removeServiceTokens(null, masterToken, null);
} catch (final MslException e) {
// This should not happen since we are only providing a master
// token.
throw new MslInternalException("Unexpected exception while removing master token bound service tokens.", e);
}
// Remove the non-replayable ID.
nonReplayableIds.remove(serialNumber);
// Finally remove the crypto context.
cryptoContexts.remove(masterToken);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearCryptoContexts()
*/
@Override
public synchronized void clearCryptoContexts() {
cryptoContexts.clear();
nonReplayableIds.clear();
userIdTokens.clear();
uitServiceTokens.clear();
mtServiceTokens.clear();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#addUserIdToken(java.lang.String, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void addUserIdToken(final String userId, final UserIdToken userIdToken) throws MslException {
boolean foundMasterToken = false;
for (final MasterToken masterToken : cryptoContexts.keySet()) {
if (userIdToken.isBoundTo(masterToken)) {
foundMasterToken = true;
break;
}
}
if (!foundMasterToken)
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_NOT_FOUND, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber());
userIdTokens.put(userId, userIdToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getUserIdToken(java.lang.String)
*/
@Override
public UserIdToken getUserIdToken(final String userId) {
return userIdTokens.get(userId);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void removeUserIdToken(final UserIdToken userIdToken) {
// Find the master token this user ID token is bound to.
MasterToken masterToken = null;
for (final MasterToken token : cryptoContexts.keySet()) {
if (userIdToken.isBoundTo(token)) {
masterToken = token;
break;
}
}
// If we didn't find a master token we shouldn't be able to find a user
// ID token, but it doesn't hurt to try anyway and clean things up.
for (final Entry<String,UserIdToken> entry : userIdTokens.entrySet()) {
if (entry.getValue().equals(userIdToken)) {
try {
removeServiceTokens(null, masterToken, userIdToken);
} catch (final MslException e) {
// This should not happen since we have already confirmed
// that the user ID token is bound to the master token.
throw new MslInternalException("Unexpected exception while removing user ID token bound service tokens.", e);
}
final String userId = entry.getKey();
userIdTokens.remove(userId);
break;
}
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearUserIdTokens()
*/
@Override
public void clearUserIdTokens() {
final List<UserIdToken> tokens = new ArrayList<UserIdToken>(userIdTokens.values());
for (final UserIdToken token : tokens)
removeUserIdToken(token);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#addServiceTokens(java.util.Set)
*/
@Override
public synchronized void addServiceTokens(final Set<ServiceToken> tokens) throws MslException {
// Verify we recognize the bound service tokens.
for (final ServiceToken token : tokens) {
// Verify master token bound.
if (token.isMasterTokenBound()) {
boolean foundMasterToken = false;
for (final MasterToken masterToken : cryptoContexts.keySet()) {
if (token.isBoundTo(masterToken)) {
foundMasterToken = true;
break;
}
}
if (!foundMasterToken)
throw new MslException(MslError.SERVICETOKEN_MASTERTOKEN_NOT_FOUND, "st mtserialnumber " + token.getMasterTokenSerialNumber());
}
// Verify user token bound.
if (token.isUserIdTokenBound()) {
boolean foundUserIdToken = false;
for (final UserIdToken userIdToken : userIdTokens.values()) {
if (token.isBoundTo(userIdToken)) {
foundUserIdToken = true;
break;
}
}
if (!foundUserIdToken)
throw new MslException(MslError.SERVICETOKEN_USERIDTOKEN_NOT_FOUND, "st uitserialnumber " + token.getUserIdTokenSerialNumber());
}
}
// Add service tokens.
for (final ServiceToken token : tokens) {
// Unbound?
if (token.isUnbound()) {
unboundServiceTokens.add(token);
continue;
}
// Master token bound?
if (token.isMasterTokenBound()) {
Set<ServiceToken> tokenSet = mtServiceTokens.get(token.getMasterTokenSerialNumber());
if (tokenSet == null) {
tokenSet = new HashSet<ServiceToken>();
mtServiceTokens.put(token.getMasterTokenSerialNumber(), tokenSet);
}
tokenSet.add(token);
}
// User ID token bound?
if (token.isUserIdTokenBound()) {
Set<ServiceToken> tokenSet = uitServiceTokens.get(token.getUserIdTokenSerialNumber());
if (tokenSet == null) {
tokenSet = new HashSet<ServiceToken>();
uitServiceTokens.put(token.getUserIdTokenSerialNumber(), tokenSet);
}
tokenSet.add(token);
}
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getServiceTokens(com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public synchronized Set<ServiceToken> getServiceTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
// Validate arguments.
if (userIdToken != null) {
if (masterToken == null)
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_NULL);
if (!userIdToken.isBoundTo(masterToken))
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber() + "; mt " + masterToken.getSerialNumber());
}
// Grab service tokens. We start with the set of unbound service
// tokens.
final Set<ServiceToken> serviceTokens = new HashSet<ServiceToken>();
serviceTokens.addAll(unboundServiceTokens);
// If we have a master token add the set of master token bound service
// tokens that are not bound to any user ID tokens.
if (masterToken != null) {
final Set<ServiceToken> mtTokens = mtServiceTokens.get(masterToken.getSerialNumber());
if (mtTokens != null) {
for (final ServiceToken mtToken : mtTokens) {
if (!mtToken.isUserIdTokenBound())
serviceTokens.add(mtToken);
}
}
}
// If we have a user ID token (and because of the check above a master
// token) add the set of user ID token bound service tokens that are
// also bound to the same master token.
if (userIdToken != null) {
final Set<ServiceToken> uitTokens = uitServiceTokens.get(userIdToken.getSerialNumber());
if (uitTokens != null) {
for (final ServiceToken uitToken : uitTokens) {
if (uitToken.isBoundTo(masterToken))
serviceTokens.add(uitToken);
}
}
}
return serviceTokens;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeServiceTokens(java.lang.String, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public synchronized void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
// Validate arguments.
if (userIdToken != null && masterToken != null &&
!userIdToken.isBoundTo(masterToken))
{
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber() + "; mt " + masterToken.getSerialNumber());
}
// If only a name was provided remove all unbound tokens with that
// name.
if (name != null && masterToken == null && userIdToken == null) {
// Remove all unbound tokens with the specified name.
final Iterator<ServiceToken> unboundTokens = unboundServiceTokens.iterator();
while (unboundTokens.hasNext()) {
if (unboundTokens.next().getName().equals(name))
unboundTokens.remove();
}
}
// If a master token was provided but no user ID token was provided,
// remove all tokens bound to the master token. If a name was also
// provided then limit removal to tokens with the specified name.
if (masterToken != null && userIdToken == null) {
final Set<ServiceToken> tokenSet = mtServiceTokens.get(masterToken.getSerialNumber());
if (tokenSet != null) {
final Iterator<ServiceToken> tokens = tokenSet.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
// Skip if the name was provided and it does not match.
if (name != null && !token.getName().equals(name))
continue;
// Remove the token.
tokens.remove();
}
}
}
// If a user ID token was provided remove all tokens bound to the user
// ID token. If a name was also provided then limit removal to tokens
// with the specified name.
if (userIdToken != null) {
final Set<ServiceToken> tokenSet = uitServiceTokens.get(userIdToken.getSerialNumber());
if (tokenSet != null) {
final Iterator<ServiceToken> tokens = tokenSet.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
// Skip if the name was provided and it does not match.
if (name != null && !token.getName().equals(name))
continue;
// Remove the token.
tokens.remove();
}
}
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearServiceTokens()
*/
@Override
public synchronized void clearServiceTokens() {
unboundServiceTokens.clear();
mtServiceTokens.clear();
uitServiceTokens.clear();
}
/** Map of master tokens onto crypto contexts. */
private final Map<MasterToken,ICryptoContext> cryptoContexts = new ConcurrentHashMap<MasterToken,ICryptoContext>();
/** Map of local user IDs onto User ID tokens. */
private final Map<String,UserIdToken> userIdTokens = new ConcurrentHashMap<String,UserIdToken>();
/** Map of master token serial numbers onto non-replayable IDs. */
private final Map<Long,Long> nonReplayableIds = new HashMap<Long,Long>();
/** Set of unbound service tokens. */
private final Set<ServiceToken> unboundServiceTokens = new HashSet<ServiceToken>();
/** Map of master token serial numbers onto service tokens. */
private final Map<Long,Set<ServiceToken>> mtServiceTokens = new HashMap<Long,Set<ServiceToken>>();
/** Map of user ID token serial numbers onto service tokens. */
private final Map<Long,Set<ServiceToken>> uitServiceTokens = new HashMap<Long,Set<ServiceToken>>();
}
| 1,693 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/NullMslStore.java
|
/**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.Collections;
import java.util.Set;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
/**
* <p>A MSL store where all operations are no-ops.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class NullMslStore implements MslStore {
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#setCryptoContext(com.netflix.msl.tokens.MasterToken, com.netflix.msl.crypto.ICryptoContext)
*/
@Override
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getMasterToken()
*/
@Override
public MasterToken getMasterToken() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getNonReplayableId(com.netflix.msl.tokens.MasterToken)
*/
@Override
public long getNonReplayableId(final MasterToken masterToken) {
return 1;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getCryptoContext(com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MasterToken masterToken) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeCryptoContext(com.netflix.msl.tokens.MasterToken)
*/
@Override
public void removeCryptoContext(final MasterToken masterToken) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearCryptoContexts()
*/
@Override
public void clearCryptoContexts() {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#addUserIdToken(java.lang.String, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void addUserIdToken(final String userId, final UserIdToken userIdToken) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getUserIdToken(java.lang.String)
*/
@Override
public UserIdToken getUserIdToken(final String userId) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void removeUserIdToken(final UserIdToken userIdToken) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearUserIdTokens()
*/
@Override
public void clearUserIdTokens() {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#addServiceTokens(java.util.Set)
*/
@Override
public void addServiceTokens(final Set<ServiceToken> tokens) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getServiceTokens(com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public Set<ServiceToken> getServiceTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
// Validate arguments.
if (userIdToken != null) {
if (masterToken == null)
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_NULL);
if (!userIdToken.isBoundTo(masterToken))
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber() + "; mt " + masterToken.getSerialNumber());
}
return Collections.emptySet();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeServiceTokens(java.lang.String, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
// Validate arguments.
if (userIdToken != null && masterToken != null &&
!userIdToken.isBoundTo(masterToken))
{
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber() + "; mt " + masterToken.getSerialNumber());
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearServiceTokens()
*/
@Override
public void clearServiceTokens() {
}
}
| 1,694 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/MslContext.java
|
/**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.Date;
import java.util.Random;
import java.util.SortedSet;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.msg.MessageCapabilities;
import com.netflix.msl.msg.MslControl;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
/**
* <p>The context provides access to all factories, builders, and containers
* that are needed by the MSL library. There is expected to be one global
* context per trusted services network or peer-to-peer network. By extension,
* the MSL store instance returned by the context is expected to be specific to
* the owning context.</p>
*
* @see MslStore
* @author Wesley Miaw <[email protected]>
*/
public abstract class MslContext {
/** Milliseconds per second. */
private static final long MILLISECONDS_PER_SECOND = 1000;
/** Re-authentication reason codes. */
public static enum ReauthCode {
/** The master token was rejected as bad or invalid. */
ENTITY_REAUTH(ResponseCode.ENTITY_REAUTH),
/** The entity authentication data failed to authenticate the entity. */
ENTITYDATA_REAUTH(ResponseCode.ENTITYDATA_REAUTH),
;
/**
* @return the re-authentication code corresponding to the response
* code.
* @throws IllegalArgumentException if the response code does not map
* onto a re-authentication code.
*/
public static ReauthCode valueOf(final ResponseCode code) {
for (final ReauthCode value : ReauthCode.values()) {
if (value.code == code)
return value;
}
throw new IllegalArgumentException("Unknown reauthentication code value " + code + ".");
}
/**
* Create a new re-authentication code mapped from the specified
* response code.
*
* @param code the response code for the re-authentication code.
*/
private ReauthCode(final ResponseCode code) {
this.code = code;
}
/**
* @return the integer value of the response code.
*/
public int intValue() {
return code.intValue();
}
/** The response code value. */
private final ResponseCode code;
}
/**
* Returns the local entity time. This is assumed to be the real time.
*
* @return {number} the local entity time in milliseconds since the epoch.
*/
public abstract long getTime();
/**
* <p>Returns a random number generator.</p>
*
* <p>It is extremely important to provide a secure (pseudo-)random number
* generator with a good source of entropy. Many random number generators,
* including those found in the Java Runtime Environment, JavaScript, and
* operating systems do not provide sufficient randomness.</p>
*
* <p>If in doubt, performing an {@code XOR} on the output of two or more
* independent random sources can be used to provide better random
* values.</p>
*
* @return a random number generator.
*/
public abstract Random getRandom();
/**
* Returns true if the context is operating in a peer-to-peer network. The
* message processing logic is slightly different in peer-to-peer networks.
*
* @return true if in peer-to-peer mode.
*/
public abstract boolean isPeerToPeer();
/**
* Returns the message capabilities for this entity.
*
* @return this entity's message capabilities.
*/
public abstract MessageCapabilities getMessageCapabilities();
/**
* <p>Returns the entity authentication data for this entity. This is used
* to authenticate messages prior to generation of a master token.</p>
*
* <p>This method should never return {@code null} but may do so in the one
* situation when the {@code reauthCode} parameter is provided and the
* application knows that the request being sent can no longer succeed
* because the existing master token, user ID token, or service tokens are
* no longer valid. This will abort the request.</p>
*
* <p>If the {@code reauthCode} parameter is equal to
* {@link ReauthCode#ENTITY_REAUTH} then the existing master token has been
* rejected, along with its bound user ID tokens and service tokens.</p>
*
* <p>If the {@code reauthCode} parameter is equal to
* {@link ReauthCode#ENTITYDATA_REAUTH} then new entity re-authentication
* data should be returned for this and all subsequent calls.</p>
*
* <p>The entity authentication scheme must never change.</p>
*
* <p>This method will be called multiple times.</p>
*
* @param reauthCode non-{@code null} if the master token or entity
* authentication data was rejected. If the entity authentication
* data was rejected then new entity authentication data is
* required.
* @return this entity's entity authentication data or null.
*/
public abstract EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode);
/**
* <p>Returns the primary crypto context used for MSL-level crypto
* operations. This is used for the master tokens and user ID tokens.</p>
*
* <p>Trusted network clients should return a crypto context that always
* returns false for verification. The other crypto context methods will
* not be used by trusted network clients.</p>
*
* @return the primary MSL crypto context.
* @throws MslCryptoException if there is an error creating the crypto
* context.
*/
public abstract ICryptoContext getMslCryptoContext() throws MslCryptoException;
/**
* <p>Returns the entity authentication scheme identified by the specified
* name or {@code null} if there is none.</p>
*
* @param name the entity authentication scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public abstract EntityAuthenticationScheme getEntityAuthenticationScheme(final String name);
/**
* Returns the entity authentication factory for the specified scheme.
*
* @param scheme the entity authentication scheme.
* @return the entity authentication factory, or null if no factory is
* available.
*/
public abstract EntityAuthenticationFactory getEntityAuthenticationFactory(final EntityAuthenticationScheme scheme);
/**
* <p>Returns the user authentication scheme identified by the specified
* name or {@code null} if there is none.</p>
*
* @param name the user authentication scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public abstract UserAuthenticationScheme getUserAuthenticationScheme(final String name);
/**
* Returns the user authentication factory for the specified scheme.
*
* Trusted network clients should always return null.
*
* @param scheme the user authentication scheme.
* @return the user authentication factory, or null if no factory is
* available.
*/
public abstract UserAuthenticationFactory getUserAuthenticationFactory(final UserAuthenticationScheme scheme);
/**
* Returns the token factory.
*
* This method will not be called by trusted network clients.
*
* @return the token factory.
*/
public abstract TokenFactory getTokenFactory();
/**
* <p>Returns the key exchange scheme identified by the specified name or
* {@code null} if there is none.</p>
*
* @param name the key exchange scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public abstract KeyExchangeScheme getKeyExchangeScheme(final String name);
/**
* Returns the key exchange factory for the specified scheme.
*
* @param scheme the key exchange scheme.
* @return the key exchange factory, or null if no factory is available.
*/
public abstract KeyExchangeFactory getKeyExchangeFactory(final KeyExchangeScheme scheme);
/**
* Returns the supported key exchange factories in order of preferred use.
* This should return an immutable collection.
*
* @return the key exchange factories, or the empty set.
*/
public abstract SortedSet<KeyExchangeFactory> getKeyExchangeFactories();
/**
* Returns the MSL store specific to this MSL context.
*
* @return the MSL store.
*/
public abstract MslStore getMslStore();
/**
* Returns the MSL encoder factory specific to this MSL context.
*
* @return the MSL encoder factory.
*/
public abstract MslEncoderFactory getMslEncoderFactory();
/**
* <p>Update the remote entity time.</p>
*
* <p>This function is only used by {@link MslControl} and should not be
* used by the application.</p>
*
* @param time remote entity time.
*/
public final void updateRemoteTime(final Date time) {
final long localSeconds = getTime() / MILLISECONDS_PER_SECOND;
final long remoteSeconds = time.getTime() / MILLISECONDS_PER_SECOND;
offset = remoteSeconds - localSeconds;
synced = true;
}
/**
* <p>Return the expected remote entity time or {@code null} if the clock
* is not yet synchronized.</p>
*
* <p>This function is only used by {@link MslControl} and should not be
* used by the application.</p>
*
* @return the expected remote entity time or {@code null} if not known.
*/
public final Date getRemoteTime() {
if (!synced) return null;
final long localSeconds = getTime() / MILLISECONDS_PER_SECOND;
final long remoteSeconds = localSeconds + offset;
return new Date(remoteSeconds * MILLISECONDS_PER_SECOND);
}
/** Remote clock is synchronized. */
private volatile boolean synced = false;
/** Remote entity time offset from local time in seconds. */
private volatile long offset = 0;
}
| 1,695 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/util/AuthenticationUtils.java
|
/**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationScheme;
/**
* Authentication utility functions.
*
* @author Wesley Miaw <[email protected]>
*/
public interface AuthenticationUtils {
/**
* Returns true if the entity identity has been revoked.
*
* @param identity the entity identity.
* @return true if the entity identity has been revoked.
*/
public boolean isEntityRevoked(final String identity);
/**
* Returns true if the identified entity is permitted to use the specified
* entity authentication scheme.
*
* @param identity the entity identity.
* @param scheme the entity authentication scheme.
* @return true if the entity is permitted to use the scheme.
*/
public boolean isSchemePermitted(final String identity, final EntityAuthenticationScheme scheme);
/**
* Returns true if the identified entity is permitted to use the specified
* user authentication scheme.
*
* @param identity the entity identity.
* @param scheme the user authentication scheme.
* @return true if the entity is permitted to use the scheme.
*/
public boolean isSchemePermitted(final String identity, final UserAuthenticationScheme scheme);
/**
* Returns true if the identified entity and user combination is permitted
* to use the specified user authentication scheme.
*
* @param identity the entity identity.
* @param user the user.
* @param scheme the user authentication scheme.
* @return true if the entity and user are permitted to use the scheme.
*/
public boolean isSchemePermitted(final String identity, final MslUser user, final UserAuthenticationScheme scheme);
/**
* Returns true if the identified entity is permitted to use the specified
* key exchange scheme.
*
* @param identity the entity identity.
* @param scheme the key exchange scheme.
* @return true if the entity is permitted to use the scheme.
*/
public boolean isSchemePermitted(final String identity, final KeyExchangeScheme scheme);
}
| 1,696 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageFactory.java
|
/**
* Copyright (c) 2015-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.MslUserIdTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslUtils;
/**
* <p>A message factory is used to create message streams and builders.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MessageFactory {
/**
* <p>Construct a new message input stream. The header is parsed.</p>
*
* <p>If key request data is provided and a matching key response data is
* found in the message header the key exchange will be performed to
* process the message payloads.</p>
*
* <p>Service tokens will be decrypted and verified with the provided crypto
* contexts identified by token name. A default crypto context may be
* provided by using the empty string as the token name; if a token name is
* not explcitly mapped onto a crypto context, the default crypto context
* will be used.</p>
*
* @param ctx MSL context.
* @param source MSL input stream.
* @param keyRequestData key request data to use when processing key
* response data.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @throws IOException if there is a problem reading from the input stream.
* @throws MslEncodingException if there is an error parsing the message.
* @throws MslCryptoException if there is an error decrypting or verifying
* the header or creating the message payload crypto context.
* @throws MslEntityAuthException if unable to create the entity
* authentication data.
* @throws MslUserAuthException if unable to create the user authentication
* data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be or if it has been revoked.
* @throws MslUserIdTokenException if the user ID token has been revoked.
* @throws MslKeyExchangeException if there is an error with the key
* request data or key response data or the key exchange scheme is
* not supported.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, the header data is
* missing or invalid, or the message ID is negative, or the
* message is not encrypted and contains user authentication data,
* or if the message master token is expired and the message is not
* renewable.
* @throws MslException if the message does not contain an entity
* authentication data or a master token, or a token is improperly
* bound to another token.
*/
public MessageInputStream createInputStream(final MslContext ctx, final InputStream source, final Set<KeyRequestData> keyRequestData, final Map<String,ICryptoContext> cryptoContexts) throws IOException, MslEncodingException, MslEntityAuthException, MslCryptoException, MslUserAuthException, MslMessageException, MslKeyExchangeException, MslMasterTokenException, MslUserIdTokenException, MslMessageException, MslException {
return new MessageInputStream(ctx, source, keyRequestData, cryptoContexts);
}
/**
* Construct a new error message output stream. The header is output
* immediately by calling {@code #flush()} on the destination output
* stream.
*
* @param ctx the MSL context.
* @param destination MSL output stream.
* @param header error header.
* @param format the MSL encoder format.
* @throws IOException if there is an error writing the header.
*/
public MessageOutputStream createOutputStream(final MslContext ctx, final OutputStream destination, final ErrorHeader header, final MslEncoderFormat format) throws IOException {
return new MessageOutputStream(ctx, destination, header, format);
}
/**
* Construct a new message output stream. The header is output
* immediately by calling {@code #flush()} on the destination output
* stream. The most preferred compression algorithm and encoder format
* supported by the local entity and message header will be used.
*
* @param ctx the MSL context.
* @param destination MSL output stream.
* @param header message header.
* @param cryptoContext payload data crypto context.
* @throws IOException if there is an error writing the header.
*/
public MessageOutputStream createOutputStream(final MslContext ctx, final OutputStream destination, final MessageHeader header, final ICryptoContext cryptoContext) throws IOException {
return new MessageOutputStream(ctx, destination, header, cryptoContext);
}
/**
* <p>Create a new message builder that will craft a new error message in
* response to another message. If the message ID of the request is not
* specified (i.e. unknown) then a random message ID will be generated.</p>
*
* @param ctx MSL context.
* @param requestMessageId message ID of request. May be null.
* @param error the MSL error.
* @param userMessage localized user-consumable error message. May be null.
* @return the error header.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslMessageException if no entity authentication data was
* returned by the MSL context.
*/
public ErrorHeader createErrorResponse(final MslContext ctx, final Long requestMessageId, final MslError error, final String userMessage) throws MslMessageException {
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
// If we have the request message ID then the error response message ID
// must be equal to the request message ID + 1.
long messageId;
if (requestMessageId != null) {
messageId = MessageBuilder.incrementMessageId(requestMessageId);
}
// Otherwise use a random message ID.
else {
messageId = MslUtils.getRandomLong(ctx);
}
final ResponseCode errorCode = error.getResponseCode();
final int internalCode = error.getInternalCode();
final String errorMsg = error.getMessage();
return new ErrorHeader(ctx, entityAuthData, messageId, errorCode, internalCode, errorMsg, userMessage);
}
/**
* <p>Create a new message builder that will craft a new message with the
* specified message ID.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @param messageId the message ID to use. Must be within range.
* @throws MslException if a user ID token is not bound to its
* corresponding master token.
*/
public MessageBuilder createRequest(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken, final long messageId) throws MslException {
return new MessageBuilder(ctx, masterToken, userIdToken, messageId);
}
/**
* <p>Create a new message builder that will craft a new message.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @throws MslException if a user ID token is not bound to its
* corresponding master token.
*/
public MessageBuilder createRequest(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
return new MessageBuilder(ctx, masterToken, userIdToken);
}
/**
* Create a new message builder that will craft a new message in response
* to another message. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslMasterTokenException if the provided message's master token
* is not trusted.
* @throws MslCryptoException if the crypto context from a key exchange
* cannot be created.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslUserAuthException if there is an error with the user
* authentication data or the user ID token cannot be created.
* @throws MslException if a user ID token in the message header is not
* bound to its corresponding master token or there is an error
* creating or renewing the master token.
*/
public MessageBuilder createResponse(final MslContext ctx, final MessageHeader requestHeader) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslUserAuthException, MslException {
return new ResponseMessageBuilder(ctx, requestHeader);
}
/**
* Create a new message builder that will craft a new message in response
* to another message without issuing or renewing any master tokens or user
* ID tokens. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslCryptoException if there is an error accessing the remote
* entity identity.
* @throws MslException if any of the request's user ID tokens is not bound
* to its master token.
*/
public MessageBuilder createIdempotentResponse(final MslContext ctx, final MessageHeader requestHeader) throws MslCryptoException, MslException {
return new IdempotentResponseMessageBuilder(ctx, requestHeader);
}
}
| 1,697 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageOutputStream.java
|
/**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* <p>A MSL message consists of a single MSL header followed by one or more
* payload chunks carrying application data. Each payload chunk is individually
* packaged but sequentially ordered. The end of the message is indicated by a
* payload with no data.</p>
*
* <p>No payload chunks may be included in an error message.</p>
*
* <p>Data is buffered until {@link #flush()} or {@link #close()} is called.
* At that point a new payload chunk is created and written out. Closing a
* {@code MessageOutputStream} does not close the destination output stream in
* case additional MSL messages will be written.</p>
*
* <p>A copy of the payload chunks is kept in-memory and can be retrieved by a
* a call to {@code getPayloads()} until {@code stopCaching()} is called. This
* is used to facilitate automatic re-sending of messages.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MessageOutputStream extends OutputStream {
/**
* Construct a new error message output stream. The header is output
* immediately by calling {@code #flush()} on the destination output
* stream.
*
* @param ctx the MSL context.
* @param destination MSL output stream.
* @param header error header.
* @param format the MSL encoder format.
* @throws IOException if there is an error writing the header.
*/
public MessageOutputStream(final MslContext ctx, final OutputStream destination, final ErrorHeader header, final MslEncoderFormat format) throws IOException {
// Encode the header.
final byte[] encoding;
try {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
encoding = header.toMslEncoding(encoder, format);
} catch (final MslEncoderException e) {
throw new IOException("Error encoding the error header.", e);
}
this.ctx = ctx;
this.destination = destination;
this.encoderFormat = format;
this.capabilities = ctx.getMessageCapabilities();
this.header = header;
this.compressionAlgo = null;
this.cryptoContext = null;
this.destination.write(encoding);
this.destination.flush();
}
/**
* <p>Construct a new message output stream. The header is output
* immediately by calling {@code #flush()} on the destination output
* stream.</p>
*
* <p>The most preferred compression algorithm and encoder format supported
* by the message header will be used. If this is a response, the message
* header capabilities will already consist of the intersection of the
* local and remote entity capabilities.</p>
*
* @param ctx the MSL context.
* @param destination MSL output stream.
* @param header message header.
* @param cryptoContext payload data crypto context.
* @throws IOException if there is an error writing the header.
*/
public MessageOutputStream(final MslContext ctx, final OutputStream destination, final MessageHeader header, final ICryptoContext cryptoContext) throws IOException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
// Identify the compression algorithm and encoder format.
final MessageCapabilities capabilities = header.getMessageCapabilities();
final CompressionAlgorithm compressionAlgo;
final MslEncoderFormat encoderFormat;
if (capabilities != null) {
final Set<CompressionAlgorithm> compressionAlgos = capabilities.getCompressionAlgorithms();
compressionAlgo = CompressionAlgorithm.getPreferredAlgorithm(compressionAlgos);
final Set<MslEncoderFormat> encoderFormats = capabilities.getEncoderFormats();
encoderFormat = encoder.getPreferredFormat(encoderFormats);
} else {
compressionAlgo = null;
encoderFormat = encoder.getPreferredFormat(null);
}
// Encode the header.
final byte[] encoding;
try {
encoding = header.toMslEncoding(encoder, encoderFormat);
} catch (final MslEncoderException e) {
throw new IOException("Error encoding the message header.", e);
}
this.ctx = ctx;
this.destination = destination;
this.encoderFormat = encoderFormat;
this.capabilities = capabilities;
this.header = header;
this.compressionAlgo = compressionAlgo;
this.cryptoContext = cryptoContext;
this.destination.write(encoding);
this.destination.flush();
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
/**
* Set the payload chunk compression algorithm that will be used for all
* future payload chunks. This function will flush any buffered data iff
* the compression algorithm is being changed.
*
* @param compressionAlgo payload chunk compression algorithm. Null for no
* compression.
* @return true if the compression algorithm is supported by the message,
* false if it is not.
* @throws IOException if buffered data could not be flushed. The
* compression algorithm will be unchanged.
* @throws MslInternalException if writing an error message.
* @see #flush()
*/
public boolean setCompressionAlgorithm(final CompressionAlgorithm compressionAlgo) throws IOException {
// Make sure this is not an error message,
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
throw new MslInternalException("Cannot write payload data for an error message.");
// Make sure the message is capable of using the compression algorithm.
if (compressionAlgo != null) {
if (capabilities == null)
return false;
final Set<CompressionAlgorithm> compressionAlgos = capabilities.getCompressionAlgorithms();
if (!compressionAlgos.contains(compressionAlgo))
return false;
}
if (this.compressionAlgo != compressionAlgo)
flush();
this.compressionAlgo = compressionAlgo;
return true;
}
/**
* @return the message header. Will be null for error messages.
*/
public MessageHeader getMessageHeader() {
if (header instanceof MessageHeader)
return (MessageHeader)header;
return null;
}
/**
* @return the error header. Will be null except for error messages.
*/
public ErrorHeader getErrorHeader() {
if (header instanceof ErrorHeader)
return (ErrorHeader)header;
return null;
}
/**
* Returns true if the payload application data is encrypted. This will be
* true if the entity authentication scheme provides encryption or if
* session keys were used. Returns false for error messages which do not
* have any payload chunks.
*
* @return true if the payload application data is encrypted. Will be false
* for error messages.
*/
public boolean encryptsPayloads() {
// Return false for error messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return false;
// If the message uses entity authentication data for an entity
// authentication scheme that provides encryption, return true.
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
if (entityAuthData != null && entityAuthData.getScheme().encrypts())
return true;
// If the message uses a master token, return true.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return true;
// If the message includes key response data, return true.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null)
return true;
// Otherwise return false.
return false;
}
/**
* Returns true if the payload application data is integrity protected.
* This will be true if the entity authentication scheme provides integrity
* protection or if session keys were used. Returns false for error
* messages which do not have any payload chunks.
*
* @return true if the payload application data is integrity protected.
* Will be false for error messages.
*/
public boolean protectsPayloadIntegrity() {
// Return false for error messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return false;
// If the message uses entity authentication data for an entity
// authentication scheme that provides integrity protection, return
// true.
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
if (entityAuthData != null && entityAuthData.getScheme().protectsIntegrity())
return true;
// If the message uses a master token, return true.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return true;
// If the message includes key response data, return true.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null)
return true;
// Otherwise return false.
return false;
}
/**
* Returns the payloads sent so far. Once payload caching is turned off
* this list will always be empty.
*
* @return an immutable ordered list of the payloads sent so far.
*/
List<PayloadChunk> getPayloads() {
return Collections.unmodifiableList(payloads);
}
/**
* Turns off caching of any message data (e.g. payloads).
*/
void stopCaching() {
caching = false;
payloads.clear();
}
/**
* By default the destination output stream is not closed when this message
* output stream is closed. If it should be closed then this method can be
* used to dictate the desired behavior.
*
* @param close true if the destination output stream should be closed,
* false if it should not.
*/
public void closeDestination(final boolean close) {
this.closeDestination = close;
}
/* (non-Javadoc)
* @see java.io.OutputStream#close()
*/
@Override
public void close() throws IOException {
if (closed) return;
// Send a final payload that can be used to identify the end of data.
// This is done by setting closed equal to true while the current
// payload not null.
closed = true;
flush();
currentPayload = null;
// Only close the destination if instructed to do so because we might
// want to reuse the connection.
if (closeDestination)
destination.close();
}
/**
* Flush any buffered data out to the destination. This creates a payload
* chunk. If there is no buffered data or this is an error message this
* function does nothing.
*
* @throws IOException if buffered data could not be flushed.
* @throws MslInternalException if writing an error message.
* @see java.io.OutputStream#flush()
*/
@Override
public void flush() throws IOException {
// If the current payload is null, we are already closed.
if (currentPayload == null) return;
// If we are not closed, and there is no data then we have nothing to
// send.
if (!closed && currentPayload.size() == 0) return;
// This is a no-op for error messages and handshake messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null || messageHeader.isHandshake()) return;
// Otherwise we are closed and need to send any buffered data as the
// last payload. If there is no buffered data, we still need to send a
// payload with the end of message flag set.
try {
final byte[] data = currentPayload.toByteArray();
final PayloadChunk chunk = createPayloadChunk(ctx, payloadSequenceNumber, messageHeader.getMessageId(), closed, compressionAlgo, data, this.cryptoContext);
if (caching) payloads.add(chunk);
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] encoding = chunk.toMslEncoding(encoder, encoderFormat);
destination.write(encoding);
destination.flush();
++payloadSequenceNumber;
// If we are closed, get rid of the current payload. This prevents
// us from sending any more payloads. Otherwise reset it for reuse.
if (closed)
currentPayload = null;
else
currentPayload.reset();
} catch (final MslEncoderException e) {
throw new IOException("Error encoding payload chunk [sequence number " + payloadSequenceNumber + "].", e);
} catch (final MslCryptoException e) {
throw new IOException("Error encrypting payload chunk [sequence number " + payloadSequenceNumber + "].", e);
} catch (final MslException e) {
throw new IOException("Error compressing payload chunk [sequence number " + payloadSequenceNumber + "].", e);
}
}
/**
* Create new payload chunk
*
* @param ctx the MSL context.
* @param sequenceNumber sequence number.
* @param messageId the message ID.
* @param endofmsg true if this is the last payload chunk of the message.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @param data the payload chunk application data.
* @param cryptoContext the crypto context.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the payload chunk.
* @throws MslException if there is an error compressing the data.
*/
protected PayloadChunk createPayloadChunk(final MslContext ctx, final long sequenceNumber, final long messageId, final boolean endofmsg, final CompressionAlgorithm compressionAlgo, final byte[] data, final ICryptoContext cryptoContext) throws MslEncodingException, MslCryptoException, MslException {
return new PayloadChunk(ctx, sequenceNumber, messageId, endofmsg, compressionAlgo, data, cryptoContext);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(byte[], int, int)
*/
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
// Fail if closed.
if (closed)
throw new IOException("Message output stream already closed.");
// Make sure this is not an error message or handshake message.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
throw new MslInternalException("Cannot write payload data for an error message.");
if (messageHeader.isHandshake())
throw new MslInternalException("Cannot write payload data for a handshake message.");
// Append data.
currentPayload.write(b, off, len);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(byte[])
*/
@Override
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(int)
*/
@Override
public void write(final int b) throws IOException {
final byte[] ba = new byte[1];
ba[0] = (byte)(b & 0xFF);
write(ba);
}
/** MSL context. */
private final MslContext ctx;
/** Destination output stream. */
private final OutputStream destination;
/** MSL encoder format. */
private final MslEncoderFormat encoderFormat;
/** Message output stream capabilities. */
private final MessageCapabilities capabilities;
/** Header. */
private final Header header;
/** Payload crypto context. */
private final ICryptoContext cryptoContext;
/** Paload chunk compression algorithm. */
private CompressionAlgorithm compressionAlgo;
/** Current payload sequence number. */
private long payloadSequenceNumber = 1;
/** Current payload chunk data. */
private ByteArrayOutputStream currentPayload = new ByteArrayOutputStream();
/** Stream is closed. */
private boolean closed = false;
/** True if the destination output stream should be closed. */
private boolean closeDestination = false;
/** True if caching data. */
private boolean caching = true;
/** Ordered list of sent payloads. */
private final List<PayloadChunk> payloads = new ArrayList<PayloadChunk>();
}
| 1,698 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageDebugContext.java
|
/**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
/**
* <p>A message debug context is used to provide debugging callbacks to
* {@link com.netflix.msl.msg.MslControl}.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public interface MessageDebugContext {
/**
* Called just prior to sending a message with the message header or error
* header that will be sent. An error may occur preventing successful
* transmission of the header after this method is called.
*
* @param header message header or error header.
*/
public void sentHeader(final Header header);
/**
* Called just after receiving a message, before performing additional
* validation, with the message header or error header.
*
* @param header message header or error header.
*/
public void receivedHeader(final Header header);
}
| 1,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.