comment stringlengths 1 45k | method_body stringlengths 23 281k | target_code stringlengths 0 5.16k | method_body_after stringlengths 12 281k | context_before stringlengths 8 543k | context_after stringlengths 8 543k |
|---|---|---|---|---|---|
Is this being done to prevent the `buffer` from being used? If so, when we're in read mode we should just skip allocating the `buffer` entirely. | public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
} | buffer.limit(0); | public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} |
I'd expand on the exception message a bit to state that the destination buffer is read-only instead of it needing to support writes. `The 'dst' ByteBuffer is read-only and cannot be written to.` | public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
} | throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes.")); | public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
}
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
}
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} |
I think this would be better as an `UnsupportedOperationException`. We could also think about having the `WriteBehavior` implementation throw this exception instead of here so that more specific information can be included (and update `WriteBehavior.canSeek`'s javadoc to mention that it can throw an exception). | private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
} | throw LOGGER.logExceptionAsError(new IllegalArgumentException( | private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
}
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
}
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} |
No. The channel knows its time to refill the buffer in read mode when `buffer.remaining() == 0`. Setting the limit to zero ensures this happens for the first read, as well as being semantically useful by indicating the buffer is empty. But the buffer will be needed once that first read takes place, and refilling the buffer clears the buffer to have limit = capacity. This will probably be clearer when constructors are separated. | public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
} | buffer.limit(0); | public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} |
Will fix by separating constructors. | public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
} | if (readBehavior != null && writeBehavior != null) { | public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} |
You're suggesting `assertCanSeek()` on the interface? | private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
} | throw LOGGER.logExceptionAsError(new IllegalArgumentException( | private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
}
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
}
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} |
Yeah, something like that, since the boolean is only used to determine whether this exception should be thrown it may be better to make it `void` and throw a more detailed exception than what's being thrown here. | private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
} | throw LOGGER.logExceptionAsError(new IllegalArgumentException( | private void writeModeSeek(long newPosition) {
if (!writeBehavior.canSeek(newPosition)) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The backing resource does not support this position change."));
}
flushWriteBuffer();
absolutePosition = newPosition;
bufferAbsolutePosition = newPosition;
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
}
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} | class StorageSeekableByteChannel implements SeekableByteChannel {
private static final ClientLogger LOGGER = new ClientLogger(StorageSeekableByteChannel.class);
/**
* Interface for injectable behavior to read from a backing Storage resource.
*/
public interface ReadBehavior {
/**
* Reads n bytes from the backing resource, where {@code 0 <= n <= dst.remaining()}.
* Emulates behavior of {@link java.nio.channels.ReadableByteChannel
*
* @param dst Destination to read the resource into.
* @param sourceOffset Offset to read from the resource.
* @return Number of bytes read from the resource, possibly zero, or -1 end of resource.
* @see java.nio.channels.ReadableByteChannel
*/
int read(ByteBuffer dst, long sourceOffset);
/**
* Gets the length of the resource. The returned value may have been cached from previous operations on this
* instance.
* @return The length in bytes.
*/
long getResourceLength();
}
/**
* Interface for injectable behavior to write to a backing Storage resource.
*/
public interface WriteBehavior {
/**
* Writes to the backing resource.
* @param src Bytes to write.
* @param destOffset Offset of backing resource to write the bytes at.
*/
void write(ByteBuffer src, long destOffset);
/**
* Calls any necessary commit/flush calls on the backing resource.
* @param totalLength Total length of the bytes being committed (necessary for some resource types).
*/
void commit(long totalLength);
/**
* Determines whether the write behavior can support a random seek to this position. May fetch information
* from the service to determine if possible.
* @param position Desired seek position.
* @return Whether the resource supports this.
*/
boolean canSeek(long position);
/**
* Changes the size of the backing resource, if supported.
* @param newSize New size of backing resource.
* @throws UnsupportedOperationException If operation is not supported by the backing resource.
*/
void resize(long newSize);
}
private final ReadBehavior readBehavior;
private final WriteBehavior writeBehavior;
private boolean isClosed;
private ByteBuffer buffer;
private long bufferAbsolutePosition;
private long absolutePosition;
/**
* Constructs an instance of this class.
* @param chunkSize Size of the internal channel buffer to use for data transfer, and for individual REST transfers.
* @param readBehavior Behavior for reading from the backing Storage resource.
* @param writeBehavior Behavior for writing to the backing Storage resource.
* @throws IllegalArgumentException If both read and write behavior are given.
*/
public StorageSeekableByteChannel(int chunkSize, ReadBehavior readBehavior, WriteBehavior writeBehavior) {
if (readBehavior != null && writeBehavior != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"StorageSeekableByteChannel can have only one of readBehavior or writeBehavior."));
}
buffer = ByteBuffer.allocate(chunkSize);
this.readBehavior = readBehavior;
this.writeBehavior = writeBehavior;
bufferAbsolutePosition = 0;
if (readBehavior != null) {
buffer.limit(0);
}
}
/**
* Gets the read-behavior used by this channel.
* @return {@link ReadBehavior} of this channel.
*/
public ReadBehavior getReadBehavior() {
return readBehavior;
}
/**
* Gets the write-behavior used by this channel.
* @return {@link WriteBehavior} of this channel.
*/
public WriteBehavior getWriteBehavior() {
return writeBehavior;
}
@Override
public int read(ByteBuffer dst) throws IOException {
assertOpen();
assertCanRead();
if (dst.isReadOnly()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("ByteBuffer dst must support writes."));
}
if (buffer.remaining() == 0) {
if (refillReadBuffer(absolutePosition) == -1) {
absolutePosition = readBehavior.getResourceLength();
return -1;
}
}
if (buffer.remaining() == 0) {
return 0;
}
int read = Math.min(buffer.remaining(), dst.remaining());
ByteBuffer temp = buffer.duplicate();
temp.limit(temp.position() + read);
dst.put(temp);
buffer.position(buffer.position() + read);
absolutePosition += read;
return read;
}
private int refillReadBuffer(long newBufferAbsolutePosition) {
buffer.clear();
int read = readBehavior.read(buffer, newBufferAbsolutePosition);
buffer.rewind();
buffer.limit(Math.max(read, 0));
bufferAbsolutePosition = Math.min(newBufferAbsolutePosition, readBehavior.getResourceLength());
return read;
}
@Override
public int write(ByteBuffer src) throws IOException {
assertOpen();
assertCanWrite();
int write = Math.min(src.remaining(), buffer.remaining());
if (write > 0) {
ByteBuffer temp = src.duplicate();
temp.limit(temp.position() + write);
buffer.put(temp);
src.position(src.position() + write);
}
if (buffer.remaining() == 0) {
try {
flushWriteBuffer();
} catch (RuntimeException e) {
buffer.position(buffer.position() - write);
throw LOGGER.logExceptionAsError(e);
}
}
absolutePosition += write;
return write;
}
private void flushWriteBuffer() {
if (buffer.position() == 0) {
return;
}
int startingPosition = buffer.position();
buffer.limit(buffer.position());
buffer.rewind();
try {
writeBehavior.write(buffer, bufferAbsolutePosition);
} catch (RuntimeException e) {
buffer.limit(buffer.capacity());
buffer.position(startingPosition);
throw LOGGER.logExceptionAsError(e);
}
bufferAbsolutePosition += buffer.limit();
buffer.clear();
}
@Override
public long position() throws IOException {
assertOpen();
return absolutePosition;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
assertOpen();
if (readBehavior != null) {
readModeSeek(newPosition);
} else {
writeModeSeek(newPosition);
}
return this;
}
private void readModeSeek(long newPosition) {
if (newPosition < bufferAbsolutePosition || newPosition > bufferAbsolutePosition + buffer.limit()) {
buffer.clear();
buffer.limit(0);
} else {
buffer.position((int) (newPosition - bufferAbsolutePosition));
}
absolutePosition = newPosition;
}
@Override
public long size() throws IOException {
assertOpen();
if (readBehavior != null) {
return readBehavior.getResourceLength();
} else {
return absolutePosition;
}
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
assertOpen();
writeBehavior.resize(size);
return this;
}
@Override
public boolean isOpen() {
return !isClosed;
}
@Override
public void close() throws IOException {
if (writeBehavior != null) {
flushWriteBuffer();
writeBehavior.commit(absolutePosition);
}
isClosed = true;
buffer = null;
}
private void assertCanRead() {
if (readBehavior == null) {
throw LOGGER.logExceptionAsError(new NonReadableChannelException());
}
}
private void assertCanWrite() {
if (writeBehavior == null) {
throw LOGGER.logExceptionAsError(new NonWritableChannelException());
}
}
private void assertOpen() throws ClosedChannelException {
if (isClosed) {
throw LOGGER.logThrowableAsError(new ClosedChannelException());
}
}
} |
I'd prefer it to log and throw - it's an invalid Content-Range header and there is no recovery from it | public static long extractSizeFromContentRange(String contentRange) {
Objects.requireNonNull(contentRange, "Cannot extract length from null 'contentRange'.");
int index = contentRange.indexOf('/');
if (index == -1) {
return -2;
}
String sizeString = contentRange.substring(index + 1).trim();
if ("*".equals(sizeString)) {
return -1;
}
return Long.parseLong(sizeString);
} | return -2; | public static long extractSizeFromContentRange(String contentRange) {
Objects.requireNonNull(contentRange, "Cannot extract length from null 'contentRange'.");
int index = contentRange.indexOf('/');
if (index == -1) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The Content-Range header wasn't properly "
+ "formatted and didn't contain a '/size' segment. The 'contentRange' was: " + contentRange));
}
String sizeString = contentRange.substring(index + 1).trim();
if ("*".equals(sizeString)) {
return -1;
}
return Long.parseLong(sizeString);
} | class from an array of Objects.
*
* @param args Array of objects to search through to find the first instance of the given `clazz` type.
* @param clazz The type trying to be found.
* @param <T> Generic type
* @return The first object of the desired type, otherwise null.
*/
public static <T> T findFirstOfType(Object[] args, Class<T> clazz) {
if (isNullOrEmpty(args)) {
return null;
}
for (Object arg : args) {
if (clazz.isInstance(arg)) {
return clazz.cast(arg);
}
}
return null;
} | class from an array of Objects.
*
* @param args Array of objects to search through to find the first instance of the given `clazz` type.
* @param clazz The type trying to be found.
* @param <T> Generic type
* @return The first object of the desired type, otherwise null.
*/
public static <T> T findFirstOfType(Object[] args, Class<T> clazz) {
if (isNullOrEmpty(args)) {
return null;
}
for (Object arg : args) {
if (clazz.isInstance(arg)) {
return clazz.cast(arg);
}
}
return null;
} |
Won't this break if the content is larger than 2GB | public Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data) {
return withContext(context -> this.uploadBlobWithResponse(data, context));
} | return withContext(context -> this.uploadBlobWithResponse(data, context)); | return withContext(context -> this.uploadBlobWithResponse(data, context));
}
private Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data, Context context) {
if (data == null) {
return monoError(LOGGER, new NullPointerException("'data' can't be null."));
}
String digest = computeDigest(data.toByteBuffer());
return blobsImpl.startUploadWithResponseAsync(repositoryName, context)
.flatMap(startUploadResponse -> blobsImpl.uploadChunkWithResponseAsync(trimNextLink(startUploadResponse.getDeserializedHeaders().getLocation()), data.toFluxByteBuffer(), data.getLength(), context))
.flatMap(uploadChunkResponse -> blobsImpl.completeUploadWithResponseAsync(digest, trimNextLink(uploadChunkResponse.getDeserializedHeaders().getLocation()), (Flux<ByteBuffer>) null, 0L, context))
.map(completeUploadResponse -> (Response<UploadBlobResult>)
new ResponseBase<>(completeUploadResponse.getRequest(),
completeUploadResponse.getStatusCode(),
completeUploadResponse.getHeaders(),
ConstructorAccessors.createUploadBlobResult(completeUploadResponse.getDeserializedHeaders().getDockerContentDigest()),
completeUploadResponse.getDeserializedHeaders()))
.onErrorMap(UtilsImpl::mapException);
} | class ContainerRegistryBlobAsyncClient {
private final AzureContainerRegistryImpl registryImplClient;
private final ContainerRegistryBlobsImpl blobsImpl;
private final ContainerRegistriesImpl registriesImpl;
private final String endpoint;
private final String repositoryName;
private static final ClientLogger LOGGER = new ClientLogger(ContainerRegistryBlobAsyncClient.class);
ContainerRegistryBlobAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String version) {
this.repositoryName = repositoryName;
this.endpoint = endpoint;
this.registryImplClient = new AzureContainerRegistryImplBuilder()
.url(endpoint)
.pipeline(httpPipeline)
.apiVersion(version)
.buildClient();
this.blobsImpl = this.registryImplClient.getContainerRegistryBlobs();
this.registriesImpl = this.registryImplClient.getContainerRegistries();
}
/**
* This method returns the registry's repository on which operations are being performed.
*
* @return The name of the repository
*/
public String getRepositoryName() {
return this.repositoryName;
}
/**
* This method returns the complete registry endpoint.
*
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* Upload the Oci manifest to the repository.
* The upload is done as a single operation.
* @see <a href="https:
* @param manifest The OciManifest that needs to be uploaded.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code manifest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(OciManifest manifest) {
if (manifest == null) {
return monoError(LOGGER, new NullPointerException("'manifest' can't be null."));
}
return withContext(context -> uploadManifestWithResponse(BinaryData.fromObject(manifest), null, ManifestMediaType.OCI_MANIFEST, context))
.flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
* @param options The options for the upload manifest operation.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(UploadManifestOptions options) {
return uploadManifestWithResponse(options).flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
*
* @param options The options for the upload manifest operation.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadManifestResult>> uploadManifestWithResponse(UploadManifestOptions options) {
if (options == null) {
return monoError(LOGGER, new NullPointerException("'options' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(options.getManifest(), options.getTag(), options.getMediaType(), context));
}
private Mono<Response<UploadManifestResult>> uploadManifestWithResponse(BinaryData manifestData, String tagOrDigest, ManifestMediaType manifestMediaType, Context context) {
ByteBuffer data = manifestData.toByteBuffer();
if (tagOrDigest == null) {
tagOrDigest = computeDigest(data);
}
return this.registriesImpl.createManifestWithResponseAsync(
repositoryName,
tagOrDigest,
Flux.just(data),
data.remaining(),
manifestMediaType.toString(),
context).map(response -> {
Response<UploadManifestResult> res = new ResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
ConstructorAccessors.createUploadManifestResult(response.getDeserializedHeaders().getDockerContentDigest()),
response.getDeserializedHeaders());
return res;
}).onErrorMap(UtilsImpl::mapException);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadBlobResult> uploadBlob(BinaryData data) {
return uploadBlobWithResponse(data).flatMap(FluxUtil::toMono);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data) {
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param options Options for the operation.
* @return The manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadManifestResult> downloadManifest(DownloadManifestOptions options) {
return this.downloadManifestWithResponse(options).flatMap(FluxUtil::toMono);
}
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param options The options for the operation.
* @return The response for the manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(DownloadManifestOptions options) {
return withContext(context -> this.downloadManifestWithResponse(options, context));
}
private Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(DownloadManifestOptions options, Context context) {
if (options == null) {
return monoError(LOGGER, new NullPointerException("'options' can't be null."));
}
String tagOrDigest = options.getTag() != null ? options.getTag() : options.getDigest();
return this.registriesImpl.getManifestWithResponseAsync(repositoryName, tagOrDigest, OCI_MANIFEST_MEDIA_TYPE, context)
.flatMap(response -> {
String digest = response.getHeaders().getValue(DOCKER_DIGEST_HEADER_NAME);
ManifestWrapper wrapper = response.getValue();
if (Objects.equals(digest, tagOrDigest) || Objects.equals(response.getValue().getTag(), tagOrDigest)) {
OciManifest ociManifest = new OciManifest()
.setAnnotations(wrapper.getAnnotations())
.setConfig(wrapper.getConfig())
.setLayers(wrapper.getLayers())
.setSchemaVersion(wrapper.getSchemaVersion());
Response<DownloadManifestResult> res = new SimpleResponse<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
new DownloadManifestResult(digest, ociManifest, BinaryData.fromObject(ociManifest)));
return Mono.just(res);
} else {
return monoError(LOGGER, new ServiceResponseException("The digest in the response does not match the expected digest."));
}
}).onErrorMap(UtilsImpl::mapException);
}
/**
* Download the blob\layer associated with the given digest.
*
* @param digest The digest for the given image layer.
* @return The image associated with the given digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobDownloadAsyncResult> downloadStream(String digest) {
return withContext(context -> downloadBlobInternal(digest, context));
}
private Mono<BlobDownloadAsyncResult> downloadBlobInternal(String digest, Context context) {
if (digest == null) {
return monoError(LOGGER, new NullPointerException("'digest' can't be null."));
}
Flux<ByteBuffer> content =
blobsImpl.getChunkWithResponseAsync(repositoryName, digest, new HttpRange(0, (long) CHUNK_SIZE).toString(), context)
.flatMapMany(firstResponse -> getAllChunks(firstResponse, digest, context))
.flatMapSequential(chunk -> chunk.getValue().toFluxByteBuffer(), 1);
return Mono.just(ConstructorAccessors.createBlobDownloadResult(digest, content));
}
private Flux<ContainerRegistryBlobsGetChunkResponse> getAllChunks(ContainerRegistryBlobsGetChunkResponse firstResponse, String digest, Context context) {
validateResponseHeaderDigest(digest, firstResponse.getHeaders());
long blobSize = getBlobSize(firstResponse.getHeaders().get(HttpHeaderName.CONTENT_RANGE));
List<Mono<ContainerRegistryBlobsGetChunkResponse>> others = new ArrayList<>();
others.add(Mono.just(firstResponse));
for (long p = firstResponse.getValue().getLength(); p < blobSize; p += CHUNK_SIZE) {
HttpRange range = new HttpRange(p, (long) CHUNK_SIZE);
others.add(blobsImpl.getChunkWithResponseAsync(repositoryName, digest, range.toString(), context));
}
return Flux.concat(others);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The completion signal.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlob(String digest) {
return this.deleteBlobWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The REST response for the completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobWithResponse(String digest) {
return withContext(context -> deleteBlobWithResponse(digest, context));
}
private Mono<Response<Void>> deleteBlobWithResponse(String digest, Context context) {
if (digest == null) {
return monoError(LOGGER, new NullPointerException("'digest' can't be null."));
}
return this.blobsImpl.deleteBlobWithResponseAsync(repositoryName, digest, context)
.flatMap(response -> Mono.just(UtilsImpl.deleteResponseToSuccess(response)))
.onErrorResume(
ex -> ex instanceof HttpResponseException && ((HttpResponseException) ex).getResponse().getStatusCode() == 404,
ex -> {
HttpResponse response = ((HttpResponseException) ex).getResponse();
return Mono.just(new SimpleResponse<Void>(response.getRequest(), 202,
response.getHeaders(), null));
})
.onErrorMap(UtilsImpl::mapException);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteManifest(String digest) {
return this.deleteManifestWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The REST response for completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteManifestWithResponse(String digest) {
return withContext(context -> deleteManifestWithResponse(digest, context));
}
private Mono<Response<Void>> deleteManifestWithResponse(String digest, Context context) {
return this.registriesImpl.deleteManifestWithResponseAsync(repositoryName, digest, context)
.flatMap(response -> Mono.just(UtilsImpl.deleteResponseToSuccess(response)))
.onErrorMap(UtilsImpl::mapException);
}
} | class ContainerRegistryBlobAsyncClient {
private final ContainerRegistryBlobsImpl blobsImpl;
private final ContainerRegistriesImpl registriesImpl;
private final String endpoint;
private final String repositoryName;
private static final ClientLogger LOGGER = new ClientLogger(ContainerRegistryBlobAsyncClient.class);
ContainerRegistryBlobAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String version) {
this.repositoryName = repositoryName;
this.endpoint = endpoint;
AzureContainerRegistryImpl registryImplClient = new AzureContainerRegistryImpl(httpPipeline, endpoint, version);
this.blobsImpl = registryImplClient.getContainerRegistryBlobs();
this.registriesImpl = registryImplClient.getContainerRegistries();
}
/**
* This method returns the registry's repository on which operations are being performed.
*
* @return The name of the repository
*/
public String getRepositoryName() {
return this.repositoryName;
}
/**
* This method returns the complete registry endpoint.
*
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* Upload the Oci manifest to the repository.
* The upload is done as a single operation.
* @see <a href="https:
* @param manifest The OciManifest that needs to be uploaded.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code manifest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(OciManifest manifest) {
if (manifest == null) {
return monoError(LOGGER, new NullPointerException("'manifest' can't be null."));
}
return withContext(context -> uploadManifestWithResponse(BinaryData.fromObject(manifest), null, ManifestMediaType.OCI_MANIFEST, context))
.flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
* @param options The options for the upload manifest operation.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(UploadManifestOptions options) {
return uploadManifestWithResponse(options).flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
*
* @param options The options for the upload manifest operation.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadManifestResult>> uploadManifestWithResponse(UploadManifestOptions options) {
if (options == null) {
return monoError(LOGGER, new NullPointerException("'options' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(options.getManifest(), options.getTag(), options.getMediaType(), context));
}
private Mono<Response<UploadManifestResult>> uploadManifestWithResponse(BinaryData manifestData, String tagOrDigest, ManifestMediaType manifestMediaType, Context context) {
ByteBuffer data = manifestData.toByteBuffer();
if (tagOrDigest == null) {
tagOrDigest = computeDigest(data);
}
return registriesImpl
.createManifestWithResponseAsync(
repositoryName,
tagOrDigest,
Flux.just(data),
data.remaining(),
manifestMediaType.toString(),
context)
.map(response -> (Response<UploadManifestResult>)
new ResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
ConstructorAccessors.createUploadManifestResult(response.getDeserializedHeaders().getDockerContentDigest()),
response.getDeserializedHeaders()))
.onErrorMap(UtilsImpl::mapException);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadBlobResult> uploadBlob(BinaryData data) {
return uploadBlobWithResponse(data).flatMap(FluxUtil::toMono);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data) {
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param tagOrDigest Manifest reference which can be tag or digest.
* @return The manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadManifestResult> downloadManifest(String tagOrDigest) {
return withContext(context -> this.downloadManifestWithResponse(tagOrDigest, SUPPORTED_MANIFEST_TYPES, context)).flatMap(FluxUtil::toMono);
}
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param tagOrDigest Manifest reference which can be tag or digest.
* @param mediaType Manifest media type to request (or a comma separated list of media types).
* @return The response for the manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest, ManifestMediaType mediaType) {
return withContext(context -> this.downloadManifestWithResponse(tagOrDigest, mediaType, context));
}
private Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest, ManifestMediaType mediaType, Context context) {
if (tagOrDigest == null) {
return monoError(LOGGER, new NullPointerException("'tagOrDigest' can't be null."));
}
return registriesImpl.getManifestWithResponseAsync(repositoryName, tagOrDigest, mediaType.toString(), context)
.map(response -> toDownloadManifestResponse(tagOrDigest, response))
.onErrorMap(UtilsImpl::mapException);
}
/**
* Download the blob\layer associated with the given digest.
*
* @param digest The digest for the given image layer.
* @return The image associated with the given digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadBlobAsyncResult> downloadStream(String digest) {
return withContext(context -> downloadBlobInternal(digest, context));
}
private Mono<DownloadBlobAsyncResult> downloadBlobInternal(String digest, Context context) {
if (digest == null) {
return monoError(LOGGER, new NullPointerException("'digest' can't be null."));
}
Flux<ByteBuffer> content =
blobsImpl.getChunkWithResponseAsync(repositoryName, digest, new HttpRange(0, (long) CHUNK_SIZE).toString(), context)
.flatMapMany(firstResponse -> getAllChunks(firstResponse, digest, context))
.flatMapSequential(chunk -> chunk.getValue().toFluxByteBuffer(), 1);
return Mono.just(ConstructorAccessors.createDownloadBlobResult(digest, content));
}
private Flux<ResponseBase<ContainerRegistryBlobsGetChunkHeaders, BinaryData>> getAllChunks(
ResponseBase<ContainerRegistryBlobsGetChunkHeaders, BinaryData> firstResponse, String digest, Context context) {
validateResponseHeaderDigest(digest, firstResponse.getHeaders());
long blobSize = getBlobSize(firstResponse.getHeaders().get(HttpHeaderName.CONTENT_RANGE));
List<Mono<ResponseBase<ContainerRegistryBlobsGetChunkHeaders, BinaryData>>> others = new ArrayList<>();
others.add(Mono.just(firstResponse));
for (long p = firstResponse.getValue().getLength(); p < blobSize; p += CHUNK_SIZE) {
HttpRange range = new HttpRange(p, (long) CHUNK_SIZE);
others.add(blobsImpl.getChunkWithResponseAsync(repositoryName, digest, range.toString(), context));
}
return Flux.concat(others);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The completion signal.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlob(String digest) {
return this.deleteBlobWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The REST response for the completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobWithResponse(String digest) {
return withContext(context -> deleteBlobWithResponse(digest, context));
}
private Mono<Response<Void>> deleteBlobWithResponse(String digest, Context context) {
if (digest == null) {
return monoError(LOGGER, new NullPointerException("'digest' can't be null."));
}
return this.blobsImpl.deleteBlobWithResponseAsync(repositoryName, digest, context)
.flatMap(response -> Mono.just(UtilsImpl.deleteResponseToSuccess(response)))
.onErrorResume(
ex -> ex instanceof HttpResponseException && ((HttpResponseException) ex).getResponse().getStatusCode() == 404,
ex -> {
HttpResponse response = ((HttpResponseException) ex).getResponse();
return Mono.just(new SimpleResponse<Void>(response.getRequest(), 202,
response.getHeaders(), null));
})
.onErrorMap(UtilsImpl::mapException);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteManifest(String digest) {
return this.deleteManifestWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The REST response for completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteManifestWithResponse(String digest) {
return withContext(context -> deleteManifestWithResponse(digest, context));
}
private Mono<Response<Void>> deleteManifestWithResponse(String digest, Context context) {
return this.registriesImpl.deleteManifestWithResponseAsync(repositoryName, digest, context)
.flatMap(response -> Mono.just(UtilsImpl.deleteResponseToSuccess(response)))
.onErrorMap(UtilsImpl::mapException);
}
} |
stay tuned for the new PR on this :) | public Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data) {
return withContext(context -> this.uploadBlobWithResponse(data, context));
} | return withContext(context -> this.uploadBlobWithResponse(data, context)); | return withContext(context -> this.uploadBlobWithResponse(data, context));
}
private Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data, Context context) {
if (data == null) {
return monoError(LOGGER, new NullPointerException("'data' can't be null."));
}
String digest = computeDigest(data.toByteBuffer());
return blobsImpl.startUploadWithResponseAsync(repositoryName, context)
.flatMap(startUploadResponse -> blobsImpl.uploadChunkWithResponseAsync(trimNextLink(startUploadResponse.getDeserializedHeaders().getLocation()), data.toFluxByteBuffer(), data.getLength(), context))
.flatMap(uploadChunkResponse -> blobsImpl.completeUploadWithResponseAsync(digest, trimNextLink(uploadChunkResponse.getDeserializedHeaders().getLocation()), (Flux<ByteBuffer>) null, 0L, context))
.map(completeUploadResponse -> (Response<UploadBlobResult>)
new ResponseBase<>(completeUploadResponse.getRequest(),
completeUploadResponse.getStatusCode(),
completeUploadResponse.getHeaders(),
ConstructorAccessors.createUploadBlobResult(completeUploadResponse.getDeserializedHeaders().getDockerContentDigest()),
completeUploadResponse.getDeserializedHeaders()))
.onErrorMap(UtilsImpl::mapException);
} | class ContainerRegistryBlobAsyncClient {
private final AzureContainerRegistryImpl registryImplClient;
private final ContainerRegistryBlobsImpl blobsImpl;
private final ContainerRegistriesImpl registriesImpl;
private final String endpoint;
private final String repositoryName;
private static final ClientLogger LOGGER = new ClientLogger(ContainerRegistryBlobAsyncClient.class);
ContainerRegistryBlobAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String version) {
this.repositoryName = repositoryName;
this.endpoint = endpoint;
this.registryImplClient = new AzureContainerRegistryImplBuilder()
.url(endpoint)
.pipeline(httpPipeline)
.apiVersion(version)
.buildClient();
this.blobsImpl = this.registryImplClient.getContainerRegistryBlobs();
this.registriesImpl = this.registryImplClient.getContainerRegistries();
}
/**
* This method returns the registry's repository on which operations are being performed.
*
* @return The name of the repository
*/
public String getRepositoryName() {
return this.repositoryName;
}
/**
* This method returns the complete registry endpoint.
*
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* Upload the Oci manifest to the repository.
* The upload is done as a single operation.
* @see <a href="https:
* @param manifest The OciManifest that needs to be uploaded.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code manifest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(OciManifest manifest) {
if (manifest == null) {
return monoError(LOGGER, new NullPointerException("'manifest' can't be null."));
}
return withContext(context -> uploadManifestWithResponse(BinaryData.fromObject(manifest), null, ManifestMediaType.OCI_MANIFEST, context))
.flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
* @param options The options for the upload manifest operation.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(UploadManifestOptions options) {
return uploadManifestWithResponse(options).flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
*
* @param options The options for the upload manifest operation.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadManifestResult>> uploadManifestWithResponse(UploadManifestOptions options) {
if (options == null) {
return monoError(LOGGER, new NullPointerException("'options' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(options.getManifest(), options.getTag(), options.getMediaType(), context));
}
private Mono<Response<UploadManifestResult>> uploadManifestWithResponse(BinaryData manifestData, String tagOrDigest, ManifestMediaType manifestMediaType, Context context) {
ByteBuffer data = manifestData.toByteBuffer();
if (tagOrDigest == null) {
tagOrDigest = computeDigest(data);
}
return this.registriesImpl.createManifestWithResponseAsync(
repositoryName,
tagOrDigest,
Flux.just(data),
data.remaining(),
manifestMediaType.toString(),
context).map(response -> {
Response<UploadManifestResult> res = new ResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
ConstructorAccessors.createUploadManifestResult(response.getDeserializedHeaders().getDockerContentDigest()),
response.getDeserializedHeaders());
return res;
}).onErrorMap(UtilsImpl::mapException);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadBlobResult> uploadBlob(BinaryData data) {
return uploadBlobWithResponse(data).flatMap(FluxUtil::toMono);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data) {
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param options Options for the operation.
* @return The manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadManifestResult> downloadManifest(DownloadManifestOptions options) {
return this.downloadManifestWithResponse(options).flatMap(FluxUtil::toMono);
}
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param options The options for the operation.
* @return The response for the manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(DownloadManifestOptions options) {
return withContext(context -> this.downloadManifestWithResponse(options, context));
}
private Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(DownloadManifestOptions options, Context context) {
if (options == null) {
return monoError(LOGGER, new NullPointerException("'options' can't be null."));
}
String tagOrDigest = options.getTag() != null ? options.getTag() : options.getDigest();
return this.registriesImpl.getManifestWithResponseAsync(repositoryName, tagOrDigest, OCI_MANIFEST_MEDIA_TYPE, context)
.flatMap(response -> {
String digest = response.getHeaders().getValue(DOCKER_DIGEST_HEADER_NAME);
ManifestWrapper wrapper = response.getValue();
if (Objects.equals(digest, tagOrDigest) || Objects.equals(response.getValue().getTag(), tagOrDigest)) {
OciManifest ociManifest = new OciManifest()
.setAnnotations(wrapper.getAnnotations())
.setConfig(wrapper.getConfig())
.setLayers(wrapper.getLayers())
.setSchemaVersion(wrapper.getSchemaVersion());
Response<DownloadManifestResult> res = new SimpleResponse<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
new DownloadManifestResult(digest, ociManifest, BinaryData.fromObject(ociManifest)));
return Mono.just(res);
} else {
return monoError(LOGGER, new ServiceResponseException("The digest in the response does not match the expected digest."));
}
}).onErrorMap(UtilsImpl::mapException);
}
/**
* Download the blob\layer associated with the given digest.
*
* @param digest The digest for the given image layer.
* @return The image associated with the given digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<BlobDownloadAsyncResult> downloadStream(String digest) {
return withContext(context -> downloadBlobInternal(digest, context));
}
private Mono<BlobDownloadAsyncResult> downloadBlobInternal(String digest, Context context) {
if (digest == null) {
return monoError(LOGGER, new NullPointerException("'digest' can't be null."));
}
Flux<ByteBuffer> content =
blobsImpl.getChunkWithResponseAsync(repositoryName, digest, new HttpRange(0, (long) CHUNK_SIZE).toString(), context)
.flatMapMany(firstResponse -> getAllChunks(firstResponse, digest, context))
.flatMapSequential(chunk -> chunk.getValue().toFluxByteBuffer(), 1);
return Mono.just(ConstructorAccessors.createBlobDownloadResult(digest, content));
}
private Flux<ContainerRegistryBlobsGetChunkResponse> getAllChunks(ContainerRegistryBlobsGetChunkResponse firstResponse, String digest, Context context) {
validateResponseHeaderDigest(digest, firstResponse.getHeaders());
long blobSize = getBlobSize(firstResponse.getHeaders().get(HttpHeaderName.CONTENT_RANGE));
List<Mono<ContainerRegistryBlobsGetChunkResponse>> others = new ArrayList<>();
others.add(Mono.just(firstResponse));
for (long p = firstResponse.getValue().getLength(); p < blobSize; p += CHUNK_SIZE) {
HttpRange range = new HttpRange(p, (long) CHUNK_SIZE);
others.add(blobsImpl.getChunkWithResponseAsync(repositoryName, digest, range.toString(), context));
}
return Flux.concat(others);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The completion signal.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlob(String digest) {
return this.deleteBlobWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The REST response for the completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobWithResponse(String digest) {
return withContext(context -> deleteBlobWithResponse(digest, context));
}
private Mono<Response<Void>> deleteBlobWithResponse(String digest, Context context) {
if (digest == null) {
return monoError(LOGGER, new NullPointerException("'digest' can't be null."));
}
return this.blobsImpl.deleteBlobWithResponseAsync(repositoryName, digest, context)
.flatMap(response -> Mono.just(UtilsImpl.deleteResponseToSuccess(response)))
.onErrorResume(
ex -> ex instanceof HttpResponseException && ((HttpResponseException) ex).getResponse().getStatusCode() == 404,
ex -> {
HttpResponse response = ((HttpResponseException) ex).getResponse();
return Mono.just(new SimpleResponse<Void>(response.getRequest(), 202,
response.getHeaders(), null));
})
.onErrorMap(UtilsImpl::mapException);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteManifest(String digest) {
return this.deleteManifestWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The REST response for completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteManifestWithResponse(String digest) {
return withContext(context -> deleteManifestWithResponse(digest, context));
}
private Mono<Response<Void>> deleteManifestWithResponse(String digest, Context context) {
return this.registriesImpl.deleteManifestWithResponseAsync(repositoryName, digest, context)
.flatMap(response -> Mono.just(UtilsImpl.deleteResponseToSuccess(response)))
.onErrorMap(UtilsImpl::mapException);
}
} | class ContainerRegistryBlobAsyncClient {
private final ContainerRegistryBlobsImpl blobsImpl;
private final ContainerRegistriesImpl registriesImpl;
private final String endpoint;
private final String repositoryName;
private static final ClientLogger LOGGER = new ClientLogger(ContainerRegistryBlobAsyncClient.class);
ContainerRegistryBlobAsyncClient(String repositoryName, HttpPipeline httpPipeline, String endpoint, String version) {
this.repositoryName = repositoryName;
this.endpoint = endpoint;
AzureContainerRegistryImpl registryImplClient = new AzureContainerRegistryImpl(httpPipeline, endpoint, version);
this.blobsImpl = registryImplClient.getContainerRegistryBlobs();
this.registriesImpl = registryImplClient.getContainerRegistries();
}
/**
* This method returns the registry's repository on which operations are being performed.
*
* @return The name of the repository
*/
public String getRepositoryName() {
return this.repositoryName;
}
/**
* This method returns the complete registry endpoint.
*
* @return The registry endpoint including the authority.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* Upload the Oci manifest to the repository.
* The upload is done as a single operation.
* @see <a href="https:
* @param manifest The OciManifest that needs to be uploaded.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code manifest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(OciManifest manifest) {
if (manifest == null) {
return monoError(LOGGER, new NullPointerException("'manifest' can't be null."));
}
return withContext(context -> uploadManifestWithResponse(BinaryData.fromObject(manifest), null, ManifestMediaType.OCI_MANIFEST, context))
.flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
* @param options The options for the upload manifest operation.
* @return operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadManifestResult> uploadManifest(UploadManifestOptions options) {
return uploadManifestWithResponse(options).flatMap(FluxUtil::toMono);
}
/**
* Uploads a manifest to the repository.
* The client currently only supports uploading OciManifests to the repository.
* And this operation makes the assumption that the data provided is a valid OCI manifest.
* <p>
* Also, the data is read into memory and then an upload operation is performed as a single operation.
* @see <a href="https:
*
* @param options The options for the upload manifest operation.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadManifestResult>> uploadManifestWithResponse(UploadManifestOptions options) {
if (options == null) {
return monoError(LOGGER, new NullPointerException("'options' can't be null."));
}
return withContext(context -> this.uploadManifestWithResponse(options.getManifest(), options.getTag(), options.getMediaType(), context));
}
private Mono<Response<UploadManifestResult>> uploadManifestWithResponse(BinaryData manifestData, String tagOrDigest, ManifestMediaType manifestMediaType, Context context) {
ByteBuffer data = manifestData.toByteBuffer();
if (tagOrDigest == null) {
tagOrDigest = computeDigest(data);
}
return registriesImpl
.createManifestWithResponseAsync(
repositoryName,
tagOrDigest,
Flux.just(data),
data.remaining(),
manifestMediaType.toString(),
context)
.map(response -> (Response<UploadManifestResult>)
new ResponseBase<>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
ConstructorAccessors.createUploadManifestResult(response.getDeserializedHeaders().getDockerContentDigest()),
response.getDeserializedHeaders()))
.onErrorMap(UtilsImpl::mapException);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<UploadBlobResult> uploadBlob(BinaryData data) {
return uploadBlobWithResponse(data).flatMap(FluxUtil::toMono);
}
/**
* Uploads a blob to the repository.
* The client currently uploads the entire blob\layer as a single unit.
* <p>
* The blob is read into memory and then an upload operation is performed as a single operation.
* We currently do not support breaking the layer into multiple chunks and uploading them one at a time
*
* @param data The blob\image content that needs to be uploaded.
* @return The rest response containing the operation result.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code data} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<UploadBlobResult>> uploadBlobWithResponse(BinaryData data) {
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param tagOrDigest Manifest reference which can be tag or digest.
* @return The manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadManifestResult> downloadManifest(String tagOrDigest) {
return withContext(context -> this.downloadManifestWithResponse(tagOrDigest, SUPPORTED_MANIFEST_TYPES, context)).flatMap(FluxUtil::toMono);
}
/**
* Download the manifest associated with the given tag or digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param tagOrDigest Manifest reference which can be tag or digest.
* @param mediaType Manifest media type to request (or a comma separated list of media types).
* @return The response for the manifest associated with the given tag or digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code tagOrDigest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest, ManifestMediaType mediaType) {
return withContext(context -> this.downloadManifestWithResponse(tagOrDigest, mediaType, context));
}
private Mono<Response<DownloadManifestResult>> downloadManifestWithResponse(String tagOrDigest, ManifestMediaType mediaType, Context context) {
if (tagOrDigest == null) {
return monoError(LOGGER, new NullPointerException("'tagOrDigest' can't be null."));
}
return registriesImpl.getManifestWithResponseAsync(repositoryName, tagOrDigest, mediaType.toString(), context)
.map(response -> toDownloadManifestResponse(tagOrDigest, response))
.onErrorMap(UtilsImpl::mapException);
}
/**
* Download the blob\layer associated with the given digest.
*
* @param digest The digest for the given image layer.
* @return The image associated with the given digest.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DownloadBlobAsyncResult> downloadStream(String digest) {
return withContext(context -> downloadBlobInternal(digest, context));
}
private Mono<DownloadBlobAsyncResult> downloadBlobInternal(String digest, Context context) {
if (digest == null) {
return monoError(LOGGER, new NullPointerException("'digest' can't be null."));
}
Flux<ByteBuffer> content =
blobsImpl.getChunkWithResponseAsync(repositoryName, digest, new HttpRange(0, (long) CHUNK_SIZE).toString(), context)
.flatMapMany(firstResponse -> getAllChunks(firstResponse, digest, context))
.flatMapSequential(chunk -> chunk.getValue().toFluxByteBuffer(), 1);
return Mono.just(ConstructorAccessors.createDownloadBlobResult(digest, content));
}
private Flux<ResponseBase<ContainerRegistryBlobsGetChunkHeaders, BinaryData>> getAllChunks(
ResponseBase<ContainerRegistryBlobsGetChunkHeaders, BinaryData> firstResponse, String digest, Context context) {
validateResponseHeaderDigest(digest, firstResponse.getHeaders());
long blobSize = getBlobSize(firstResponse.getHeaders().get(HttpHeaderName.CONTENT_RANGE));
List<Mono<ResponseBase<ContainerRegistryBlobsGetChunkHeaders, BinaryData>>> others = new ArrayList<>();
others.add(Mono.just(firstResponse));
for (long p = firstResponse.getValue().getLength(); p < blobSize; p += CHUNK_SIZE) {
HttpRange range = new HttpRange(p, (long) CHUNK_SIZE);
others.add(blobsImpl.getChunkWithResponseAsync(repositoryName, digest, range.toString(), context));
}
return Flux.concat(others);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The completion signal.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteBlob(String digest) {
return this.deleteBlobWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the image associated with the given digest
*
* @param digest The digest for the given image layer.
* @return The REST response for the completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteBlobWithResponse(String digest) {
return withContext(context -> deleteBlobWithResponse(digest, context));
}
private Mono<Response<Void>> deleteBlobWithResponse(String digest, Context context) {
if (digest == null) {
return monoError(LOGGER, new NullPointerException("'digest' can't be null."));
}
return this.blobsImpl.deleteBlobWithResponseAsync(repositoryName, digest, context)
.flatMap(response -> Mono.just(UtilsImpl.deleteResponseToSuccess(response)))
.onErrorResume(
ex -> ex instanceof HttpResponseException && ((HttpResponseException) ex).getResponse().getStatusCode() == 404,
ex -> {
HttpResponse response = ((HttpResponseException) ex).getResponse();
return Mono.just(new SimpleResponse<Void>(response.getRequest(), 202,
response.getHeaders(), null));
})
.onErrorMap(UtilsImpl::mapException);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteManifest(String digest) {
return this.deleteManifestWithResponse(digest).flatMap(FluxUtil::toMono);
}
/**
* Delete the manifest associated with the given digest.
* We currently only support downloading OCI manifests.
*
* @see <a href="https:
*
* @param digest The digest of the manifest.
* @return The REST response for completion.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws NullPointerException thrown if the {@code digest} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteManifestWithResponse(String digest) {
return withContext(context -> deleteManifestWithResponse(digest, context));
}
private Mono<Response<Void>> deleteManifestWithResponse(String digest, Context context) {
return this.registriesImpl.deleteManifestWithResponseAsync(repositoryName, digest, context)
.flatMap(response -> Mono.just(UtilsImpl.deleteResponseToSuccess(response)))
.onErrorMap(UtilsImpl::mapException);
}
} |
Long term, and no need to change in this PR as this is more to just throw ideas out, now that we use the generated layer I wonder if we should have implementation APIs where we don't need to create this `ConfigurationSetting` anymore and just pass along the `key`, `label`, and `value`. This is a relatively low win but if at any point we begin seeing performance issues (unlikely) this is a place/idea we could start with (and this would apply to all locations where we create a `ConfigurationSetting` just to turn it into a `KeyValue` later in the call stack). | public Mono<ConfigurationSetting> addConfigurationSetting(String key, String label, String value) {
return addConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
} | return addConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value)); | public Mono<ConfigurationSetting> addConfigurationSetting(String key, String label, String value) {
return addConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
} | class ConfigurationAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationAsyncClient.class);
private final AzureAppConfigurationImpl serviceClient;
private final SyncTokenPolicy syncTokenPolicy;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceClient The {@link AzureAppConfigurationImpl} that the client routes its request through.
* @param syncTokenPolicy {@link SyncTokenPolicy} to be used to update the external synchronization token to ensure
* service requests receive up-to-date values.
*/
ConfigurationAsyncClient(AzureAppConfigurationImpl serviceClient, SyncTokenPolicy syncTokenPolicy) {
this.serviceClient = serviceClient;
this.syncTokenPolicy = syncTokenPolicy;
}
/**
* Gets the service endpoint for the Azure App Configuration instance.
*
* @return the service endpoint for the Azure App Configuration instance.
*/
public String getEndpoint() {
return serviceClient.getEndpoint();
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add. If {@code null} no label will be used.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addConfigurationSetting(ConfigurationSetting setting) {
return addConfigurationSettingWithResponse(setting).map(Response::getValue);
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
* <pre>
* client.addConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .subscribe&
* ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addConfigurationSettingWithResponse(ConfigurationSetting setting) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.putKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
null, ETAG_ANY, toKeyValue(setting),
addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response, toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, If {@code null} no label will be used.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(String key, String label, String value) {
return setConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(ConfigurationSetting setting) {
return setConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* setting's ETag matches. If the ETag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
* <pre>
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* &
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is read-only, or an ETag was provided but does not match the service's current ETag
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's ETag does not match, or the setting exists and is
* read-only.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.putKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
getIfMatchETag(ifUnchanged, setting), null, toKeyValue(setting),
addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label) {
return getConfigurationSetting(key, label, null);
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code acceptDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* "prodDBConnection", null, OffsetDateTime.now&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label, OffsetDateTime acceptDateTime) {
return getConfigurationSettingWithResponse(new ConfigurationSetting().setKey(key).setLabel(label),
acceptDateTime, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param setting The setting to retrieve.
*
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(ConfigurationSetting setting) {
return getConfigurationSettingWithResponse(setting, null, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
* <pre>
* client.getConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
*
* @param setting The setting to retrieve.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getConfigurationSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime acceptDateTime, boolean ifChanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.getKeyValueWithResponseAsync(
setting.getKey(),
setting.getLabel(),
acceptDateTime == null ? null : acceptDateTime.toString(),
null,
getIfNoneMatchETag(ifChanged, setting),
null,
addTracingNamespace(context))
.onErrorResume(HttpResponseException.class,
(Function<Throwable, Mono<ResponseBase<GetKeyValueHeaders, KeyValue>>>)
throwable -> {
HttpResponseException e = (HttpResponseException) throwable;
HttpResponse httpResponse = e.getResponse();
if (httpResponse.getStatusCode() == 304) {
return Mono.just(new ResponseBase<GetKeyValueHeaders, KeyValue>(
httpResponse.getRequest(),
httpResponse.getStatusCode(),
httpResponse.getHeaders(),
null,
null));
}
return Mono.error(throwable);
})
.map(response ->
new SimpleResponse<>(response, toConfigurationSetting(response.getValue())))
);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete. If {@code null} no label will be used.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(String key, String label) {
return deleteConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label));
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
*
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(ConfigurationSetting setting) {
return deleteConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
* <pre>
* client.deleteConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.deleteKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
getIfMatchETag(ifUnchanged, setting), addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Sets the read-only status for the {@link ConfigurationSetting} that matches the {@code key}, the optional
* {@code label}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .contextWrite&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to set to be read-only.
* @param label The label of configuration setting to read-only. If {@code null} no label will be used.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label, boolean isReadOnly) {
return setReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), isReadOnly);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
*
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(ConfigurationSetting setting, boolean isReadOnly) {
return setReadOnlyWithResponse(setting, isReadOnly).map(Response::getValue);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .contextWrite&
* .subscribe&
* ConfigurationSetting result = response.getValue&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return A REST response containing the read-only or not read-only ConfigurationSetting if {@code isReadOnly}
* is true or null, or false respectively. Or return {@code null} if the setting didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting,
boolean isReadOnly) {
try {
validateSetting(setting);
return withContext(
context -> {
final String key = setting.getKey();
final String label = setting.getLabel();
context = addTracingNamespace(context);
return (isReadOnly
? serviceClient.putLockWithResponseAsync(key, label, null, null, context)
: serviceClient.deleteLockWithResponseAsync(key, label, null, null, context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue())));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Fetches the configuration settings that match the {@code selector}. If {@code selector} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
* <pre>
* client.listConfigurationSettings&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code selector}. If no options were provided, the Flux
* contains all of the current settings in the service.
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listConfigurationSettings(SettingSelector selector) {
try {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getKeyValuesSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
null,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null))),
nextLink -> withContext(
context -> serviceClient.getKeyValuesNextSinglePageAsync(
nextLink,
acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null)))
);
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(LOGGER, ex));
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* Revisions expire after a period of time, see <a href="https:
* for more information.
*
* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code selector}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
* <pre>
* client.listRevisions&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listRevisions(SettingSelector selector) {
try {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getRevisionsSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null))),
nextLink -> withContext(
context ->
serviceClient.getRevisionsNextSinglePageAsync(nextLink, acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(), null))));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(LOGGER, ex));
}
}
/**
* Adds an external synchronization token to ensure service requests receive up-to-date values.
*
* @param token an external synchronization token to ensure service requests receive up-to-date values.
* @throws NullPointerException if the given token is null.
*/
public void updateSyncToken(String token) {
Objects.requireNonNull(token, "'token' cannot be null.");
syncTokenPolicy.updateSyncToken(token);
}
} | class ConfigurationAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationAsyncClient.class);
private final AzureAppConfigurationImpl serviceClient;
private final SyncTokenPolicy syncTokenPolicy;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceClient The {@link AzureAppConfigurationImpl} that the client routes its request through.
* @param syncTokenPolicy {@link SyncTokenPolicy} to be used to update the external synchronization token to ensure
* service requests receive up-to-date values.
*/
ConfigurationAsyncClient(AzureAppConfigurationImpl serviceClient, SyncTokenPolicy syncTokenPolicy) {
this.serviceClient = serviceClient;
this.syncTokenPolicy = syncTokenPolicy;
}
/**
* Gets the service endpoint for the Azure App Configuration instance.
*
* @return the service endpoint for the Azure App Configuration instance.
*/
public String getEndpoint() {
return serviceClient.getEndpoint();
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add. If {@code null} no label will be used.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addConfigurationSetting(ConfigurationSetting setting) {
return addConfigurationSettingWithResponse(setting).map(Response::getValue);
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
* <pre>
* client.addConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .subscribe&
* ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addConfigurationSettingWithResponse(ConfigurationSetting setting) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.putKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), null, ETAG_ANY, toKeyValue(settingInternal),
addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, If {@code null} no label will be used.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(String key, String label, String value) {
return setConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(ConfigurationSetting setting) {
return setConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* setting's ETag matches. If the ETag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
* <pre>
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* &
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is read-only, or an ETag was provided but does not match the service's current ETag
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's ETag does not match, or the setting exists and is
* read-only.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.putKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), getEtag(ifUnchanged, settingInternal), null,
toKeyValue(settingInternal), addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label) {
return getConfigurationSetting(key, label, null);
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code acceptDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* "prodDBConnection", null, OffsetDateTime.now&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label, OffsetDateTime acceptDateTime) {
return getConfigurationSettingWithResponse(new ConfigurationSetting().setKey(key).setLabel(label),
acceptDateTime, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param setting The setting to retrieve.
*
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(ConfigurationSetting setting) {
return getConfigurationSettingWithResponse(setting, null, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
* <pre>
* client.getConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
*
* @param setting The setting to retrieve.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getConfigurationSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime acceptDateTime, boolean ifChanged) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal ->
serviceClient.getKeyValueWithResponseAsync(settingInternal.getKey(), settingInternal.getLabel(),
acceptDateTime == null ? null : acceptDateTime.toString(), null,
getEtag(ifChanged, settingInternal), null, addTracingNamespace(context))
.onErrorResume(
HttpResponseException.class,
(Function<Throwable, Mono<ResponseBase<GetKeyValueHeaders, KeyValue>>>) throwable -> {
HttpResponseException e = (HttpResponseException) throwable;
HttpResponse httpResponse = e.getResponse();
if (httpResponse.getStatusCode() == 304) {
return Mono.just(new ResponseBase<GetKeyValueHeaders, KeyValue>(
httpResponse.getRequest(), httpResponse.getStatusCode(),
httpResponse.getHeaders(), null, null));
}
return Mono.error(throwable);
})
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete. If {@code null} no label will be used.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(String key, String label) {
return deleteConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label));
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
*
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(ConfigurationSetting setting) {
return deleteConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
* <pre>
* client.deleteConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
return withContext(context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.deleteKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), getEtag(ifUnchanged, settingInternal), addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Sets the read-only status for the {@link ConfigurationSetting} that matches the {@code key}, the optional
* {@code label}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .contextWrite&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to set to be read-only.
* @param label The label of configuration setting to read-only. If {@code null} no label will be used.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label, boolean isReadOnly) {
return setReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), isReadOnly);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
*
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(ConfigurationSetting setting, boolean isReadOnly) {
return setReadOnlyWithResponse(setting, isReadOnly).map(Response::getValue);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .contextWrite&
* .subscribe&
* ConfigurationSetting result = response.getValue&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return A REST response containing the read-only or not read-only ConfigurationSetting if {@code isReadOnly}
* is true or null, or false respectively. Or return {@code null} if the setting didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting,
boolean isReadOnly) {
return withContext(context -> validateSettingAsync(setting).flatMap(
settingInternal -> {
final String key = settingInternal.getKey();
final String label = settingInternal.getLabel();
final Context contextInternal = addTracingNamespace(context);
return (isReadOnly
? serviceClient.putLockWithResponseAsync(key, label, null, null, contextInternal)
: serviceClient.deleteLockWithResponseAsync(key, label, null, null, contextInternal))
.map(response -> toConfigurationSettingWithResponse(response));
}));
}
/**
* Fetches the configuration settings that match the {@code selector}. If {@code selector} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
* <pre>
* client.listConfigurationSettings&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code selector}. If no options were provided, the Flux
* contains all of the current settings in the service.
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listConfigurationSettings(SettingSelector selector) {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getKeyValuesSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
null,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))),
nextLink -> withContext(
context -> serviceClient.getKeyValuesNextSinglePageAsync(
nextLink,
acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse)))
);
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* Revisions expire after a period of time, see <a href="https:
* for more information.
*
* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code selector}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
* <pre>
* client.listRevisions&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listRevisions(SettingSelector selector) {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getRevisionsSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))),
nextLink -> withContext(
context ->
serviceClient.getRevisionsNextSinglePageAsync(nextLink, acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))));
}
/**
* Adds an external synchronization token to ensure service requests receive up-to-date values.
*
* @param token an external synchronization token to ensure service requests receive up-to-date values.
* @throws NullPointerException if the given token is null.
*/
public void updateSyncToken(String token) {
Objects.requireNonNull(token, "'token' cannot be null.");
syncTokenPolicy.updateSyncToken(token);
}
} |
Let's add a utility method for converting paged responses as this is repeated in a handful of locations | public PagedFlux<ConfigurationSetting> listConfigurationSettings(SettingSelector selector) {
try {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getKeyValuesSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
null,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null))),
nextLink -> withContext(
context -> serviceClient.getKeyValuesNextSinglePageAsync(
nextLink,
acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null)))
);
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(LOGGER, ex));
}
} | null))), | public PagedFlux<ConfigurationSetting> listConfigurationSettings(SettingSelector selector) {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getKeyValuesSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
null,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))),
nextLink -> withContext(
context -> serviceClient.getKeyValuesNextSinglePageAsync(
nextLink,
acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse)))
);
} | class ConfigurationAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationAsyncClient.class);
private final AzureAppConfigurationImpl serviceClient;
private final SyncTokenPolicy syncTokenPolicy;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceClient The {@link AzureAppConfigurationImpl} that the client routes its request through.
* @param syncTokenPolicy {@link SyncTokenPolicy} to be used to update the external synchronization token to ensure
* service requests receive up-to-date values.
*/
ConfigurationAsyncClient(AzureAppConfigurationImpl serviceClient, SyncTokenPolicy syncTokenPolicy) {
this.serviceClient = serviceClient;
this.syncTokenPolicy = syncTokenPolicy;
}
/**
* Gets the service endpoint for the Azure App Configuration instance.
*
* @return the service endpoint for the Azure App Configuration instance.
*/
public String getEndpoint() {
return serviceClient.getEndpoint();
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add. If {@code null} no label will be used.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addConfigurationSetting(String key, String label, String value) {
return addConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addConfigurationSetting(ConfigurationSetting setting) {
return addConfigurationSettingWithResponse(setting).map(Response::getValue);
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
* <pre>
* client.addConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .subscribe&
* ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addConfigurationSettingWithResponse(ConfigurationSetting setting) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.putKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
null, ETAG_ANY, toKeyValue(setting),
addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response, toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, If {@code null} no label will be used.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(String key, String label, String value) {
return setConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(ConfigurationSetting setting) {
return setConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* setting's ETag matches. If the ETag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
* <pre>
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* &
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is read-only, or an ETag was provided but does not match the service's current ETag
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's ETag does not match, or the setting exists and is
* read-only.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.putKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
getIfMatchETag(ifUnchanged, setting), null, toKeyValue(setting),
addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label) {
return getConfigurationSetting(key, label, null);
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code acceptDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* "prodDBConnection", null, OffsetDateTime.now&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label, OffsetDateTime acceptDateTime) {
return getConfigurationSettingWithResponse(new ConfigurationSetting().setKey(key).setLabel(label),
acceptDateTime, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param setting The setting to retrieve.
*
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(ConfigurationSetting setting) {
return getConfigurationSettingWithResponse(setting, null, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
* <pre>
* client.getConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
*
* @param setting The setting to retrieve.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getConfigurationSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime acceptDateTime, boolean ifChanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.getKeyValueWithResponseAsync(
setting.getKey(),
setting.getLabel(),
acceptDateTime == null ? null : acceptDateTime.toString(),
null,
getIfNoneMatchETag(ifChanged, setting),
null,
addTracingNamespace(context))
.onErrorResume(HttpResponseException.class,
(Function<Throwable, Mono<ResponseBase<GetKeyValueHeaders, KeyValue>>>)
throwable -> {
HttpResponseException e = (HttpResponseException) throwable;
HttpResponse httpResponse = e.getResponse();
if (httpResponse.getStatusCode() == 304) {
return Mono.just(new ResponseBase<GetKeyValueHeaders, KeyValue>(
httpResponse.getRequest(),
httpResponse.getStatusCode(),
httpResponse.getHeaders(),
null,
null));
}
return Mono.error(throwable);
})
.map(response ->
new SimpleResponse<>(response, toConfigurationSetting(response.getValue())))
);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete. If {@code null} no label will be used.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(String key, String label) {
return deleteConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label));
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
*
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(ConfigurationSetting setting) {
return deleteConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
* <pre>
* client.deleteConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.deleteKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
getIfMatchETag(ifUnchanged, setting), addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Sets the read-only status for the {@link ConfigurationSetting} that matches the {@code key}, the optional
* {@code label}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .contextWrite&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to set to be read-only.
* @param label The label of configuration setting to read-only. If {@code null} no label will be used.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label, boolean isReadOnly) {
return setReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), isReadOnly);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
*
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(ConfigurationSetting setting, boolean isReadOnly) {
return setReadOnlyWithResponse(setting, isReadOnly).map(Response::getValue);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .contextWrite&
* .subscribe&
* ConfigurationSetting result = response.getValue&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return A REST response containing the read-only or not read-only ConfigurationSetting if {@code isReadOnly}
* is true or null, or false respectively. Or return {@code null} if the setting didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting,
boolean isReadOnly) {
try {
validateSetting(setting);
return withContext(
context -> {
final String key = setting.getKey();
final String label = setting.getLabel();
context = addTracingNamespace(context);
return (isReadOnly
? serviceClient.putLockWithResponseAsync(key, label, null, null, context)
: serviceClient.deleteLockWithResponseAsync(key, label, null, null, context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue())));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Fetches the configuration settings that match the {@code selector}. If {@code selector} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
* <pre>
* client.listConfigurationSettings&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code selector}. If no options were provided, the Flux
* contains all of the current settings in the service.
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* Revisions expire after a period of time, see <a href="https:
* for more information.
*
* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code selector}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
* <pre>
* client.listRevisions&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listRevisions(SettingSelector selector) {
try {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getRevisionsSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null))),
nextLink -> withContext(
context ->
serviceClient.getRevisionsNextSinglePageAsync(nextLink, acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(), null))));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(LOGGER, ex));
}
}
/**
* Adds an external synchronization token to ensure service requests receive up-to-date values.
*
* @param token an external synchronization token to ensure service requests receive up-to-date values.
* @throws NullPointerException if the given token is null.
*/
public void updateSyncToken(String token) {
Objects.requireNonNull(token, "'token' cannot be null.");
syncTokenPolicy.updateSyncToken(token);
}
} | class ConfigurationAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationAsyncClient.class);
private final AzureAppConfigurationImpl serviceClient;
private final SyncTokenPolicy syncTokenPolicy;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceClient The {@link AzureAppConfigurationImpl} that the client routes its request through.
* @param syncTokenPolicy {@link SyncTokenPolicy} to be used to update the external synchronization token to ensure
* service requests receive up-to-date values.
*/
ConfigurationAsyncClient(AzureAppConfigurationImpl serviceClient, SyncTokenPolicy syncTokenPolicy) {
this.serviceClient = serviceClient;
this.syncTokenPolicy = syncTokenPolicy;
}
/**
* Gets the service endpoint for the Azure App Configuration instance.
*
* @return the service endpoint for the Azure App Configuration instance.
*/
public String getEndpoint() {
return serviceClient.getEndpoint();
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add. If {@code null} no label will be used.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addConfigurationSetting(String key, String label, String value) {
return addConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addConfigurationSetting(ConfigurationSetting setting) {
return addConfigurationSettingWithResponse(setting).map(Response::getValue);
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
* <pre>
* client.addConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .subscribe&
* ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addConfigurationSettingWithResponse(ConfigurationSetting setting) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.putKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), null, ETAG_ANY, toKeyValue(settingInternal),
addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, If {@code null} no label will be used.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(String key, String label, String value) {
return setConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(ConfigurationSetting setting) {
return setConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* setting's ETag matches. If the ETag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
* <pre>
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* &
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is read-only, or an ETag was provided but does not match the service's current ETag
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's ETag does not match, or the setting exists and is
* read-only.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.putKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), getEtag(ifUnchanged, settingInternal), null,
toKeyValue(settingInternal), addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label) {
return getConfigurationSetting(key, label, null);
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code acceptDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* "prodDBConnection", null, OffsetDateTime.now&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label, OffsetDateTime acceptDateTime) {
return getConfigurationSettingWithResponse(new ConfigurationSetting().setKey(key).setLabel(label),
acceptDateTime, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param setting The setting to retrieve.
*
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(ConfigurationSetting setting) {
return getConfigurationSettingWithResponse(setting, null, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
* <pre>
* client.getConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
*
* @param setting The setting to retrieve.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getConfigurationSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime acceptDateTime, boolean ifChanged) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal ->
serviceClient.getKeyValueWithResponseAsync(settingInternal.getKey(), settingInternal.getLabel(),
acceptDateTime == null ? null : acceptDateTime.toString(), null,
getEtag(ifChanged, settingInternal), null, addTracingNamespace(context))
.onErrorResume(
HttpResponseException.class,
(Function<Throwable, Mono<ResponseBase<GetKeyValueHeaders, KeyValue>>>) throwable -> {
HttpResponseException e = (HttpResponseException) throwable;
HttpResponse httpResponse = e.getResponse();
if (httpResponse.getStatusCode() == 304) {
return Mono.just(new ResponseBase<GetKeyValueHeaders, KeyValue>(
httpResponse.getRequest(), httpResponse.getStatusCode(),
httpResponse.getHeaders(), null, null));
}
return Mono.error(throwable);
})
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete. If {@code null} no label will be used.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(String key, String label) {
return deleteConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label));
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
*
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(ConfigurationSetting setting) {
return deleteConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
* <pre>
* client.deleteConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
return withContext(context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.deleteKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), getEtag(ifUnchanged, settingInternal), addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Sets the read-only status for the {@link ConfigurationSetting} that matches the {@code key}, the optional
* {@code label}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .contextWrite&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to set to be read-only.
* @param label The label of configuration setting to read-only. If {@code null} no label will be used.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label, boolean isReadOnly) {
return setReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), isReadOnly);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
*
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(ConfigurationSetting setting, boolean isReadOnly) {
return setReadOnlyWithResponse(setting, isReadOnly).map(Response::getValue);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .contextWrite&
* .subscribe&
* ConfigurationSetting result = response.getValue&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return A REST response containing the read-only or not read-only ConfigurationSetting if {@code isReadOnly}
* is true or null, or false respectively. Or return {@code null} if the setting didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting,
boolean isReadOnly) {
return withContext(context -> validateSettingAsync(setting).flatMap(
settingInternal -> {
final String key = settingInternal.getKey();
final String label = settingInternal.getLabel();
final Context contextInternal = addTracingNamespace(context);
return (isReadOnly
? serviceClient.putLockWithResponseAsync(key, label, null, null, contextInternal)
: serviceClient.deleteLockWithResponseAsync(key, label, null, null, contextInternal))
.map(response -> toConfigurationSettingWithResponse(response));
}));
}
/**
* Fetches the configuration settings that match the {@code selector}. If {@code selector} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
* <pre>
* client.listConfigurationSettings&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code selector}. If no options were provided, the Flux
* contains all of the current settings in the service.
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* Revisions expire after a period of time, see <a href="https:
* for more information.
*
* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code selector}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
* <pre>
* client.listRevisions&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listRevisions(SettingSelector selector) {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getRevisionsSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))),
nextLink -> withContext(
context ->
serviceClient.getRevisionsNextSinglePageAsync(nextLink, acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))));
}
/**
* Adds an external synchronization token to ensure service requests receive up-to-date values.
*
* @param token an external synchronization token to ensure service requests receive up-to-date values.
* @throws NullPointerException if the given token is null.
*/
public void updateSyncToken(String token) {
Objects.requireNonNull(token, "'token' cannot be null.");
syncTokenPolicy.updateSyncToken(token);
}
} |
We should update `ConfigurationSetting` to compose `KeyValue`, that way we don't need to convert like this but instead just retrieve the wrapped `KeyValue`. And when turning a `KeyValue` into `ConfigurationSetting` it would be just passing the `KeyValue` into the `ConfigurationSetting` constructor. Storage has a good example of this with: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/models/BlobProperties.java#L35 | public static KeyValue toKeyValue(ConfigurationSetting setting) {
return new KeyValue()
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setContentType(setting.getContentType())
.setEtag(setting.getETag())
.setLastModified(setting.getLastModified())
.setLocked(setting.isReadOnly())
.setTags(setting.getTags());
} | return new KeyValue() | public static KeyValue toKeyValue(ConfigurationSetting setting) {
return new KeyValue()
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setContentType(setting.getContentType())
.setEtag(setting.getETag())
.setLastModified(setting.getLastModified())
.setLocked(setting.isReadOnly())
.setTags(setting.getTags());
} | class Utility {
private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable";
public static final String APP_CONFIG_TRACING_NAMESPACE_VALUE = "Microsoft.AppConfiguration";
static final String ID = "id";
static final String DESCRIPTION = "description";
static final String DISPLAY_NAME = "display_name";
static final String ENABLED = "enabled";
static final String CONDITIONS = "conditions";
static final String CLIENT_FILTERS = "client_filters";
static final String NAME = "name";
static final String PARAMETERS = "parameters";
static final String URI = "uri";
/**
* Represents any value in Etag.
*/
public static final String ETAG_ANY = "*";
/*
* Translate public ConfigurationSetting to KeyValue autorest generated class.
*/
public static SettingFields[] toSettingFieldsArray(List<KeyValueFields> kvFieldsList) {
return kvFieldsList.stream()
.map(keyValueFields -> toSettingFields(keyValueFields))
.collect(Collectors.toList())
.toArray(new SettingFields[kvFieldsList.size()]);
}
public static SettingFields toSettingFields(KeyValueFields keyValueFields) {
return keyValueFields == null ? null : SettingFields.fromString(keyValueFields.toString());
}
public static List<KeyValueFields> toKeyValueFieldsList(SettingFields[] settingFieldsArray) {
return Arrays.stream(settingFieldsArray)
.map(settingFields -> toKeyValueFields(settingFields))
.collect(Collectors.toList());
}
public static KeyValueFields toKeyValueFields(SettingFields settingFields) {
return settingFields == null ? null : KeyValueFields.fromString(settingFields.toString());
}
/*
* Azure Configuration service requires that the ETag value is surrounded in quotation marks.
*
* @param ETag The ETag to get the value for. If null is pass in, an empty string is returned.
* @return The ETag surrounded by quotations. (ex. "ETag")
*/
private static String getETagValue(String etag) {
return (etag == null || "*".equals(etag)) ? etag : "\"" + etag + "\"";
}
/*
* Get HTTP header value, if-match. Used to perform an operation only if the targeted resource's etag matches the
* value provided.
*/
public static String getIfMatchETag(boolean ifUnchanged, ConfigurationSetting setting) {
return ifUnchanged ? getETagValue(setting.getETag()) : null;
}
/*
* Get HTTP header value, if-none-match. Used to perform an operation only if the targeted resource's etag does not
* match the value provided.
*/
public static String getIfNoneMatchETag(boolean onlyIfChanged, ConfigurationSetting setting) {
return onlyIfChanged ? getETagValue(setting.getETag()) : null;
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
public static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/**
* Enable the sync stack rest proxy.
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context enableSyncRestProxy(Context context) {
return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true);
}
public static Context addTracingNamespace(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(AZ_TRACING_NAMESPACE_KEY, APP_CONFIG_TRACING_NAMESPACE_VALUE);
}
} | class Utility {
private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable";
public static final String APP_CONFIG_TRACING_NAMESPACE_VALUE = "Microsoft.AppConfiguration";
static final String ID = "id";
static final String DESCRIPTION = "description";
static final String DISPLAY_NAME = "display_name";
static final String ENABLED = "enabled";
static final String CONDITIONS = "conditions";
static final String CLIENT_FILTERS = "client_filters";
static final String NAME = "name";
static final String PARAMETERS = "parameters";
static final String URI = "uri";
/**
* Represents any value in Etag.
*/
public static final String ETAG_ANY = "*";
/*
* Translate public ConfigurationSetting to KeyValue autorest generated class.
*/
public static SettingFields[] toSettingFieldsArray(List<KeyValueFields> kvFieldsList) {
int size = kvFieldsList.size();
SettingFields[] fields = new SettingFields[size];
for (int i = 0; i < size; i++) {
fields[i] = toSettingFields(kvFieldsList.get(i));
}
return fields;
}
public static SettingFields toSettingFields(KeyValueFields keyValueFields) {
return keyValueFields == null ? null : SettingFields.fromString(keyValueFields.toString());
}
public static List<KeyValueFields> toKeyValueFieldsList(SettingFields[] settingFieldsArray) {
int size = settingFieldsArray.length;
List<KeyValueFields> keyValueFields = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
keyValueFields.add(toKeyValueFields(settingFieldsArray[i]));
}
return keyValueFields;
}
public static KeyValueFields toKeyValueFields(SettingFields settingFields) {
return settingFields == null ? null : KeyValueFields.fromString(settingFields.toString());
}
/*
* Azure Configuration service requires that the ETag value is surrounded in quotation marks.
*
* @param ETag The ETag to get the value for. If null is pass in, an empty string is returned.
* @return The ETag surrounded by quotations. (ex. "ETag")
*/
private static String getETagValue(String etag) {
return (etag == null || "*".equals(etag)) ? etag : "\"" + etag + "\"";
}
/*
* Get HTTP header value, if-match or if-none-match.. Used to perform an operation only if the targeted resource's
* etag matches the value provided.
*/
public static String getEtag(boolean isEtagRequired, ConfigurationSetting setting) {
return isEtagRequired ? getETagValue(setting.getETag()) : null;
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
public static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Asynchronously validate that setting and key is not null. The key is used in the service URL,
* so it cannot be null.
*/
public static Mono<ConfigurationSetting> validateSettingAsync(ConfigurationSetting setting) {
if (setting == null) {
return Mono.error(new NullPointerException("Configuration setting cannot be null"));
}
if (setting.getKey() == null) {
return Mono.error(new IllegalArgumentException("Parameter 'key' is required and cannot be null."));
}
return Mono.just(setting);
}
/**
* Enable the sync stack rest proxy.
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context enableSyncRestProxy(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true);
}
public static Context addTracingNamespace(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(AZ_TRACING_NAMESPACE_KEY, APP_CONFIG_TRACING_NAMESPACE_VALUE);
}
} |
nit: Stream does add overhead compared to iterating the list itself as here we create a temporary list to just throw it away ```suggestion int size = kvFieldsList.size(); SettingFields[] fields = new SettingFields[size]; for (int i = 0; i < size; i++) { fields[i] = toSettingFields(kvFieldsList.get(i)); } return fields; ``` | public static SettingFields[] toSettingFieldsArray(List<KeyValueFields> kvFieldsList) {
return kvFieldsList.stream()
.map(keyValueFields -> toSettingFields(keyValueFields))
.collect(Collectors.toList())
.toArray(new SettingFields[kvFieldsList.size()]);
} | return kvFieldsList.stream() | public static SettingFields[] toSettingFieldsArray(List<KeyValueFields> kvFieldsList) {
int size = kvFieldsList.size();
SettingFields[] fields = new SettingFields[size];
for (int i = 0; i < size; i++) {
fields[i] = toSettingFields(kvFieldsList.get(i));
}
return fields;
} | class Utility {
private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable";
public static final String APP_CONFIG_TRACING_NAMESPACE_VALUE = "Microsoft.AppConfiguration";
static final String ID = "id";
static final String DESCRIPTION = "description";
static final String DISPLAY_NAME = "display_name";
static final String ENABLED = "enabled";
static final String CONDITIONS = "conditions";
static final String CLIENT_FILTERS = "client_filters";
static final String NAME = "name";
static final String PARAMETERS = "parameters";
static final String URI = "uri";
/**
* Represents any value in Etag.
*/
public static final String ETAG_ANY = "*";
/*
* Translate public ConfigurationSetting to KeyValue autorest generated class.
*/
public static KeyValue toKeyValue(ConfigurationSetting setting) {
return new KeyValue()
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setContentType(setting.getContentType())
.setEtag(setting.getETag())
.setLastModified(setting.getLastModified())
.setLocked(setting.isReadOnly())
.setTags(setting.getTags());
}
public static SettingFields toSettingFields(KeyValueFields keyValueFields) {
return keyValueFields == null ? null : SettingFields.fromString(keyValueFields.toString());
}
public static List<KeyValueFields> toKeyValueFieldsList(SettingFields[] settingFieldsArray) {
return Arrays.stream(settingFieldsArray)
.map(settingFields -> toKeyValueFields(settingFields))
.collect(Collectors.toList());
}
public static KeyValueFields toKeyValueFields(SettingFields settingFields) {
return settingFields == null ? null : KeyValueFields.fromString(settingFields.toString());
}
/*
* Azure Configuration service requires that the ETag value is surrounded in quotation marks.
*
* @param ETag The ETag to get the value for. If null is pass in, an empty string is returned.
* @return The ETag surrounded by quotations. (ex. "ETag")
*/
private static String getETagValue(String etag) {
return (etag == null || "*".equals(etag)) ? etag : "\"" + etag + "\"";
}
/*
* Get HTTP header value, if-match. Used to perform an operation only if the targeted resource's etag matches the
* value provided.
*/
public static String getIfMatchETag(boolean ifUnchanged, ConfigurationSetting setting) {
return ifUnchanged ? getETagValue(setting.getETag()) : null;
}
/*
* Get HTTP header value, if-none-match. Used to perform an operation only if the targeted resource's etag does not
* match the value provided.
*/
public static String getIfNoneMatchETag(boolean onlyIfChanged, ConfigurationSetting setting) {
return onlyIfChanged ? getETagValue(setting.getETag()) : null;
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
public static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/**
* Enable the sync stack rest proxy.
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context enableSyncRestProxy(Context context) {
return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true);
}
public static Context addTracingNamespace(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(AZ_TRACING_NAMESPACE_KEY, APP_CONFIG_TRACING_NAMESPACE_VALUE);
}
} | class Utility {
private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable";
public static final String APP_CONFIG_TRACING_NAMESPACE_VALUE = "Microsoft.AppConfiguration";
static final String ID = "id";
static final String DESCRIPTION = "description";
static final String DISPLAY_NAME = "display_name";
static final String ENABLED = "enabled";
static final String CONDITIONS = "conditions";
static final String CLIENT_FILTERS = "client_filters";
static final String NAME = "name";
static final String PARAMETERS = "parameters";
static final String URI = "uri";
/**
* Represents any value in Etag.
*/
public static final String ETAG_ANY = "*";
/*
* Translate public ConfigurationSetting to KeyValue autorest generated class.
*/
public static KeyValue toKeyValue(ConfigurationSetting setting) {
return new KeyValue()
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setContentType(setting.getContentType())
.setEtag(setting.getETag())
.setLastModified(setting.getLastModified())
.setLocked(setting.isReadOnly())
.setTags(setting.getTags());
}
public static SettingFields toSettingFields(KeyValueFields keyValueFields) {
return keyValueFields == null ? null : SettingFields.fromString(keyValueFields.toString());
}
public static List<KeyValueFields> toKeyValueFieldsList(SettingFields[] settingFieldsArray) {
int size = settingFieldsArray.length;
List<KeyValueFields> keyValueFields = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
keyValueFields.add(toKeyValueFields(settingFieldsArray[i]));
}
return keyValueFields;
}
public static KeyValueFields toKeyValueFields(SettingFields settingFields) {
return settingFields == null ? null : KeyValueFields.fromString(settingFields.toString());
}
/*
* Azure Configuration service requires that the ETag value is surrounded in quotation marks.
*
* @param ETag The ETag to get the value for. If null is pass in, an empty string is returned.
* @return The ETag surrounded by quotations. (ex. "ETag")
*/
private static String getETagValue(String etag) {
return (etag == null || "*".equals(etag)) ? etag : "\"" + etag + "\"";
}
/*
* Get HTTP header value, if-match or if-none-match.. Used to perform an operation only if the targeted resource's
* etag matches the value provided.
*/
public static String getEtag(boolean isEtagRequired, ConfigurationSetting setting) {
return isEtagRequired ? getETagValue(setting.getETag()) : null;
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
public static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Asynchronously validate that setting and key is not null. The key is used in the service URL,
* so it cannot be null.
*/
public static Mono<ConfigurationSetting> validateSettingAsync(ConfigurationSetting setting) {
if (setting == null) {
return Mono.error(new NullPointerException("Configuration setting cannot be null"));
}
if (setting.getKey() == null) {
return Mono.error(new IllegalArgumentException("Parameter 'key' is required and cannot be null."));
}
return Mono.just(setting);
}
/**
* Enable the sync stack rest proxy.
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context enableSyncRestProxy(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true);
}
public static Context addTracingNamespace(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(AZ_TRACING_NAMESPACE_KEY, APP_CONFIG_TRACING_NAMESPACE_VALUE);
}
} |
nit: just check the content type, from my discussions with the service team it isn't explicitly enforced that a feature flag starts with the key prefix. https://github.com/Azure/azure-sdk-for-java/issues/33332 | public static ConfigurationSetting toConfigurationSetting(KeyValue keyValue) {
if (keyValue == null) {
return null;
}
final String contentType = keyValue.getContentType();
final String key = keyValue.getKey();
final String value = keyValue.getValue();
final String label = keyValue.getLabel();
final String etag = keyValue.getEtag();
final Map<String, String> tags = keyValue.getTags();
final ConfigurationSetting setting = new ConfigurationSetting()
.setKey(key)
.setValue(value)
.setLabel(label)
.setContentType(contentType)
.setETag(etag)
.setTags(tags);
ConfigurationSettingHelper.setLastModified(setting, keyValue.getLastModified());
ConfigurationSettingHelper.setReadOnly(setting, keyValue.isLocked() == null ? false : keyValue.isLocked());
try {
if (key != null && key.startsWith(FeatureFlagConfigurationSetting.KEY_PREFIX)
&& FEATURE_FLAG_CONTENT_TYPE.equals(contentType)) {
return subclassConfigurationSettingReflection(setting, parseFeatureFlagValue(setting.getValue()))
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setETag(setting.getETag())
.setContentType(setting.getContentType())
.setTags(setting.getTags());
} else if (SECRET_REFERENCE_CONTENT_TYPE.equals(contentType)) {
return subclassConfigurationSettingReflection(setting,
parseSecretReferenceFieldValue(setting.getKey(), setting.getValue()))
.setValue(value)
.setLabel(label)
.setETag(etag)
.setContentType(contentType)
.setTags(tags);
} else {
return setting;
}
} catch (Exception exception) {
throw LOGGER.logExceptionAsError(new RuntimeException(
"The setting is neither a 'FeatureFlagConfigurationSetting' nor "
+ "'SecretReferenceConfigurationSetting', return the setting as 'ConfigurationSetting'. "
+ "Error: ", exception));
}
} | && FEATURE_FLAG_CONTENT_TYPE.equals(contentType)) { | public static ConfigurationSetting toConfigurationSetting(KeyValue keyValue) {
if (keyValue == null) {
return null;
}
final String contentType = keyValue.getContentType();
final String key = keyValue.getKey();
final String value = keyValue.getValue();
final String label = keyValue.getLabel();
final String etag = keyValue.getEtag();
final Map<String, String> tags = keyValue.getTags();
final ConfigurationSetting setting = new ConfigurationSetting()
.setKey(key)
.setValue(value)
.setLabel(label)
.setContentType(contentType)
.setETag(etag)
.setTags(tags);
ConfigurationSettingHelper.setLastModified(setting, keyValue.getLastModified());
ConfigurationSettingHelper.setReadOnly(setting, keyValue.isLocked() == null ? false : keyValue.isLocked());
try {
if (FEATURE_FLAG_CONTENT_TYPE.equals(contentType)) {
return subclassConfigurationSettingReflection(setting, parseFeatureFlagValue(setting.getValue()))
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setETag(setting.getETag())
.setContentType(setting.getContentType())
.setTags(setting.getTags());
} else if (SECRET_REFERENCE_CONTENT_TYPE.equals(contentType)) {
return subclassConfigurationSettingReflection(setting,
parseSecretReferenceFieldValue(setting.getKey(), setting.getValue()))
.setValue(value)
.setLabel(label)
.setETag(etag)
.setContentType(contentType)
.setTags(tags);
} else {
return setting;
}
} catch (Exception exception) {
throw LOGGER.logExceptionAsError(new RuntimeException(
"The setting is neither a 'FeatureFlagConfigurationSetting' nor "
+ "'SecretReferenceConfigurationSetting', return the setting as 'ConfigurationSetting'. "
+ "Error: ", exception));
}
} | class KeyValue to public-explored ConfigurationSetting.
*/ | class KeyValue to public-explored ConfigurationSetting.
*/ |
Will create a follow-up PR to address the issue above to avoid review complexity. But will address the comment here. | public static ConfigurationSetting toConfigurationSetting(KeyValue keyValue) {
if (keyValue == null) {
return null;
}
final String contentType = keyValue.getContentType();
final String key = keyValue.getKey();
final String value = keyValue.getValue();
final String label = keyValue.getLabel();
final String etag = keyValue.getEtag();
final Map<String, String> tags = keyValue.getTags();
final ConfigurationSetting setting = new ConfigurationSetting()
.setKey(key)
.setValue(value)
.setLabel(label)
.setContentType(contentType)
.setETag(etag)
.setTags(tags);
ConfigurationSettingHelper.setLastModified(setting, keyValue.getLastModified());
ConfigurationSettingHelper.setReadOnly(setting, keyValue.isLocked() == null ? false : keyValue.isLocked());
try {
if (key != null && key.startsWith(FeatureFlagConfigurationSetting.KEY_PREFIX)
&& FEATURE_FLAG_CONTENT_TYPE.equals(contentType)) {
return subclassConfigurationSettingReflection(setting, parseFeatureFlagValue(setting.getValue()))
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setETag(setting.getETag())
.setContentType(setting.getContentType())
.setTags(setting.getTags());
} else if (SECRET_REFERENCE_CONTENT_TYPE.equals(contentType)) {
return subclassConfigurationSettingReflection(setting,
parseSecretReferenceFieldValue(setting.getKey(), setting.getValue()))
.setValue(value)
.setLabel(label)
.setETag(etag)
.setContentType(contentType)
.setTags(tags);
} else {
return setting;
}
} catch (Exception exception) {
throw LOGGER.logExceptionAsError(new RuntimeException(
"The setting is neither a 'FeatureFlagConfigurationSetting' nor "
+ "'SecretReferenceConfigurationSetting', return the setting as 'ConfigurationSetting'. "
+ "Error: ", exception));
}
} | && FEATURE_FLAG_CONTENT_TYPE.equals(contentType)) { | public static ConfigurationSetting toConfigurationSetting(KeyValue keyValue) {
if (keyValue == null) {
return null;
}
final String contentType = keyValue.getContentType();
final String key = keyValue.getKey();
final String value = keyValue.getValue();
final String label = keyValue.getLabel();
final String etag = keyValue.getEtag();
final Map<String, String> tags = keyValue.getTags();
final ConfigurationSetting setting = new ConfigurationSetting()
.setKey(key)
.setValue(value)
.setLabel(label)
.setContentType(contentType)
.setETag(etag)
.setTags(tags);
ConfigurationSettingHelper.setLastModified(setting, keyValue.getLastModified());
ConfigurationSettingHelper.setReadOnly(setting, keyValue.isLocked() == null ? false : keyValue.isLocked());
try {
if (FEATURE_FLAG_CONTENT_TYPE.equals(contentType)) {
return subclassConfigurationSettingReflection(setting, parseFeatureFlagValue(setting.getValue()))
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setETag(setting.getETag())
.setContentType(setting.getContentType())
.setTags(setting.getTags());
} else if (SECRET_REFERENCE_CONTENT_TYPE.equals(contentType)) {
return subclassConfigurationSettingReflection(setting,
parseSecretReferenceFieldValue(setting.getKey(), setting.getValue()))
.setValue(value)
.setLabel(label)
.setETag(etag)
.setContentType(contentType)
.setTags(tags);
} else {
return setting;
}
} catch (Exception exception) {
throw LOGGER.logExceptionAsError(new RuntimeException(
"The setting is neither a 'FeatureFlagConfigurationSetting' nor "
+ "'SecretReferenceConfigurationSetting', return the setting as 'ConfigurationSetting'. "
+ "Error: ", exception));
}
} | class KeyValue to public-explored ConfigurationSetting.
*/ | class KeyValue to public-explored ConfigurationSetting.
*/ |
Created an issue to address after this PR: https://github.com/Azure/azure-sdk-for-java/issues/33991 | public static KeyValue toKeyValue(ConfigurationSetting setting) {
return new KeyValue()
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setContentType(setting.getContentType())
.setEtag(setting.getETag())
.setLastModified(setting.getLastModified())
.setLocked(setting.isReadOnly())
.setTags(setting.getTags());
} | return new KeyValue() | public static KeyValue toKeyValue(ConfigurationSetting setting) {
return new KeyValue()
.setKey(setting.getKey())
.setValue(setting.getValue())
.setLabel(setting.getLabel())
.setContentType(setting.getContentType())
.setEtag(setting.getETag())
.setLastModified(setting.getLastModified())
.setLocked(setting.isReadOnly())
.setTags(setting.getTags());
} | class Utility {
private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable";
public static final String APP_CONFIG_TRACING_NAMESPACE_VALUE = "Microsoft.AppConfiguration";
static final String ID = "id";
static final String DESCRIPTION = "description";
static final String DISPLAY_NAME = "display_name";
static final String ENABLED = "enabled";
static final String CONDITIONS = "conditions";
static final String CLIENT_FILTERS = "client_filters";
static final String NAME = "name";
static final String PARAMETERS = "parameters";
static final String URI = "uri";
/**
* Represents any value in Etag.
*/
public static final String ETAG_ANY = "*";
/*
* Translate public ConfigurationSetting to KeyValue autorest generated class.
*/
public static SettingFields[] toSettingFieldsArray(List<KeyValueFields> kvFieldsList) {
return kvFieldsList.stream()
.map(keyValueFields -> toSettingFields(keyValueFields))
.collect(Collectors.toList())
.toArray(new SettingFields[kvFieldsList.size()]);
}
public static SettingFields toSettingFields(KeyValueFields keyValueFields) {
return keyValueFields == null ? null : SettingFields.fromString(keyValueFields.toString());
}
public static List<KeyValueFields> toKeyValueFieldsList(SettingFields[] settingFieldsArray) {
return Arrays.stream(settingFieldsArray)
.map(settingFields -> toKeyValueFields(settingFields))
.collect(Collectors.toList());
}
public static KeyValueFields toKeyValueFields(SettingFields settingFields) {
return settingFields == null ? null : KeyValueFields.fromString(settingFields.toString());
}
/*
* Azure Configuration service requires that the ETag value is surrounded in quotation marks.
*
* @param ETag The ETag to get the value for. If null is pass in, an empty string is returned.
* @return The ETag surrounded by quotations. (ex. "ETag")
*/
private static String getETagValue(String etag) {
return (etag == null || "*".equals(etag)) ? etag : "\"" + etag + "\"";
}
/*
* Get HTTP header value, if-match. Used to perform an operation only if the targeted resource's etag matches the
* value provided.
*/
public static String getIfMatchETag(boolean ifUnchanged, ConfigurationSetting setting) {
return ifUnchanged ? getETagValue(setting.getETag()) : null;
}
/*
* Get HTTP header value, if-none-match. Used to perform an operation only if the targeted resource's etag does not
* match the value provided.
*/
public static String getIfNoneMatchETag(boolean onlyIfChanged, ConfigurationSetting setting) {
return onlyIfChanged ? getETagValue(setting.getETag()) : null;
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
public static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/**
* Enable the sync stack rest proxy.
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context enableSyncRestProxy(Context context) {
return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true);
}
public static Context addTracingNamespace(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(AZ_TRACING_NAMESPACE_KEY, APP_CONFIG_TRACING_NAMESPACE_VALUE);
}
} | class Utility {
private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable";
public static final String APP_CONFIG_TRACING_NAMESPACE_VALUE = "Microsoft.AppConfiguration";
static final String ID = "id";
static final String DESCRIPTION = "description";
static final String DISPLAY_NAME = "display_name";
static final String ENABLED = "enabled";
static final String CONDITIONS = "conditions";
static final String CLIENT_FILTERS = "client_filters";
static final String NAME = "name";
static final String PARAMETERS = "parameters";
static final String URI = "uri";
/**
* Represents any value in Etag.
*/
public static final String ETAG_ANY = "*";
/*
* Translate public ConfigurationSetting to KeyValue autorest generated class.
*/
public static SettingFields[] toSettingFieldsArray(List<KeyValueFields> kvFieldsList) {
int size = kvFieldsList.size();
SettingFields[] fields = new SettingFields[size];
for (int i = 0; i < size; i++) {
fields[i] = toSettingFields(kvFieldsList.get(i));
}
return fields;
}
public static SettingFields toSettingFields(KeyValueFields keyValueFields) {
return keyValueFields == null ? null : SettingFields.fromString(keyValueFields.toString());
}
public static List<KeyValueFields> toKeyValueFieldsList(SettingFields[] settingFieldsArray) {
int size = settingFieldsArray.length;
List<KeyValueFields> keyValueFields = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
keyValueFields.add(toKeyValueFields(settingFieldsArray[i]));
}
return keyValueFields;
}
public static KeyValueFields toKeyValueFields(SettingFields settingFields) {
return settingFields == null ? null : KeyValueFields.fromString(settingFields.toString());
}
/*
* Azure Configuration service requires that the ETag value is surrounded in quotation marks.
*
* @param ETag The ETag to get the value for. If null is pass in, an empty string is returned.
* @return The ETag surrounded by quotations. (ex. "ETag")
*/
private static String getETagValue(String etag) {
return (etag == null || "*".equals(etag)) ? etag : "\"" + etag + "\"";
}
/*
* Get HTTP header value, if-match or if-none-match.. Used to perform an operation only if the targeted resource's
* etag matches the value provided.
*/
public static String getEtag(boolean isEtagRequired, ConfigurationSetting setting) {
return isEtagRequired ? getETagValue(setting.getETag()) : null;
}
/*
* Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL.
*/
public static void validateSetting(ConfigurationSetting setting) {
Objects.requireNonNull(setting);
if (setting.getKey() == null) {
throw new IllegalArgumentException("Parameter 'key' is required and cannot be null.");
}
}
/*
* Asynchronously validate that setting and key is not null. The key is used in the service URL,
* so it cannot be null.
*/
public static Mono<ConfigurationSetting> validateSettingAsync(ConfigurationSetting setting) {
if (setting == null) {
return Mono.error(new NullPointerException("Configuration setting cannot be null"));
}
if (setting.getKey() == null) {
return Mono.error(new IllegalArgumentException("Parameter 'key' is required and cannot be null."));
}
return Mono.just(setting);
}
/**
* Enable the sync stack rest proxy.
*
* @param context It offers a means of passing arbitrary data (key-value pairs) to pipeline policies.
* Most applications do not need to pass arbitrary data to the pipeline and can pass Context.NONE or null.
*
* @return The Context.
*/
public static Context enableSyncRestProxy(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true);
}
public static Context addTracingNamespace(Context context) {
context = context == null ? Context.NONE : context;
return context.addData(AZ_TRACING_NAMESPACE_KEY, APP_CONFIG_TRACING_NAMESPACE_VALUE);
}
} |
https://github.com/Azure/azure-sdk-for-java/issues/33991 | public Mono<ConfigurationSetting> addConfigurationSetting(String key, String label, String value) {
return addConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
} | return addConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value)); | public Mono<ConfigurationSetting> addConfigurationSetting(String key, String label, String value) {
return addConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
} | class ConfigurationAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationAsyncClient.class);
private final AzureAppConfigurationImpl serviceClient;
private final SyncTokenPolicy syncTokenPolicy;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceClient The {@link AzureAppConfigurationImpl} that the client routes its request through.
* @param syncTokenPolicy {@link SyncTokenPolicy} to be used to update the external synchronization token to ensure
* service requests receive up-to-date values.
*/
ConfigurationAsyncClient(AzureAppConfigurationImpl serviceClient, SyncTokenPolicy syncTokenPolicy) {
this.serviceClient = serviceClient;
this.syncTokenPolicy = syncTokenPolicy;
}
/**
* Gets the service endpoint for the Azure App Configuration instance.
*
* @return the service endpoint for the Azure App Configuration instance.
*/
public String getEndpoint() {
return serviceClient.getEndpoint();
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add. If {@code null} no label will be used.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addConfigurationSetting(ConfigurationSetting setting) {
return addConfigurationSettingWithResponse(setting).map(Response::getValue);
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
* <pre>
* client.addConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .subscribe&
* ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addConfigurationSettingWithResponse(ConfigurationSetting setting) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.putKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
null, ETAG_ANY, toKeyValue(setting),
addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response, toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, If {@code null} no label will be used.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(String key, String label, String value) {
return setConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(ConfigurationSetting setting) {
return setConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* setting's ETag matches. If the ETag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
* <pre>
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* &
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is read-only, or an ETag was provided but does not match the service's current ETag
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's ETag does not match, or the setting exists and is
* read-only.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.putKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
getIfMatchETag(ifUnchanged, setting), null, toKeyValue(setting),
addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label) {
return getConfigurationSetting(key, label, null);
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code acceptDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* "prodDBConnection", null, OffsetDateTime.now&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label, OffsetDateTime acceptDateTime) {
return getConfigurationSettingWithResponse(new ConfigurationSetting().setKey(key).setLabel(label),
acceptDateTime, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param setting The setting to retrieve.
*
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(ConfigurationSetting setting) {
return getConfigurationSettingWithResponse(setting, null, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
* <pre>
* client.getConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
*
* @param setting The setting to retrieve.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getConfigurationSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime acceptDateTime, boolean ifChanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.getKeyValueWithResponseAsync(
setting.getKey(),
setting.getLabel(),
acceptDateTime == null ? null : acceptDateTime.toString(),
null,
getIfNoneMatchETag(ifChanged, setting),
null,
addTracingNamespace(context))
.onErrorResume(HttpResponseException.class,
(Function<Throwable, Mono<ResponseBase<GetKeyValueHeaders, KeyValue>>>)
throwable -> {
HttpResponseException e = (HttpResponseException) throwable;
HttpResponse httpResponse = e.getResponse();
if (httpResponse.getStatusCode() == 304) {
return Mono.just(new ResponseBase<GetKeyValueHeaders, KeyValue>(
httpResponse.getRequest(),
httpResponse.getStatusCode(),
httpResponse.getHeaders(),
null,
null));
}
return Mono.error(throwable);
})
.map(response ->
new SimpleResponse<>(response, toConfigurationSetting(response.getValue())))
);
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete. If {@code null} no label will be used.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(String key, String label) {
return deleteConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label));
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
*
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(ConfigurationSetting setting) {
return deleteConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
* <pre>
* client.deleteConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
try {
validateSetting(setting);
return withContext(
context -> serviceClient.deleteKeyValueWithResponseAsync(setting.getKey(), setting.getLabel(),
getIfMatchETag(ifUnchanged, setting), addTracingNamespace(context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue()))));
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Sets the read-only status for the {@link ConfigurationSetting} that matches the {@code key}, the optional
* {@code label}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .contextWrite&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to set to be read-only.
* @param label The label of configuration setting to read-only. If {@code null} no label will be used.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label, boolean isReadOnly) {
return setReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), isReadOnly);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
*
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(ConfigurationSetting setting, boolean isReadOnly) {
return setReadOnlyWithResponse(setting, isReadOnly).map(Response::getValue);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .contextWrite&
* .subscribe&
* ConfigurationSetting result = response.getValue&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return A REST response containing the read-only or not read-only ConfigurationSetting if {@code isReadOnly}
* is true or null, or false respectively. Or return {@code null} if the setting didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting,
boolean isReadOnly) {
try {
validateSetting(setting);
return withContext(
context -> {
final String key = setting.getKey();
final String label = setting.getLabel();
context = addTracingNamespace(context);
return (isReadOnly
? serviceClient.putLockWithResponseAsync(key, label, null, null, context)
: serviceClient.deleteLockWithResponseAsync(key, label, null, null, context))
.map(response -> new SimpleResponse<>(response,
toConfigurationSetting(response.getValue())));
});
} catch (RuntimeException ex) {
return monoError(LOGGER, ex);
}
}
/**
* Fetches the configuration settings that match the {@code selector}. If {@code selector} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
* <pre>
* client.listConfigurationSettings&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code selector}. If no options were provided, the Flux
* contains all of the current settings in the service.
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listConfigurationSettings(SettingSelector selector) {
try {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getKeyValuesSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
null,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null))),
nextLink -> withContext(
context -> serviceClient.getKeyValuesNextSinglePageAsync(
nextLink,
acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null)))
);
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(LOGGER, ex));
}
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* Revisions expire after a period of time, see <a href="https:
* for more information.
*
* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code selector}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
* <pre>
* client.listRevisions&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listRevisions(SettingSelector selector) {
try {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getRevisionsSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(),
null))),
nextLink -> withContext(
context ->
serviceClient.getRevisionsNextSinglePageAsync(nextLink, acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> new PagedResponseBase<>(
pagedResponse.getRequest(),
pagedResponse.getStatusCode(),
pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(keyValue -> toConfigurationSetting(keyValue))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(), null))));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(LOGGER, ex));
}
}
/**
* Adds an external synchronization token to ensure service requests receive up-to-date values.
*
* @param token an external synchronization token to ensure service requests receive up-to-date values.
* @throws NullPointerException if the given token is null.
*/
public void updateSyncToken(String token) {
Objects.requireNonNull(token, "'token' cannot be null.");
syncTokenPolicy.updateSyncToken(token);
}
} | class ConfigurationAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationAsyncClient.class);
private final AzureAppConfigurationImpl serviceClient;
private final SyncTokenPolicy syncTokenPolicy;
/**
* Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}.
* Each service call goes through the {@code pipeline}.
*
* @param serviceClient The {@link AzureAppConfigurationImpl} that the client routes its request through.
* @param syncTokenPolicy {@link SyncTokenPolicy} to be used to update the external synchronization token to ensure
* service requests receive up-to-date values.
*/
ConfigurationAsyncClient(AzureAppConfigurationImpl serviceClient, SyncTokenPolicy syncTokenPolicy) {
this.serviceClient = serviceClient;
this.syncTokenPolicy = syncTokenPolicy;
}
/**
* Gets the service endpoint for the Azure App Configuration instance.
*
* @return the service endpoint for the Azure App Configuration instance.
*/
public String getEndpoint() {
return serviceClient.getEndpoint();
}
/**
* Adds a configuration value in the service if that key does not exist. The {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS" and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param key The key of the configuration setting to add.
* @param label The label of the configuration setting to add. If {@code null} no label will be used.
* @param value The value associated with this configuration setting key.
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If a ConfigurationSetting with the same key exists.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
* <pre>
* client.addConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created, or {@code null} if a key collision occurs or the key
* is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> addConfigurationSetting(ConfigurationSetting setting) {
return addConfigurationSettingWithResponse(setting).map(Response::getValue);
}
/**
* Adds a configuration value in the service if that key and label does not exist. The label value of the
* ConfigurationSetting is optional.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
* <pre>
* client.addConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .subscribe&
* ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse
*
* @param setting The setting to add based on its key and optional label combination.
* @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs
* or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> addConfigurationSettingWithResponse(ConfigurationSetting setting) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.putKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), null, ETAG_ANY, toKeyValue(settingInternal),
addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Creates or updates a configuration value in the service with the given key. the {@code label} is optional.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param key The key of the configuration setting to create or update.
* @param label The label of the configuration setting to create or update, If {@code null} no label will be used.
* @param value The value of this configuration setting.
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(String key, String label, String value) {
return setConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value));
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", "westUS" and value "db_connection"</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
* <pre>
* client.setConfigurationSetting&
* .subscribe&
* response.getKey&
* &
* client.setConfigurationSetting&
* new ConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting
*
* @param setting The setting to add based on its key and optional label combination.
*
* @return The {@link ConfigurationSetting} that was created or updated, or an empty Mono if the key is an invalid
* value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If the setting exists and is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setConfigurationSetting(ConfigurationSetting setting) {
return setConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Creates or updates a configuration value in the service. Partial updates are not supported and the entire
* configuration setting is updated.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* setting's ETag matches. If the ETag's value is equal to the wildcard character ({@code "*"}), the setting will
* always be updated.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p>
* <p>Update setting's value "db_connection" to "updated_db_connection"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
* <pre>
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* &
* client.setConfigurationSettingWithResponse&
* .setValue&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse
*
* @param setting The setting to create or update based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an
* invalid value, the setting is read-only, or an ETag was provided but does not match the service's current ETag
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceModifiedException If the {@link ConfigurationSetting
* wildcard character, and the current configuration value's ETag does not match, or the setting exists and is
* read-only.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.putKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), getEtag(ifUnchanged, settingInternal), null,
toKeyValue(settingInternal), addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, and the optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label) {
return getConfigurationSetting(key, label, null);
}
/**
* Attempts to get a ConfigurationSetting that matches the {@code key}, the optional {@code label}, and the optional
* {@code acceptDateTime} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* "prodDBConnection", null, OffsetDateTime.now&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param key The key of the setting to retrieve.
* @param label The label of the configuration setting to retrieve. If {@code null} no label will be used.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(String key, String label, OffsetDateTime acceptDateTime) {
return getConfigurationSettingWithResponse(new ConfigurationSetting().setKey(key).setLabel(label),
acceptDateTime, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
* <pre>
* client.getConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting
*
* @param setting The setting to retrieve.
*
* @return The {@link ConfigurationSetting} stored in the service, or an empty Mono if the configuration value does
* not exist or the key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> getConfigurationSetting(ConfigurationSetting setting) {
return getConfigurationSettingWithResponse(setting, null, false).map(Response::getValue);
}
/**
* Attempts to get the ConfigurationSetting with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
* <pre>
* client.getConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse
*
* @param setting The setting to retrieve.
* @param acceptDateTime Datetime to access a past state of the configuration setting. If {@code null}
* then the current state of the configuration setting will be returned.
* @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* If-None-Match header.
* @return A REST response containing the {@link ConfigurationSetting} stored in the service, or {@code null} if
* didn't exist. {@code null} is also returned if the configuration value does not exist or the key is an invalid
* value (which will also throw HttpResponseException described below).
* @throws NullPointerException If {@code setting} is {@code null}.
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist.
* @throws HttpResponseException If the {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> getConfigurationSettingWithResponse(ConfigurationSetting setting,
OffsetDateTime acceptDateTime, boolean ifChanged) {
return withContext(
context -> validateSettingAsync(setting).flatMap(
settingInternal ->
serviceClient.getKeyValueWithResponseAsync(settingInternal.getKey(), settingInternal.getLabel(),
acceptDateTime == null ? null : acceptDateTime.toString(), null,
getEtag(ifChanged, settingInternal), null, addTracingNamespace(context))
.onErrorResume(
HttpResponseException.class,
(Function<Throwable, Mono<ResponseBase<GetKeyValueHeaders, KeyValue>>>) throwable -> {
HttpResponseException e = (HttpResponseException) throwable;
HttpResponse httpResponse = e.getResponse();
if (httpResponse.getStatusCode() == 304) {
return Mono.just(new ResponseBase<GetKeyValueHeaders, KeyValue>(
httpResponse.getRequest(), httpResponse.getStatusCode(),
httpResponse.getHeaders(), null, null));
}
return Mono.error(throwable);
})
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Deletes the ConfigurationSetting with a matching {@code key} and optional {@code label} combination.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param key The key of configuration setting to delete.
* @param label The label of configuration setting to delete. If {@code null} no label will be used.
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(String key, String label) {
return deleteConfigurationSetting(new ConfigurationSetting().setKey(key).setLabel(label));
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
* <pre>
* client.deleteConfigurationSetting&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
*
* @return The deleted ConfigurationSetting or an empty Mono is also returned if the {@code key} is an invalid value
* (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> deleteConfigurationSetting(ConfigurationSetting setting) {
return deleteConfigurationSettingWithResponse(setting, false).map(Response::getValue);
}
/**
* Deletes the {@link ConfigurationSetting} with a matching {@link ConfigurationSetting
* {@link ConfigurationSetting
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* If {@link ConfigurationSetting
* the setting is <b>only</b> deleted if the ETag matches the current ETag; this means that no one has updated the
* ConfigurationSetting yet.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the setting with the key-label "prodDBConnection"-"westUS"</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
* <pre>
* client.deleteConfigurationSettingWithResponse&
* new ConfigurationSetting&
* .contextWrite&
* .subscribe&
* final ConfigurationSetting responseSetting = response.getValue&
* System.out.printf&
* responseSetting.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse
*
* @param setting The setting to delete based on its key, optional label and optional ETag combination.
* @param ifUnchanged Flag indicating if the {@code setting} {@link ConfigurationSetting
* IF-MATCH header.
* @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null}
* is also returned if the {@link ConfigurationSetting
* {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws NullPointerException When {@code setting} is {@code null}.
* @throws ResourceModifiedException If {@code setting} is read-only.
* @throws ResourceNotFoundException If {@link ConfigurationSetting
* character, and does not match the current ETag value.
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> deleteConfigurationSettingWithResponse(ConfigurationSetting setting,
boolean ifUnchanged) {
return withContext(context -> validateSettingAsync(setting).flatMap(
settingInternal -> serviceClient.deleteKeyValueWithResponseAsync(settingInternal.getKey(),
settingInternal.getLabel(), getEtag(ifUnchanged, settingInternal), addTracingNamespace(context))
.map(response -> toConfigurationSettingWithResponse(response))));
}
/**
* Sets the read-only status for the {@link ConfigurationSetting} that matches the {@code key}, the optional
* {@code label}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .contextWrite&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param key The key of configuration setting to set to be read-only.
* @param label The label of configuration setting to read-only. If {@code null} no label will be used.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@code key} is {@code null}.
* @throws HttpResponseException If {@code key} is an empty string.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(String key, String label, boolean isReadOnly) {
return setReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), isReadOnly);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* response.getKey&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
* <pre>
* client.setReadOnly&
* .subscribe&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnly
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
*
* @return The {@link ConfigurationSetting} that is read-only, or an empty Mono if a key collision occurs or the
* key is an invalid value (which will also throw HttpResponseException described below).
*
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ConfigurationSetting> setReadOnly(ConfigurationSetting setting, boolean isReadOnly) {
return setReadOnlyWithResponse(setting, isReadOnly).map(Response::getValue);
}
/**
* Sets the read-only status for the {@link ConfigurationSetting}.
*
* For more configuration setting types, see {@link FeatureFlagConfigurationSetting} and
* {@link SecretReferenceConfigurationSetting}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Set the setting to read-only with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .subscribe&
* final ConfigurationSetting result = response.getValue&
* System.out.printf&
* result.getKey&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* <p>Clear read-only of the setting with the key-label "prodDBConnection"-"westUS".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
* <pre>
* client.setReadOnlyWithResponse&
* .contextWrite&
* .subscribe&
* ConfigurationSetting result = response.getValue&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse
*
* @param setting The configuration setting to set to read-only or not read-only based on the {@code isReadOnly}.
* @param isReadOnly Flag used to set the read-only status of the configuration. {@code true} will put the
* configuration into a read-only state, {@code false} will clear the state.
* @return A REST response containing the read-only or not read-only ConfigurationSetting if {@code isReadOnly}
* is true or null, or false respectively. Or return {@code null} if the setting didn't exist.
* {@code null} is also returned if the {@link ConfigurationSetting
* (which will also throw HttpResponseException described below).
* @throws IllegalArgumentException If {@link ConfigurationSetting
* @throws HttpResponseException If {@link ConfigurationSetting
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting,
boolean isReadOnly) {
return withContext(context -> validateSettingAsync(setting).flatMap(
settingInternal -> {
final String key = settingInternal.getKey();
final String label = settingInternal.getLabel();
final Context contextInternal = addTracingNamespace(context);
return (isReadOnly
? serviceClient.putLockWithResponseAsync(key, label, null, null, contextInternal)
: serviceClient.deleteLockWithResponseAsync(key, label, null, null, contextInternal))
.map(response -> toConfigurationSettingWithResponse(response));
}));
}
/**
* Fetches the configuration settings that match the {@code selector}. If {@code selector} is {@code null}, then all
* the {@link ConfigurationSetting configuration settings} are fetched with their current values.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all settings that use the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
* <pre>
* client.listConfigurationSettings&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings -->
*
* @param selector Optional. Selector to filter configuration setting results from the service.
* @return A Flux of ConfigurationSettings that matches the {@code selector}. If no options were provided, the Flux
* contains all of the current settings in the service.
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listConfigurationSettings(SettingSelector selector) {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getKeyValuesSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
null,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))),
nextLink -> withContext(
context -> serviceClient.getKeyValuesNextSinglePageAsync(
nextLink,
acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse)))
);
}
/**
* Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided
* in descending order from their {@link ConfigurationSetting
* Revisions expire after a period of time, see <a href="https:
* for more information.
*
* If {@code selector} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched
* in their current state. Otherwise, the results returned match the parameters given in {@code selector}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p>
*
* <!-- src_embed com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
* <pre>
* client.listRevisions&
* .contextWrite&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions -->
*
* @param selector Optional. Used to filter configuration setting revisions from the service.
* @return Revisions of the ConfigurationSetting
* @throws HttpResponseException If a client or service error occurs, such as a 404, 409, 429 or 500.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ConfigurationSetting> listRevisions(SettingSelector selector) {
final String keyFilter = selector == null ? null : selector.getKeyFilter();
final String labelFilter = selector == null ? null : selector.getLabelFilter();
final String acceptDateTime = selector == null ? null : selector.getAcceptDateTime();
final List<KeyValueFields> keyValueFields = selector == null ? null
: toKeyValueFieldsList(selector.getFields());
return new PagedFlux<>(
() -> withContext(
context -> serviceClient.getRevisionsSinglePageAsync(
keyFilter,
labelFilter,
null,
acceptDateTime,
keyValueFields,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))),
nextLink -> withContext(
context ->
serviceClient.getRevisionsNextSinglePageAsync(nextLink, acceptDateTime,
addTracingNamespace(context))
.map(pagedResponse -> toConfigurationSettingWithPagedResponse(pagedResponse))));
}
/**
* Adds an external synchronization token to ensure service requests receive up-to-date values.
*
* @param token an external synchronization token to ensure service requests receive up-to-date values.
* @throws NullPointerException if the given token is null.
*/
public void updateSyncToken(String token) {
Objects.requireNonNull(token, "'token' cannot be null.");
syncTokenPolicy.updateSyncToken(token);
}
} |
Use the constant PHONE_NUMBER here as well. `return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER.length()));` | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER)) {
return new PhoneNumberIdentifier(rawId.substring("4:".length()));
}
final String[] segments = rawId.split(":");
if (segments.length < 3) {
if (segments.length == 2 && segments[0].equals("28")) {
return new MicrosoftBotIdentifier(segments[1], true).setCloudEnvironment(CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = rawId.substring(prefix.length());
if (TEAM_USER_ANONYMOUS.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAM_USER_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAM_USER_DOD_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAM_USER_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (STRING.equals(prefix) || SPOOL_USER.equals(prefix) || ACS_USER_DOD_CLOUD.equals(prefix) || ACS_USER_GCCH_CLOUD.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | return new PhoneNumberIdentifier(rawId.substring("4:".length())); | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER_PREFIX)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER_PREFIX.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_PREFIX)) {
return new MicrosoftBotIdentifier(segments[1], false, CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = segments[2];
if (TEAMS_USER_ANONYMOUS_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER_PREFIX.equals(prefix) || SPOOL_USER_PREFIX.equals(prefix) || ACS_USER_DOD_CLOUD_PREFIX.equals(prefix) || ACS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | class CommunicationIdentifier {
/**
* Prefix for a phone number.
*/
protected static final String PHONE_NUMBER = "4:";
/**
* Prefix for a bot.
*/
protected static final String BOT = "28:";
/**
* Prefix for a bot with public cloud.
*/
protected static final String BOT_PUBLIC_CLOUD = "28:orgid:";
/**
* Prefix for a bot with DOD cloud.
*/
protected static final String BOT_DOD_CLOUD = "28:dod:";
/**
* Prefix for a global bot with DOD cloud.
*/
protected static final String BOT_DOD_CLOUD_GLOBAL = "28:dod-global:";
/**
* Prefix for a bot with GCCH cloud.
*/
protected static final String BOT_GCCH_CLOUD = "28:gcch:";
/**
* Prefix for a global bot with GCCH cloud.
*/
protected static final String BOT_GCCH_CLOUD_GLOBAL = "28:gcch-global:";
/**
* Prefix for an anonymous Teams user.
*/
protected static final String TEAM_USER_ANONYMOUS = "8:teamsvisitor:";
/**
* Prefix for a Teams user with public cloud.
*/
protected static final String TEAM_USER_PUBLIC_CLOUD = "8:orgid:";
/**
* Prefix for a Teams user with DOD cloud.
*/
protected static final String TEAM_USER_DOD_CLOUD = "8:dod:";
/**
* Prefix for a Teams user with GCCH cloud.
*/
protected static final String TEAM_USER_GCCH_CLOUD = "8:gcch:";
/**
* Prefix for an ACS user.
*/
protected static final String STRING = "8:acs:";
/**
* Prefix for an ACS user with DOD cloud.
*/
protected static final String ACS_USER_DOD_CLOUD = "8:dod-acs:";
/**
* Prefix for an ACS user with GCCH cloud.
*/
protected static final String ACS_USER_GCCH_CLOUD = "8:gcch-acs:";
/**
* Prefix for a Spool user.
*/
protected static final String SPOOL_USER = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} | class CommunicationIdentifier {
static final String PHONE_NUMBER_PREFIX = "4:";
static final String BOT_PREFIX = "28:";
static final String BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:";
static final String BOT_DOD_CLOUD_PREFIX = "28:dod:";
static final String BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:";
static final String BOT_GCCH_CLOUD_PREFIX = "28:gcch:";
static final String BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:";
static final String TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:";
static final String TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:";
static final String TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:";
static final String TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:";
static final String ACS_USER_PREFIX = "8:acs:";
static final String ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:";
static final String ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:";
static final String SPOOL_USER_PREFIX = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} |
Thanks, updated | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER)) {
return new PhoneNumberIdentifier(rawId.substring("4:".length()));
}
final String[] segments = rawId.split(":");
if (segments.length < 3) {
if (segments.length == 2 && segments[0].equals("28")) {
return new MicrosoftBotIdentifier(segments[1], true).setCloudEnvironment(CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = rawId.substring(prefix.length());
if (TEAM_USER_ANONYMOUS.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAM_USER_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAM_USER_DOD_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAM_USER_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (STRING.equals(prefix) || SPOOL_USER.equals(prefix) || ACS_USER_DOD_CLOUD.equals(prefix) || ACS_USER_GCCH_CLOUD.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | return new PhoneNumberIdentifier(rawId.substring("4:".length())); | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER_PREFIX)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER_PREFIX.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_PREFIX)) {
return new MicrosoftBotIdentifier(segments[1], false, CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = segments[2];
if (TEAMS_USER_ANONYMOUS_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER_PREFIX.equals(prefix) || SPOOL_USER_PREFIX.equals(prefix) || ACS_USER_DOD_CLOUD_PREFIX.equals(prefix) || ACS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | class CommunicationIdentifier {
/**
* Prefix for a phone number.
*/
protected static final String PHONE_NUMBER = "4:";
/**
* Prefix for a bot.
*/
protected static final String BOT = "28:";
/**
* Prefix for a bot with public cloud.
*/
protected static final String BOT_PUBLIC_CLOUD = "28:orgid:";
/**
* Prefix for a bot with DOD cloud.
*/
protected static final String BOT_DOD_CLOUD = "28:dod:";
/**
* Prefix for a global bot with DOD cloud.
*/
protected static final String BOT_DOD_CLOUD_GLOBAL = "28:dod-global:";
/**
* Prefix for a bot with GCCH cloud.
*/
protected static final String BOT_GCCH_CLOUD = "28:gcch:";
/**
* Prefix for a global bot with GCCH cloud.
*/
protected static final String BOT_GCCH_CLOUD_GLOBAL = "28:gcch-global:";
/**
* Prefix for an anonymous Teams user.
*/
protected static final String TEAM_USER_ANONYMOUS = "8:teamsvisitor:";
/**
* Prefix for a Teams user with public cloud.
*/
protected static final String TEAM_USER_PUBLIC_CLOUD = "8:orgid:";
/**
* Prefix for a Teams user with DOD cloud.
*/
protected static final String TEAM_USER_DOD_CLOUD = "8:dod:";
/**
* Prefix for a Teams user with GCCH cloud.
*/
protected static final String TEAM_USER_GCCH_CLOUD = "8:gcch:";
/**
* Prefix for an ACS user.
*/
protected static final String STRING = "8:acs:";
/**
* Prefix for an ACS user with DOD cloud.
*/
protected static final String ACS_USER_DOD_CLOUD = "8:dod-acs:";
/**
* Prefix for an ACS user with GCCH cloud.
*/
protected static final String ACS_USER_GCCH_CLOUD = "8:gcch-acs:";
/**
* Prefix for a Spool user.
*/
protected static final String SPOOL_USER = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} | class CommunicationIdentifier {
static final String PHONE_NUMBER_PREFIX = "4:";
static final String BOT_PREFIX = "28:";
static final String BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:";
static final String BOT_DOD_CLOUD_PREFIX = "28:dod:";
static final String BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:";
static final String BOT_GCCH_CLOUD_PREFIX = "28:gcch:";
static final String BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:";
static final String TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:";
static final String TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:";
static final String TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:";
static final String TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:";
static final String ACS_USER_PREFIX = "8:acs:";
static final String ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:";
static final String ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:";
static final String SPOOL_USER_PREFIX = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} |
just reuse the third item, instead of substring the rawId again | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_GLOBAL)) {
return new MicrosoftBotIdentifier(segments[1], CommunicationCloudEnvironment.PUBLIC, true);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = rawId.substring(prefix.length());
if (TEAMS_USER_ANONYMOUS.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER.equals(prefix) || SPOOL_USER.equals(prefix) || ACS_USER_DOD_CLOUD.equals(prefix) || ACS_USER_GCCH_CLOUD.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, true);
} else if (BOT_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.PUBLIC, false);
} else if (BOT_DOD_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, true);
} else if (BOT_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, false);
} else if (BOT_DOD_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, false);
}
return new UnknownIdentifier(rawId);
} | final String suffix = rawId.substring(prefix.length()); | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER_PREFIX)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER_PREFIX.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_PREFIX)) {
return new MicrosoftBotIdentifier(segments[1], false, CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = segments[2];
if (TEAMS_USER_ANONYMOUS_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER_PREFIX.equals(prefix) || SPOOL_USER_PREFIX.equals(prefix) || ACS_USER_DOD_CLOUD_PREFIX.equals(prefix) || ACS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | class CommunicationIdentifier {
/**
* Prefix for a phone number.
*/
static final String PHONE_NUMBER = "4:";
/**
* Prefix for a bot.
*/
static final String BOT_GLOBAL = "28:";
/**
* Prefix for a bot with public cloud.
*/
static final String BOT_PUBLIC_CLOUD = "28:orgid:";
/**
* Prefix for a bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD = "28:dod:";
/**
* Prefix for a global bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD_GLOBAL = "28:dod-global:";
/**
* Prefix for a bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD = "28:gcch:";
/**
* Prefix for a global bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD_GLOBAL = "28:gcch-global:";
/**
* Prefix for an anonymous Teams user.
*/
static final String TEAMS_USER_ANONYMOUS = "8:teamsvisitor:";
/**
* Prefix for a Teams user with public cloud.
*/
static final String TEAMS_USER_PUBLIC_CLOUD = "8:orgid:";
/**
* Prefix for a Teams user with DOD cloud.
*/
static final String TEAMS_USER_DOD_CLOUD = "8:dod:";
/**
* Prefix for a Teams user with GCCH cloud.
*/
static final String TEAMS_USER_GCCH_CLOUD = "8:gcch:";
/**
* Prefix for an ACS user.
*/
static final String ACS_USER = "8:acs:";
/**
* Prefix for an ACS user with DOD cloud.
*/
static final String ACS_USER_DOD_CLOUD = "8:dod-acs:";
/**
* Prefix for an ACS user with GCCH cloud.
*/
static final String ACS_USER_GCCH_CLOUD = "8:gcch-acs:";
/**
* Prefix for a Spool user.
*/
static final String SPOOL_USER = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} | class CommunicationIdentifier {
static final String PHONE_NUMBER_PREFIX = "4:";
static final String BOT_PREFIX = "28:";
static final String BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:";
static final String BOT_DOD_CLOUD_PREFIX = "28:dod:";
static final String BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:";
static final String BOT_GCCH_CLOUD_PREFIX = "28:gcch:";
static final String BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:";
static final String TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:";
static final String TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:";
static final String TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:";
static final String TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:";
static final String ACS_USER_PREFIX = "8:acs:";
static final String ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:";
static final String ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:";
static final String SPOOL_USER_PREFIX = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} |
wdyt about replacing it with a switch block? it looks more readable for android instead of calling equals each time. | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_GLOBAL)) {
return new MicrosoftBotIdentifier(segments[1], CommunicationCloudEnvironment.PUBLIC, true);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = rawId.substring(prefix.length());
if (TEAMS_USER_ANONYMOUS.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER.equals(prefix) || SPOOL_USER.equals(prefix) || ACS_USER_DOD_CLOUD.equals(prefix) || ACS_USER_GCCH_CLOUD.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, true);
} else if (BOT_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.PUBLIC, false);
} else if (BOT_DOD_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, true);
} else if (BOT_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, false);
} else if (BOT_DOD_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, false);
}
return new UnknownIdentifier(rawId);
} | if (TEAMS_USER_ANONYMOUS.equals(prefix)) { | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER_PREFIX)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER_PREFIX.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_PREFIX)) {
return new MicrosoftBotIdentifier(segments[1], false, CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = segments[2];
if (TEAMS_USER_ANONYMOUS_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER_PREFIX.equals(prefix) || SPOOL_USER_PREFIX.equals(prefix) || ACS_USER_DOD_CLOUD_PREFIX.equals(prefix) || ACS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | class CommunicationIdentifier {
/**
* Prefix for a phone number.
*/
static final String PHONE_NUMBER = "4:";
/**
* Prefix for a bot.
*/
static final String BOT_GLOBAL = "28:";
/**
* Prefix for a bot with public cloud.
*/
static final String BOT_PUBLIC_CLOUD = "28:orgid:";
/**
* Prefix for a bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD = "28:dod:";
/**
* Prefix for a global bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD_GLOBAL = "28:dod-global:";
/**
* Prefix for a bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD = "28:gcch:";
/**
* Prefix for a global bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD_GLOBAL = "28:gcch-global:";
/**
* Prefix for an anonymous Teams user.
*/
static final String TEAMS_USER_ANONYMOUS = "8:teamsvisitor:";
/**
* Prefix for a Teams user with public cloud.
*/
static final String TEAMS_USER_PUBLIC_CLOUD = "8:orgid:";
/**
* Prefix for a Teams user with DOD cloud.
*/
static final String TEAMS_USER_DOD_CLOUD = "8:dod:";
/**
* Prefix for a Teams user with GCCH cloud.
*/
static final String TEAMS_USER_GCCH_CLOUD = "8:gcch:";
/**
* Prefix for an ACS user.
*/
static final String ACS_USER = "8:acs:";
/**
* Prefix for an ACS user with DOD cloud.
*/
static final String ACS_USER_DOD_CLOUD = "8:dod-acs:";
/**
* Prefix for an ACS user with GCCH cloud.
*/
static final String ACS_USER_GCCH_CLOUD = "8:gcch-acs:";
/**
* Prefix for a Spool user.
*/
static final String SPOOL_USER = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} | class CommunicationIdentifier {
static final String PHONE_NUMBER_PREFIX = "4:";
static final String BOT_PREFIX = "28:";
static final String BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:";
static final String BOT_DOD_CLOUD_PREFIX = "28:dod:";
static final String BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:";
static final String BOT_GCCH_CLOUD_PREFIX = "28:gcch:";
static final String BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:";
static final String TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:";
static final String TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:";
static final String TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:";
static final String TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:";
static final String ACS_USER_PREFIX = "8:acs:";
static final String ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:";
static final String ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:";
static final String SPOOL_USER_PREFIX = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} |
java has switches? 😮 (just joking 😁) | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_GLOBAL)) {
return new MicrosoftBotIdentifier(segments[1], CommunicationCloudEnvironment.PUBLIC, true);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = rawId.substring(prefix.length());
if (TEAMS_USER_ANONYMOUS.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER.equals(prefix) || SPOOL_USER.equals(prefix) || ACS_USER_DOD_CLOUD.equals(prefix) || ACS_USER_GCCH_CLOUD.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, true);
} else if (BOT_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.PUBLIC, false);
} else if (BOT_DOD_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, true);
} else if (BOT_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, false);
} else if (BOT_DOD_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, false);
}
return new UnknownIdentifier(rawId);
} | if (TEAMS_USER_ANONYMOUS.equals(prefix)) { | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER_PREFIX)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER_PREFIX.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_PREFIX)) {
return new MicrosoftBotIdentifier(segments[1], false, CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = segments[2];
if (TEAMS_USER_ANONYMOUS_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER_PREFIX.equals(prefix) || SPOOL_USER_PREFIX.equals(prefix) || ACS_USER_DOD_CLOUD_PREFIX.equals(prefix) || ACS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | class CommunicationIdentifier {
/**
* Prefix for a phone number.
*/
static final String PHONE_NUMBER = "4:";
/**
* Prefix for a bot.
*/
static final String BOT_GLOBAL = "28:";
/**
* Prefix for a bot with public cloud.
*/
static final String BOT_PUBLIC_CLOUD = "28:orgid:";
/**
* Prefix for a bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD = "28:dod:";
/**
* Prefix for a global bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD_GLOBAL = "28:dod-global:";
/**
* Prefix for a bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD = "28:gcch:";
/**
* Prefix for a global bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD_GLOBAL = "28:gcch-global:";
/**
* Prefix for an anonymous Teams user.
*/
static final String TEAMS_USER_ANONYMOUS = "8:teamsvisitor:";
/**
* Prefix for a Teams user with public cloud.
*/
static final String TEAMS_USER_PUBLIC_CLOUD = "8:orgid:";
/**
* Prefix for a Teams user with DOD cloud.
*/
static final String TEAMS_USER_DOD_CLOUD = "8:dod:";
/**
* Prefix for a Teams user with GCCH cloud.
*/
static final String TEAMS_USER_GCCH_CLOUD = "8:gcch:";
/**
* Prefix for an ACS user.
*/
static final String ACS_USER = "8:acs:";
/**
* Prefix for an ACS user with DOD cloud.
*/
static final String ACS_USER_DOD_CLOUD = "8:dod-acs:";
/**
* Prefix for an ACS user with GCCH cloud.
*/
static final String ACS_USER_GCCH_CLOUD = "8:gcch-acs:";
/**
* Prefix for a Spool user.
*/
static final String SPOOL_USER = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} | class CommunicationIdentifier {
static final String PHONE_NUMBER_PREFIX = "4:";
static final String BOT_PREFIX = "28:";
static final String BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:";
static final String BOT_DOD_CLOUD_PREFIX = "28:dod:";
static final String BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:";
static final String BOT_GCCH_CLOUD_PREFIX = "28:gcch:";
static final String BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:";
static final String TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:";
static final String TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:";
static final String TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:";
static final String TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:";
static final String ACS_USER_PREFIX = "8:acs:";
static final String ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:";
static final String ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:";
static final String SPOOL_USER_PREFIX = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} |
@AikoBB the version of Java used in the pipelines doesn't support switches. I've made this change at first and had to roll back it. | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_GLOBAL)) {
return new MicrosoftBotIdentifier(segments[1], CommunicationCloudEnvironment.PUBLIC, true);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = rawId.substring(prefix.length());
if (TEAMS_USER_ANONYMOUS.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER.equals(prefix) || SPOOL_USER.equals(prefix) || ACS_USER_DOD_CLOUD.equals(prefix) || ACS_USER_GCCH_CLOUD.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, true);
} else if (BOT_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.PUBLIC, false);
} else if (BOT_DOD_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, true);
} else if (BOT_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, false);
} else if (BOT_DOD_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, false);
}
return new UnknownIdentifier(rawId);
} | if (TEAMS_USER_ANONYMOUS.equals(prefix)) { | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER_PREFIX)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER_PREFIX.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_PREFIX)) {
return new MicrosoftBotIdentifier(segments[1], false, CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = segments[2];
if (TEAMS_USER_ANONYMOUS_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER_PREFIX.equals(prefix) || SPOOL_USER_PREFIX.equals(prefix) || ACS_USER_DOD_CLOUD_PREFIX.equals(prefix) || ACS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | class CommunicationIdentifier {
/**
* Prefix for a phone number.
*/
static final String PHONE_NUMBER = "4:";
/**
* Prefix for a bot.
*/
static final String BOT_GLOBAL = "28:";
/**
* Prefix for a bot with public cloud.
*/
static final String BOT_PUBLIC_CLOUD = "28:orgid:";
/**
* Prefix for a bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD = "28:dod:";
/**
* Prefix for a global bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD_GLOBAL = "28:dod-global:";
/**
* Prefix for a bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD = "28:gcch:";
/**
* Prefix for a global bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD_GLOBAL = "28:gcch-global:";
/**
* Prefix for an anonymous Teams user.
*/
static final String TEAMS_USER_ANONYMOUS = "8:teamsvisitor:";
/**
* Prefix for a Teams user with public cloud.
*/
static final String TEAMS_USER_PUBLIC_CLOUD = "8:orgid:";
/**
* Prefix for a Teams user with DOD cloud.
*/
static final String TEAMS_USER_DOD_CLOUD = "8:dod:";
/**
* Prefix for a Teams user with GCCH cloud.
*/
static final String TEAMS_USER_GCCH_CLOUD = "8:gcch:";
/**
* Prefix for an ACS user.
*/
static final String ACS_USER = "8:acs:";
/**
* Prefix for an ACS user with DOD cloud.
*/
static final String ACS_USER_DOD_CLOUD = "8:dod-acs:";
/**
* Prefix for an ACS user with GCCH cloud.
*/
static final String ACS_USER_GCCH_CLOUD = "8:gcch-acs:";
/**
* Prefix for a Spool user.
*/
static final String SPOOL_USER = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} | class CommunicationIdentifier {
static final String PHONE_NUMBER_PREFIX = "4:";
static final String BOT_PREFIX = "28:";
static final String BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:";
static final String BOT_DOD_CLOUD_PREFIX = "28:dod:";
static final String BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:";
static final String BOT_GCCH_CLOUD_PREFIX = "28:gcch:";
static final String BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:";
static final String TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:";
static final String TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:";
static final String TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:";
static final String TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:";
static final String ACS_USER_PREFIX = "8:acs:";
static final String ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:";
static final String ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:";
static final String SPOOL_USER_PREFIX = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} |
Updated | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_GLOBAL)) {
return new MicrosoftBotIdentifier(segments[1], CommunicationCloudEnvironment.PUBLIC, true);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = rawId.substring(prefix.length());
if (TEAMS_USER_ANONYMOUS.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER.equals(prefix) || SPOOL_USER.equals(prefix) || ACS_USER_DOD_CLOUD.equals(prefix) || ACS_USER_GCCH_CLOUD.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, true);
} else if (BOT_PUBLIC_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.PUBLIC, false);
} else if (BOT_DOD_CLOUD_GLOBAL.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, true);
} else if (BOT_GCCH_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.GCCH, false);
} else if (BOT_DOD_CLOUD.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, CommunicationCloudEnvironment.DOD, false);
}
return new UnknownIdentifier(rawId);
} | final String suffix = rawId.substring(prefix.length()); | public static CommunicationIdentifier fromRawId(String rawId) {
if (CoreUtils.isNullOrEmpty(rawId)) {
throw new IllegalArgumentException("The parameter [rawId] cannot be null to empty.");
}
if (rawId.startsWith(PHONE_NUMBER_PREFIX)) {
return new PhoneNumberIdentifier(rawId.substring(PHONE_NUMBER_PREFIX.length()));
}
final String[] segments = rawId.split(":");
if (segments.length != 3) {
if (segments.length == 2 && rawId.startsWith(BOT_PREFIX)) {
return new MicrosoftBotIdentifier(segments[1], false, CommunicationCloudEnvironment.PUBLIC);
}
return new UnknownIdentifier(rawId);
}
final String prefix = segments[0] + ":" + segments[1] + ":";
final String suffix = segments[2];
if (TEAMS_USER_ANONYMOUS_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, true);
} else if (TEAMS_USER_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false);
} else if (TEAMS_USER_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.DOD);
} else if (TEAMS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftTeamsUserIdentifier(suffix, false).setCloudEnvironment(CommunicationCloudEnvironment.GCCH);
} else if (ACS_USER_PREFIX.equals(prefix) || SPOOL_USER_PREFIX.equals(prefix) || ACS_USER_DOD_CLOUD_PREFIX.equals(prefix) || ACS_USER_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new CommunicationUserIdentifier(rawId);
} else if (BOT_GCCH_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.GCCH);
} else if (BOT_PUBLIC_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.PUBLIC);
} else if (BOT_DOD_CLOUD_GLOBAL_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, false, CommunicationCloudEnvironment.DOD);
} else if (BOT_GCCH_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.GCCH);
} else if (BOT_DOD_CLOUD_PREFIX.equals(prefix)) {
return new MicrosoftBotIdentifier(suffix, true, CommunicationCloudEnvironment.DOD);
}
return new UnknownIdentifier(rawId);
} | class CommunicationIdentifier {
/**
* Prefix for a phone number.
*/
static final String PHONE_NUMBER = "4:";
/**
* Prefix for a bot.
*/
static final String BOT_GLOBAL = "28:";
/**
* Prefix for a bot with public cloud.
*/
static final String BOT_PUBLIC_CLOUD = "28:orgid:";
/**
* Prefix for a bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD = "28:dod:";
/**
* Prefix for a global bot with DOD cloud.
*/
static final String BOT_DOD_CLOUD_GLOBAL = "28:dod-global:";
/**
* Prefix for a bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD = "28:gcch:";
/**
* Prefix for a global bot with GCCH cloud.
*/
static final String BOT_GCCH_CLOUD_GLOBAL = "28:gcch-global:";
/**
* Prefix for an anonymous Teams user.
*/
static final String TEAMS_USER_ANONYMOUS = "8:teamsvisitor:";
/**
* Prefix for a Teams user with public cloud.
*/
static final String TEAMS_USER_PUBLIC_CLOUD = "8:orgid:";
/**
* Prefix for a Teams user with DOD cloud.
*/
static final String TEAMS_USER_DOD_CLOUD = "8:dod:";
/**
* Prefix for a Teams user with GCCH cloud.
*/
static final String TEAMS_USER_GCCH_CLOUD = "8:gcch:";
/**
* Prefix for an ACS user.
*/
static final String ACS_USER = "8:acs:";
/**
* Prefix for an ACS user with DOD cloud.
*/
static final String ACS_USER_DOD_CLOUD = "8:dod-acs:";
/**
* Prefix for an ACS user with GCCH cloud.
*/
static final String ACS_USER_GCCH_CLOUD = "8:gcch-acs:";
/**
* Prefix for a Spool user.
*/
static final String SPOOL_USER = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} | class CommunicationIdentifier {
static final String PHONE_NUMBER_PREFIX = "4:";
static final String BOT_PREFIX = "28:";
static final String BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:";
static final String BOT_DOD_CLOUD_PREFIX = "28:dod:";
static final String BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:";
static final String BOT_GCCH_CLOUD_PREFIX = "28:gcch:";
static final String BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:";
static final String TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:";
static final String TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:";
static final String TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:";
static final String TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:";
static final String ACS_USER_PREFIX = "8:acs:";
static final String ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:";
static final String ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:";
static final String SPOOL_USER_PREFIX = "8:spool:";
private String rawId;
/**
* When storing rawIds, use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId raw id.
* @return CommunicationIdentifier
* @throws IllegalArgumentException raw id is null or empty.
*/
/**
* Returns the rawId for a given CommunicationIdentifier.
* You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @return raw id
*/
public String getRawId() {
return rawId;
}
/**
* Set full id of the identifier
* RawId is the encoded format for identifiers to store in databases or as stable keys in general.
*
* @param rawId full id of the identifier
* @return CommunicationIdentifier object itself
*/
protected CommunicationIdentifier setRawId(String rawId) {
this.rawId = rawId;
return this;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof CommunicationIdentifier)) {
return false;
}
CommunicationIdentifier thatId = (CommunicationIdentifier) that;
return this.getRawId().equals(thatId.getRawId());
}
@Override
public int hashCode() {
return getRawId().hashCode();
}
} |
Per discussion offline with Kishore, when this timeout error happens, it's already the case that there is a backoff completed - Either as a try-timeout on the client or as a delay waiting for service to respond. Additionally (as mentioned in the pr description) this aligns with what T1 is doing [code](https://github.com/Azure/azure-sdk-for-java/pull/16828/files) and [git-ticket](https://github.com/Azure/azure-service-bus-java/issues/394) | Mono<ServiceBusReceiveLink> getActiveLink() {
if (this.receiveLink != null) {
return Mono.just(this.receiveLink);
}
return Mono.defer(() -> createSessionReceiveLink()
.flatMap(link -> link.getEndpointStates()
.filter(e -> e == AmqpEndpointState.ACTIVE)
.next()
.switchIfEmpty(Mono.error(() ->
new AmqpException(true, "Session receive link completed without being active", null)))
.timeout(operationTimeout)
.then(Mono.just(link))))
.retryWhen(Retry.from(retrySignals -> retrySignals.flatMap(signal -> {
final Throwable failure = signal.failure();
LOGGER.atInfo()
.addKeyValue(ENTITY_PATH_KEY, entityPath)
.addKeyValue("attempt", signal.totalRetriesInARow())
.log("Error occurred while getting unnamed session.", failure);
if (isDisposed.get()) {
return Mono.<Long>error(new AmqpException(false, "SessionManager is already disposed.", failure,
getErrorContext()));
} else if (failure instanceof TimeoutException) {
return Mono.empty();
} else if (failure instanceof AmqpException
&& ((AmqpException) failure).getErrorCondition() == AmqpErrorCondition.TIMEOUT_ERROR) {
return Mono.empty();
} else {
final long id = System.nanoTime();
LOGGER.atInfo()
.addKeyValue(TRACKING_ID_KEY, id)
.log("Unable to acquire new session.", failure);
return Mono.<Long>error(failure)
.publishOn(Schedulers.boundedElastic())
.doOnError(e -> LOGGER.atInfo()
.addKeyValue(TRACKING_ID_KEY, id)
.log("Emitting the error signal received for session acquire attempt.", e)
);
}
})));
} | return Mono.empty(); | Mono<ServiceBusReceiveLink> getActiveLink() {
if (this.receiveLink != null) {
return Mono.just(this.receiveLink);
}
return Mono.defer(() -> createSessionReceiveLink()
.flatMap(link -> link.getEndpointStates()
.filter(e -> e == AmqpEndpointState.ACTIVE)
.next()
.switchIfEmpty(Mono.error(() ->
new AmqpException(true, "Session receive link completed without being active", null)))
.timeout(operationTimeout)
.then(Mono.just(link))))
.retryWhen(Retry.from(retrySignals -> retrySignals.flatMap(signal -> {
final Throwable failure = signal.failure();
LOGGER.atInfo()
.addKeyValue(ENTITY_PATH_KEY, entityPath)
.addKeyValue("attempt", signal.totalRetriesInARow())
.log("Error occurred while getting unnamed session.", failure);
if (isDisposed.get()) {
return Mono.<Long>error(new AmqpException(false, "SessionManager is already disposed.", failure,
getErrorContext()));
} else if (failure instanceof TimeoutException) {
return Mono.empty();
} else if (failure instanceof AmqpException
&& ((AmqpException) failure).getErrorCondition() == AmqpErrorCondition.TIMEOUT_ERROR) {
return Mono.empty();
} else {
final long id = System.nanoTime();
LOGGER.atInfo()
.addKeyValue(TRACKING_ID_KEY, id)
.log("Unable to acquire new session.", failure);
return Mono.<Long>error(failure)
.publishOn(Schedulers.boundedElastic())
.doOnError(e -> LOGGER.atInfo()
.addKeyValue(TRACKING_ID_KEY, id)
.log("Emitting the error signal received for session acquire attempt.", e)
);
}
})));
} | class ServiceBusSessionManager implements AutoCloseable {
private static final String TRACKING_ID_KEY = "trackingId";
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusSessionManager.class);
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusReceiveLink receiveLink;
private final ServiceBusConnectionProcessor connectionProcessor;
private final Duration operationTimeout;
private final MessageSerializer messageSerializer;
private final String identifier;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicBoolean isStarted = new AtomicBoolean();
private final List<Scheduler> schedulers;
private final Deque<Scheduler> availableSchedulers = new ConcurrentLinkedDeque<>();
private final Duration maxSessionLockRenewDuration;
/**
* SessionId to receiver mapping.
*/
private final ConcurrentHashMap<String, ServiceBusSessionReceiver> sessionReceivers = new ConcurrentHashMap<>();
private final EmitterProcessor<Flux<ServiceBusMessageContext>> processor;
private final FluxSink<Flux<ServiceBusMessageContext>> sessionReceiveSink;
private volatile Flux<ServiceBusMessageContext> receiveFlux;
ServiceBusSessionManager(String entityPath, MessagingEntityType entityType,
ServiceBusConnectionProcessor connectionProcessor,
MessageSerializer messageSerializer, ReceiverOptions receiverOptions, ServiceBusReceiveLink receiveLink, String identifier) {
this.entityPath = entityPath;
this.entityType = entityType;
this.receiverOptions = receiverOptions;
this.connectionProcessor = connectionProcessor;
this.operationTimeout = connectionProcessor.getRetryOptions().getTryTimeout();
this.messageSerializer = messageSerializer;
this.maxSessionLockRenewDuration = receiverOptions.getMaxLockRenewDuration();
this.identifier = identifier;
final int numberOfSchedulers = receiverOptions.isRollingSessionReceiver()
? receiverOptions.getMaxConcurrentSessions()
: 1;
final List<Scheduler> schedulerList = IntStream.range(0, numberOfSchedulers)
.mapToObj(index -> Schedulers.newBoundedElastic(DEFAULT_BOUNDED_ELASTIC_SIZE,
DEFAULT_BOUNDED_ELASTIC_QUEUESIZE, "receiver-" + index))
.collect(Collectors.toList());
this.schedulers = Collections.unmodifiableList(schedulerList);
this.availableSchedulers.addAll(this.schedulers);
this.processor = EmitterProcessor.create(numberOfSchedulers, false);
this.sessionReceiveSink = processor.sink();
this.receiveLink = receiveLink;
}
ServiceBusSessionManager(String entityPath, MessagingEntityType entityType,
ServiceBusConnectionProcessor connectionProcessor,
MessageSerializer messageSerializer, ReceiverOptions receiverOptions, String identifier) {
this(entityPath, entityType, connectionProcessor,
messageSerializer, receiverOptions, null, identifier);
}
/**
* Gets the link name with the matching {@code sessionId}.
*
* @param sessionId Session id to get link name for.
*
* @return The name of the link, or {@code null} if there is no open link with that {@code sessionId}.
*/
String getLinkName(String sessionId) {
final ServiceBusSessionReceiver receiver = sessionReceivers.get(sessionId);
return receiver != null ? receiver.getLinkName() : null;
}
/**
* Gets the identifier of the instance of {@link ServiceBusSessionManager}.
*
* @return The identifier that can identify the instance of {@link ServiceBusSessionManager}.
*/
public String getIdentifier() {
return this.identifier;
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The session state or an empty Mono if there is no state set for the session.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
Mono<byte[]> getSessionState(String sessionId) {
return validateParameter(sessionId, "sessionId", "getSessionState").then(
getManagementNode().flatMap(channel -> {
final ServiceBusSessionReceiver receiver = sessionReceivers.get(sessionId);
final String associatedLinkName = receiver != null ? receiver.getLinkName() : null;
return channel.getSessionState(sessionId, associatedLinkName);
}));
}
/**
* Gets a stream of messages from different sessions.
*
* @return A Flux of messages merged from different sessions.
*/
Flux<ServiceBusMessageContext> receive() {
if (!isStarted.getAndSet(true)) {
this.sessionReceiveSink.onRequest(this::onSessionRequest);
if (!receiverOptions.isRollingSessionReceiver()) {
receiveFlux = getSession(schedulers.get(0), false);
} else {
receiveFlux = Flux.merge(processor, receiverOptions.getMaxConcurrentSessions());
}
}
return receiveFlux;
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
Mono<OffsetDateTime> renewSessionLock(String sessionId) {
return validateParameter(sessionId, "sessionId", "renewSessionLock").then(
getManagementNode().flatMap(channel -> {
final ServiceBusSessionReceiver receiver = sessionReceivers.get(sessionId);
final String associatedLinkName = receiver != null ? receiver.getLinkName() : null;
return channel.renewSessionLock(sessionId, associatedLinkName).handle((offsetDateTime, sink) -> {
if (receiver != null) {
receiver.setSessionLockedUntil(offsetDateTime);
}
sink.next(offsetDateTime);
});
}));
}
/**
* Tries to update the message disposition on a session aware receive link.
*
* @return {@code true} if the {@code lockToken} was updated on receive link. {@code false} otherwise. This means
* there isn't an open link with that {@code sessionId}.
*/
Mono<Boolean> updateDisposition(String lockToken, String sessionId,
DispositionStatus dispositionStatus, Map<String, Object> propertiesToModify, String deadLetterReason,
String deadLetterDescription, ServiceBusTransactionContext transactionContext) {
final String operation = "updateDisposition";
return Mono.when(
validateParameter(lockToken, "lockToken", operation),
validateParameter(lockToken, "lockToken", operation),
validateParameter(sessionId, "'sessionId'", operation)).then(
Mono.defer(() -> {
final ServiceBusSessionReceiver receiver = sessionReceivers.get(sessionId);
if (receiver == null || !receiver.containsLockToken(lockToken)) {
return Mono.just(false);
}
final DeliveryState deliveryState = MessageUtils.getDeliveryState(dispositionStatus, deadLetterReason,
deadLetterDescription, propertiesToModify, transactionContext);
return receiver.updateDisposition(lockToken, deliveryState).thenReturn(true);
}));
}
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
final List<Mono<Void>> closeables = sessionReceivers.values().stream()
.map(receiver -> receiver.closeAsync())
.collect(Collectors.toList());
Mono.when(closeables).block(operationTimeout);
sessionReceiveSink.complete();
for (Scheduler scheduler : schedulers) {
scheduler.dispose();
}
}
private AmqpErrorContext getErrorContext() {
return new SessionErrorContext(connectionProcessor.getFullyQualifiedNamespace(), entityPath);
}
/**
* Creates an session receive link.
*
* @return A Mono that completes with an session receive link.
*/
private Mono<ServiceBusReceiveLink> createSessionReceiveLink() {
final String sessionId = receiverOptions.getSessionId();
final String linkName = (sessionId != null)
? sessionId
: StringUtil.getRandomString("session-");
return connectionProcessor
.flatMap(connection -> {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, identifier, sessionId);
});
}
/**
* Gets an active unnamed session link.
*
* @return A Mono that completes when an unnamed session becomes available.
* @throws AmqpException if the session manager is already disposed.
*/
/**
* Gets the next available unnamed session with the given receive options and publishes its contents on the given
* {@code scheduler}.
*
* @param scheduler Scheduler to coordinate received methods on.
* @param disposeOnIdle true to dispose receiver when it idles; false otherwise.
* @return A Mono that completes with an unnamed session receiver.
*/
private Flux<ServiceBusMessageContext> getSession(Scheduler scheduler, boolean disposeOnIdle) {
return getActiveLink().flatMap(link -> link.getSessionId()
.map(sessionId -> sessionReceivers.compute(sessionId, (key, existing) -> {
if (existing != null) {
return existing;
}
return new ServiceBusSessionReceiver(link, messageSerializer, connectionProcessor.getRetryOptions(),
receiverOptions.getPrefetchCount(), disposeOnIdle, scheduler, this::renewSessionLock,
maxSessionLockRenewDuration);
})))
.flatMapMany(sessionReceiver -> sessionReceiver.receive().doFinally(signalType -> {
LOGGER.atVerbose()
.addKeyValue(SESSION_ID_KEY, sessionReceiver.getSessionId())
.log("Closing session receiver.");
availableSchedulers.push(scheduler);
sessionReceivers.remove(sessionReceiver.getSessionId());
sessionReceiver.closeAsync().subscribe();
if (receiverOptions.isRollingSessionReceiver()) {
onSessionRequest(1L);
}
}));
}
private Mono<ServiceBusManagementNode> getManagementNode() {
return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType));
}
/**
* Emits a new unnamed active session when it becomes available.
*
* @param request Number of unnamed active sessions to emit.
*/
private void onSessionRequest(long request) {
if (isDisposed.get()) {
LOGGER.info("Session manager is disposed. Not emitting more unnamed sessions.");
return;
}
LOGGER.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, request)
.log("Requested unnamed sessions.");
for (int i = 0; i < request; i++) {
final Scheduler scheduler = availableSchedulers.poll();
if (scheduler == null) {
if (request != Long.MAX_VALUE) {
LOGGER.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, request)
.log("There are no available schedulers to fetch.");
}
return;
}
Flux<ServiceBusMessageContext> session = getSession(scheduler, true);
sessionReceiveSink.next(session);
}
}
private <T> Mono<Void> validateParameter(T parameter, String parameterName, String operation) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, operation)));
} else if (parameter == null) {
return monoError(LOGGER, new NullPointerException(String.format("'%s' cannot be null.", parameterName)));
} else if ((parameter instanceof String) && (((String) parameter).isEmpty())) {
return monoError(LOGGER, new IllegalArgumentException(String.format("'%s' cannot be an empty string.",
parameterName)));
} else {
return Mono.empty();
}
}
} | class ServiceBusSessionManager implements AutoCloseable {
private static final String TRACKING_ID_KEY = "trackingId";
private static final ClientLogger LOGGER = new ClientLogger(ServiceBusSessionManager.class);
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusReceiveLink receiveLink;
private final ServiceBusConnectionProcessor connectionProcessor;
private final Duration operationTimeout;
private final MessageSerializer messageSerializer;
private final String identifier;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicBoolean isStarted = new AtomicBoolean();
private final List<Scheduler> schedulers;
private final Deque<Scheduler> availableSchedulers = new ConcurrentLinkedDeque<>();
private final Duration maxSessionLockRenewDuration;
/**
* SessionId to receiver mapping.
*/
private final ConcurrentHashMap<String, ServiceBusSessionReceiver> sessionReceivers = new ConcurrentHashMap<>();
private final EmitterProcessor<Flux<ServiceBusMessageContext>> processor;
private final FluxSink<Flux<ServiceBusMessageContext>> sessionReceiveSink;
private volatile Flux<ServiceBusMessageContext> receiveFlux;
ServiceBusSessionManager(String entityPath, MessagingEntityType entityType,
ServiceBusConnectionProcessor connectionProcessor,
MessageSerializer messageSerializer, ReceiverOptions receiverOptions, ServiceBusReceiveLink receiveLink, String identifier) {
this.entityPath = entityPath;
this.entityType = entityType;
this.receiverOptions = receiverOptions;
this.connectionProcessor = connectionProcessor;
this.operationTimeout = connectionProcessor.getRetryOptions().getTryTimeout();
this.messageSerializer = messageSerializer;
this.maxSessionLockRenewDuration = receiverOptions.getMaxLockRenewDuration();
this.identifier = identifier;
final int numberOfSchedulers = receiverOptions.isRollingSessionReceiver()
? receiverOptions.getMaxConcurrentSessions()
: 1;
final List<Scheduler> schedulerList = IntStream.range(0, numberOfSchedulers)
.mapToObj(index -> Schedulers.newBoundedElastic(DEFAULT_BOUNDED_ELASTIC_SIZE,
DEFAULT_BOUNDED_ELASTIC_QUEUESIZE, "receiver-" + index))
.collect(Collectors.toList());
this.schedulers = Collections.unmodifiableList(schedulerList);
this.availableSchedulers.addAll(this.schedulers);
this.processor = EmitterProcessor.create(numberOfSchedulers, false);
this.sessionReceiveSink = processor.sink();
this.receiveLink = receiveLink;
}
ServiceBusSessionManager(String entityPath, MessagingEntityType entityType,
ServiceBusConnectionProcessor connectionProcessor,
MessageSerializer messageSerializer, ReceiverOptions receiverOptions, String identifier) {
this(entityPath, entityType, connectionProcessor,
messageSerializer, receiverOptions, null, identifier);
}
/**
* Gets the link name with the matching {@code sessionId}.
*
* @param sessionId Session id to get link name for.
*
* @return The name of the link, or {@code null} if there is no open link with that {@code sessionId}.
*/
String getLinkName(String sessionId) {
final ServiceBusSessionReceiver receiver = sessionReceivers.get(sessionId);
return receiver != null ? receiver.getLinkName() : null;
}
/**
* Gets the identifier of the instance of {@link ServiceBusSessionManager}.
*
* @return The identifier that can identify the instance of {@link ServiceBusSessionManager}.
*/
public String getIdentifier() {
return this.identifier;
}
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The session state or an empty Mono if there is no state set for the session.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
Mono<byte[]> getSessionState(String sessionId) {
return validateParameter(sessionId, "sessionId", "getSessionState").then(
getManagementNode().flatMap(channel -> {
final ServiceBusSessionReceiver receiver = sessionReceivers.get(sessionId);
final String associatedLinkName = receiver != null ? receiver.getLinkName() : null;
return channel.getSessionState(sessionId, associatedLinkName);
}));
}
/**
* Gets a stream of messages from different sessions.
*
* @return A Flux of messages merged from different sessions.
*/
Flux<ServiceBusMessageContext> receive() {
if (!isStarted.getAndSet(true)) {
this.sessionReceiveSink.onRequest(this::onSessionRequest);
if (!receiverOptions.isRollingSessionReceiver()) {
receiveFlux = getSession(schedulers.get(0), false);
} else {
receiveFlux = Flux.merge(processor, receiverOptions.getMaxConcurrentSessions());
}
}
return receiveFlux;
}
/**
* Renews the session lock.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
Mono<OffsetDateTime> renewSessionLock(String sessionId) {
return validateParameter(sessionId, "sessionId", "renewSessionLock").then(
getManagementNode().flatMap(channel -> {
final ServiceBusSessionReceiver receiver = sessionReceivers.get(sessionId);
final String associatedLinkName = receiver != null ? receiver.getLinkName() : null;
return channel.renewSessionLock(sessionId, associatedLinkName).handle((offsetDateTime, sink) -> {
if (receiver != null) {
receiver.setSessionLockedUntil(offsetDateTime);
}
sink.next(offsetDateTime);
});
}));
}
/**
* Tries to update the message disposition on a session aware receive link.
*
* @return {@code true} if the {@code lockToken} was updated on receive link. {@code false} otherwise. This means
* there isn't an open link with that {@code sessionId}.
*/
Mono<Boolean> updateDisposition(String lockToken, String sessionId,
DispositionStatus dispositionStatus, Map<String, Object> propertiesToModify, String deadLetterReason,
String deadLetterDescription, ServiceBusTransactionContext transactionContext) {
final String operation = "updateDisposition";
return Mono.when(
validateParameter(lockToken, "lockToken", operation),
validateParameter(lockToken, "lockToken", operation),
validateParameter(sessionId, "'sessionId'", operation)).then(
Mono.defer(() -> {
final ServiceBusSessionReceiver receiver = sessionReceivers.get(sessionId);
if (receiver == null || !receiver.containsLockToken(lockToken)) {
return Mono.just(false);
}
final DeliveryState deliveryState = MessageUtils.getDeliveryState(dispositionStatus, deadLetterReason,
deadLetterDescription, propertiesToModify, transactionContext);
return receiver.updateDisposition(lockToken, deliveryState).thenReturn(true);
}));
}
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
final List<Mono<Void>> closeables = sessionReceivers.values().stream()
.map(receiver -> receiver.closeAsync())
.collect(Collectors.toList());
Mono.when(closeables).block(operationTimeout);
sessionReceiveSink.complete();
for (Scheduler scheduler : schedulers) {
scheduler.dispose();
}
}
private AmqpErrorContext getErrorContext() {
return new SessionErrorContext(connectionProcessor.getFullyQualifiedNamespace(), entityPath);
}
/**
* Creates an session receive link.
*
* @return A Mono that completes with an session receive link.
*/
private Mono<ServiceBusReceiveLink> createSessionReceiveLink() {
final String sessionId = receiverOptions.getSessionId();
final String linkName = (sessionId != null)
? sessionId
: StringUtil.getRandomString("session-");
return connectionProcessor
.flatMap(connection -> {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, identifier, sessionId);
});
}
/**
* Gets an active unnamed session link.
*
* @return A Mono that completes when an unnamed session becomes available.
* @throws AmqpException if the session manager is already disposed.
*/
/**
* Gets the next available unnamed session with the given receive options and publishes its contents on the given
* {@code scheduler}.
*
* @param scheduler Scheduler to coordinate received methods on.
* @param disposeOnIdle true to dispose receiver when it idles; false otherwise.
* @return A Mono that completes with an unnamed session receiver.
*/
private Flux<ServiceBusMessageContext> getSession(Scheduler scheduler, boolean disposeOnIdle) {
return getActiveLink().flatMap(link -> link.getSessionId()
.map(sessionId -> sessionReceivers.compute(sessionId, (key, existing) -> {
if (existing != null) {
return existing;
}
return new ServiceBusSessionReceiver(link, messageSerializer, connectionProcessor.getRetryOptions(),
receiverOptions.getPrefetchCount(), disposeOnIdle, scheduler, this::renewSessionLock,
maxSessionLockRenewDuration);
})))
.flatMapMany(sessionReceiver -> sessionReceiver.receive().doFinally(signalType -> {
LOGGER.atVerbose()
.addKeyValue(SESSION_ID_KEY, sessionReceiver.getSessionId())
.log("Closing session receiver.");
availableSchedulers.push(scheduler);
sessionReceivers.remove(sessionReceiver.getSessionId());
sessionReceiver.closeAsync().subscribe();
if (receiverOptions.isRollingSessionReceiver()) {
onSessionRequest(1L);
}
}));
}
private Mono<ServiceBusManagementNode> getManagementNode() {
return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType));
}
/**
* Emits a new unnamed active session when it becomes available.
*
* @param request Number of unnamed active sessions to emit.
*/
private void onSessionRequest(long request) {
if (isDisposed.get()) {
LOGGER.info("Session manager is disposed. Not emitting more unnamed sessions.");
return;
}
LOGGER.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, request)
.log("Requested unnamed sessions.");
for (int i = 0; i < request; i++) {
final Scheduler scheduler = availableSchedulers.poll();
if (scheduler == null) {
if (request != Long.MAX_VALUE) {
LOGGER.atVerbose()
.addKeyValue(NUMBER_OF_REQUESTED_MESSAGES_KEY, request)
.log("There are no available schedulers to fetch.");
}
return;
}
Flux<ServiceBusMessageContext> session = getSession(scheduler, true);
sessionReceiveSink.next(session);
}
}
private <T> Mono<Void> validateParameter(T parameter, String parameterName, String operation) {
if (isDisposed.get()) {
return monoError(LOGGER, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, operation)));
} else if (parameter == null) {
return monoError(LOGGER, new NullPointerException(String.format("'%s' cannot be null.", parameterName)));
} else if ((parameter instanceof String) && (((String) parameter).isEmpty())) {
return monoError(LOGGER, new IllegalArgumentException(String.format("'%s' cannot be an empty string.",
parameterName)));
} else {
return Mono.empty();
}
}
} |
and similar below ```suggestion // metrics are exported every 60 seconds by default MINUTES.sleep(5); ``` | private static void sendDoubleHistogram() {
try {
MetricExporter exporter = new AzureMonitorExporterBuilder()
.connectionString(APPINSIGHTS_CONNECTION_STRING)
.buildMetricExporter();
PeriodicMetricReader periodicMetricReader = PeriodicMetricReader
.builder(exporter)
.build();
SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(periodicMetricReader)
.build();
OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
.setMeterProvider(sdkMeterProvider)
.buildAndRegisterGlobal();
Meter meter = openTelemetry.meterBuilder("OTEL.AzureMonitor.Demo")
.build();
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
Thread.sleep(300000);
} catch (Exception ex) {
ex.printStackTrace();
}
} | Thread.sleep(300000); | private static void sendDoubleHistogram() {
try {
MetricExporter exporter = new AzureMonitorExporterBuilder()
.connectionString(APPINSIGHTS_CONNECTION_STRING)
.buildMetricExporter();
PeriodicMetricReader periodicMetricReader = PeriodicMetricReader
.builder(exporter)
.build();
SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(periodicMetricReader)
.build();
OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
.setMeterProvider(sdkMeterProvider)
.buildAndRegisterGlobal();
Meter meter = openTelemetry.meterBuilder("OTEL.AzureMonitor.Demo")
.build();
DoubleHistogram histogram = meter.histogramBuilder("histogram").build();
histogram.record(1.0);
histogram.record(100.0);
histogram.record(30.0);
MINUTES.sleep(5);
} catch (Exception ex) {
ex.printStackTrace();
}
} | class AzureMonitorMetricExporterSample {
private static final String APPINSIGHTS_CONNECTION_STRING = "<YOUR_CONNECTION_STRING>";
public static void main(String[] args) {
sendDoubleHistogram();
}
private static void sendLongCounter() {
try {
MetricExporter exporter = new AzureMonitorExporterBuilder()
.connectionString(APPINSIGHTS_CONNECTION_STRING)
.buildMetricExporter();
PeriodicMetricReader periodicMetricReader = PeriodicMetricReader
.builder(exporter)
.build();
SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(periodicMetricReader)
.build();
OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
.setMeterProvider(sdkMeterProvider)
.buildAndRegisterGlobal();
Meter meter = openTelemetry.meterBuilder("OTEL.AzureMonitor.Demo")
.build();
LongCounter myFruitCounter = meter
.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
Thread.sleep(300000);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void sendGaugeMetric() {
try {
MetricExporter exporter = new AzureMonitorExporterBuilder()
.connectionString(APPINSIGHTS_CONNECTION_STRING)
.buildMetricExporter();
PeriodicMetricReader periodicMetricReader = PeriodicMetricReader
.builder(exporter)
.build();
SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(periodicMetricReader)
.build();
OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
.setMeterProvider(sdkMeterProvider)
.buildAndRegisterGlobal();
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
Thread.sleep(300000);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} | class AzureMonitorMetricExporterSample {
private static final String APPINSIGHTS_CONNECTION_STRING = "<YOUR_CONNECTION_STRING>";
public static void main(String[] args) {
sendDoubleHistogram();
}
private static void sendLongCounter() {
try {
MetricExporter exporter = new AzureMonitorExporterBuilder()
.connectionString(APPINSIGHTS_CONNECTION_STRING)
.buildMetricExporter();
PeriodicMetricReader periodicMetricReader = PeriodicMetricReader
.builder(exporter)
.build();
SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(periodicMetricReader)
.build();
OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
.setMeterProvider(sdkMeterProvider)
.buildAndRegisterGlobal();
Meter meter = openTelemetry.meterBuilder("OTEL.AzureMonitor.Demo")
.build();
LongCounter myFruitCounter = meter
.counterBuilder("MyFruitCounter")
.build();
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(1, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
myFruitCounter.add(2, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "green"));
myFruitCounter.add(5, Attributes.of(AttributeKey.stringKey("name"), "apple", AttributeKey.stringKey("color"), "red"));
myFruitCounter.add(4, Attributes.of(AttributeKey.stringKey("name"), "lemon", AttributeKey.stringKey("color"), "yellow"));
MINUTES.sleep(5);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void sendGaugeMetric() {
try {
MetricExporter exporter = new AzureMonitorExporterBuilder()
.connectionString(APPINSIGHTS_CONNECTION_STRING)
.buildMetricExporter();
PeriodicMetricReader periodicMetricReader = PeriodicMetricReader
.builder(exporter)
.build();
SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(periodicMetricReader)
.build();
OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
.setMeterProvider(sdkMeterProvider)
.buildAndRegisterGlobal();
Meter meter = openTelemetry.getMeter("OTEL.AzureMonitor.Demo");
meter.gaugeBuilder("gauge")
.buildWithCallback(
observableMeasurement -> {
double randomNumber = Math.floor(Math.random() * 100);
observableMeasurement.record(randomNumber, Attributes.of(AttributeKey.stringKey("testKey"), "testValue"));
});
MINUTES.sleep(5);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} |
I think we should use a more generic name for the ledger like what you used to have. | protected void beforeTest() {
try {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} catch (Exception ex) {
System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex);
Assertions.assertTrue(false);
}
} | String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests"); | protected void beforeTest() {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-live-tests-ledger");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught IO exception " + ex);
Assertions.fail();
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught SSL exception " + ex);
Assertions.fail();
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} |
We should not hard-code the name of the endpoint. It's better to read it from the env variables because every time we deploy resources for testing the endpoint will end up being different. | protected void beforeTest() {
try {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} catch (Exception ex) {
System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex);
Assertions.assertTrue(false);
}
} | .ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https: | protected void beforeTest() {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-live-tests-ledger");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught IO exception " + ex);
Assertions.fail();
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught SSL exception " + ex);
Assertions.fail();
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} |
You don't need to reassign the builder variable to itself, that's the beauty of builders, you can modify them on the spot :) ```suggestion confidentialLedgerClientBuilder ``` | protected void beforeTest() {
try {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} catch (Exception ex) {
System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex);
Assertions.assertTrue(false);
}
} | confidentialLedgerClientBuilder = confidentialLedgerClientBuilder | protected void beforeTest() {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-live-tests-ledger");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught IO exception " + ex);
Assertions.fail();
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught SSL exception " + ex);
Assertions.fail();
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} |
You can use the `fail()` method to make the test fail here instead of an assertion. Also, would it not be better to throw the exception and not use a try/catch block? | protected void beforeTest() {
try {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} catch (Exception ex) {
System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex);
Assertions.assertTrue(false);
}
} | Assertions.assertTrue(false); | protected void beforeTest() {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-live-tests-ledger");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught IO exception " + ex);
Assertions.fail();
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught SSL exception " + ex);
Assertions.fail();
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} |
Sounds good. I removed the exception handling. | protected void beforeTest() {
try {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} catch (Exception ex) {
System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex);
Assertions.assertTrue(false);
}
} | Assertions.assertTrue(false); | protected void beforeTest() {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-live-tests-ledger");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught IO exception " + ex);
Assertions.fail();
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught SSL exception " + ex);
Assertions.fail();
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} |
Done! | protected void beforeTest() {
try {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} catch (Exception ex) {
System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex);
Assertions.assertTrue(false);
}
} | confidentialLedgerClientBuilder = confidentialLedgerClientBuilder | protected void beforeTest() {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-live-tests-ledger");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught IO exception " + ex);
Assertions.fail();
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught SSL exception " + ex);
Assertions.fail();
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} |
I understand that a test resource is deployed before the tests start and it takes a random name. In that case the `LEDGER_URI` env variable would be set to that random value. otherwise in case of a **PLAYBACK** testing is done and the `LEDGER_URI` isn't set to any value, it falls back to the hard-coded value so it would be consistent with the values in the records files. | protected void beforeTest() {
try {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} catch (Exception ex) {
System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex);
Assertions.assertTrue(false);
}
} | .ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https: | protected void beforeTest() {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-live-tests-ledger");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught IO exception " + ex);
Assertions.fail();
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught SSL exception " + ex);
Assertions.fail();
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} |
Done! | protected void beforeTest() {
try {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught exception " + ex);
Assertions.assertTrue(false);
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder = confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} catch (Exception ex) {
System.out.println("Error thrown from ConfidentialLedgerClientTestBase:" + ex);
Assertions.assertTrue(false);
}
} | String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "emily-java-sdk-tests"); | protected void beforeTest() {
ConfidentialLedgerCertificateClientBuilder confidentialLedgerCertificateClientBuilder = new ConfidentialLedgerCertificateClientBuilder()
.certificateEndpoint("https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerCertificateClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerCertificateClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerCertificateClientBuilder.credential(new DefaultAzureCredentialBuilder().build());
}
confidentialLedgerCertificateClient = confidentialLedgerCertificateClientBuilder.buildClient();
String ledgerName = Configuration.getGlobalConfiguration().get("LEDGER_NAME", "java-sdk-live-tests-ledger");
Response<BinaryData> ledgerIdentityWithResponse = confidentialLedgerCertificateClient
.getLedgerIdentityWithResponse(ledgerName, null);
BinaryData identityResponse = ledgerIdentityWithResponse.getValue();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(identityResponse.toBytes());
} catch (IOException ex) {
System.out.println("Caught IO exception " + ex);
Assertions.fail();
}
String ledgerTlsCertificate = jsonNode.get("ledgerTlsCertificate").asText();
reactor.netty.http.client.HttpClient reactorClient = null;
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(new ByteArrayInputStream(
ledgerTlsCertificate.getBytes(StandardCharsets.UTF_8)))
.build();
reactorClient = reactor.netty.http.client.HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
} catch (SSLException ex) {
System.out.println("Caught SSL exception " + ex);
Assertions.fail();
}
HttpClient httpClient = new NettyAsyncHttpClientBuilder(reactorClient).wiretap(true).build();
confidentialLedgerClientBuilder = new ConfidentialLedgerClientBuilder()
.ledgerEndpoint(Configuration.getGlobalConfiguration().get("LEDGER_URI", "https:
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC));
if (getTestMode() == TestMode.PLAYBACK) {
confidentialLedgerClientBuilder
.httpClient(interceptorManager.getPlaybackClient())
.credential(request -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)));
} else if (getTestMode() == TestMode.RECORD) {
confidentialLedgerClientBuilder
.addPolicy(interceptorManager.getRecordPolicy())
.httpClient(httpClient)
.credential(new DefaultAzureCredentialBuilder().build());
} else if (getTestMode() == TestMode.LIVE) {
confidentialLedgerClientBuilder
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient);
}
confidentialLedgerClient = confidentialLedgerClientBuilder.buildClient();
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} | class ConfidentialLedgerClientTestBase extends TestBase {
protected ConfidentialLedgerClient confidentialLedgerClient;
protected ConfidentialLedgerClientBuilder confidentialLedgerClientBuilder;
protected ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient;
@Override
} |
`if` -> `else if` | public String toString() {
StringBuilder sb = new StringBuilder();
if (usesCustomFilter) {
sb.append(CUSTOM_FILTER);
}
if (usesPercentageFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER);
}
if (usesTimeWindowFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TIME_WINDOW_FILTER);
}
if (usesTargetingFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TARGETING_FILTER);
}
return sb.toString();
} | if (usesPercentageFilter) { | public String toString() {
StringBuilder sb = new StringBuilder();
if (usesCustomFilter) {
sb.append(CUSTOM_FILTER);
}
if (usesPercentageFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER);
}
if (usesTimeWindowFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TIME_WINDOW_FILTER);
}
if (usesTargetingFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TARGETING_FILTER);
}
return sb.toString();
} | class FeatureFlagTracing {
private static final String CUSTOM_FILTER = "CSTM";
private static final String PERCENTAGE_FILTER = "PRCNT";
private static final String TIME_WINDOW_FILTER = "TIME";
private static final String TARGETING_FILTER = "TRGT";
private static final String FILTER_TYPE_DELIMITER = "+";
private static final List<String> PERCENTAGE_FILTER_NAMES = Arrays.asList("Percentage", "Microsoft.Percentage",
"PercentageFilter", "Microsoft.PercentageFilter");
private static final List<String> TIME_WINDOW_FILTER_NAMES = Arrays.asList("TimeWindow", "Microsoft.TimeWindow",
"TimeWindowFilter", "Microsoft.TimeWindowFilter");
private static final List<String> TARGETING_FILTER_NAMES = Arrays.asList("Targeting", "Microsoft.Targeting",
"TargetingFilter", "Microsoft.TargetingFilter");
private Boolean usesCustomFilter = false;
private Boolean usesPercentageFilter = false;
private Boolean usesTimeWindowFilter = false;
private Boolean usesTargetingFilter = false;
public boolean usesAnyFilter() {
return usesCustomFilter || usesPercentageFilter || usesTimeWindowFilter || usesTargetingFilter;
}
public void resetFeatureFilterTelemetry() {
usesCustomFilter = false;
usesPercentageFilter = false;
usesTimeWindowFilter = false;
usesTargetingFilter = false;
}
public void updateFeatureFilterTelemetry(String filterName) {
if (PERCENTAGE_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesPercentageFilter = true;
} else if (TIME_WINDOW_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTimeWindowFilter = true;
} else if (TARGETING_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTargetingFilter = true;
} else {
usesCustomFilter = true;
}
}
@Override
} | class FeatureFlagTracing {
private static final String CUSTOM_FILTER = "CSTM";
private static final String PERCENTAGE_FILTER = "PRCNT";
private static final String TIME_WINDOW_FILTER = "TIME";
private static final String TARGETING_FILTER = "TRGT";
private static final String FILTER_TYPE_DELIMITER = "+";
private static final List<String> PERCENTAGE_FILTER_NAMES = Arrays.asList("Percentage", "Microsoft.Percentage",
"PercentageFilter", "Microsoft.PercentageFilter");
private static final List<String> TIME_WINDOW_FILTER_NAMES = Arrays.asList("TimeWindow", "Microsoft.TimeWindow",
"TimeWindowFilter", "Microsoft.TimeWindowFilter");
private static final List<String> TARGETING_FILTER_NAMES = Arrays.asList("Targeting", "Microsoft.Targeting",
"TargetingFilter", "Microsoft.TargetingFilter");
private Boolean usesCustomFilter = false;
private Boolean usesPercentageFilter = false;
private Boolean usesTimeWindowFilter = false;
private Boolean usesTargetingFilter = false;
public boolean usesAnyFilter() {
return usesCustomFilter || usesPercentageFilter || usesTimeWindowFilter || usesTargetingFilter;
}
public void resetFeatureFilterTelemetry() {
usesCustomFilter = false;
usesPercentageFilter = false;
usesTimeWindowFilter = false;
usesTargetingFilter = false;
}
public void updateFeatureFilterTelemetry(String filterName) {
if (PERCENTAGE_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesPercentageFilter = true;
} else if (TIME_WINDOW_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTimeWindowFilter = true;
} else if (TARGETING_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTargetingFilter = true;
} else {
usesCustomFilter = true;
}
}
@Override
} |
> sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "") Avoid duplicated code. | public String toString() {
StringBuilder sb = new StringBuilder();
if (usesCustomFilter) {
sb.append(CUSTOM_FILTER);
}
if (usesPercentageFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER);
}
if (usesTimeWindowFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TIME_WINDOW_FILTER);
}
if (usesTargetingFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TARGETING_FILTER);
}
return sb.toString();
} | sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER); | public String toString() {
StringBuilder sb = new StringBuilder();
if (usesCustomFilter) {
sb.append(CUSTOM_FILTER);
}
if (usesPercentageFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER);
}
if (usesTimeWindowFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TIME_WINDOW_FILTER);
}
if (usesTargetingFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TARGETING_FILTER);
}
return sb.toString();
} | class FeatureFlagTracing {
private static final String CUSTOM_FILTER = "CSTM";
private static final String PERCENTAGE_FILTER = "PRCNT";
private static final String TIME_WINDOW_FILTER = "TIME";
private static final String TARGETING_FILTER = "TRGT";
private static final String FILTER_TYPE_DELIMITER = "+";
private static final List<String> PERCENTAGE_FILTER_NAMES = Arrays.asList("Percentage", "Microsoft.Percentage",
"PercentageFilter", "Microsoft.PercentageFilter");
private static final List<String> TIME_WINDOW_FILTER_NAMES = Arrays.asList("TimeWindow", "Microsoft.TimeWindow",
"TimeWindowFilter", "Microsoft.TimeWindowFilter");
private static final List<String> TARGETING_FILTER_NAMES = Arrays.asList("Targeting", "Microsoft.Targeting",
"TargetingFilter", "Microsoft.TargetingFilter");
private Boolean usesCustomFilter = false;
private Boolean usesPercentageFilter = false;
private Boolean usesTimeWindowFilter = false;
private Boolean usesTargetingFilter = false;
public boolean usesAnyFilter() {
return usesCustomFilter || usesPercentageFilter || usesTimeWindowFilter || usesTargetingFilter;
}
public void resetFeatureFilterTelemetry() {
usesCustomFilter = false;
usesPercentageFilter = false;
usesTimeWindowFilter = false;
usesTargetingFilter = false;
}
public void updateFeatureFilterTelemetry(String filterName) {
if (PERCENTAGE_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesPercentageFilter = true;
} else if (TIME_WINDOW_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTimeWindowFilter = true;
} else if (TARGETING_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTargetingFilter = true;
} else {
usesCustomFilter = true;
}
}
@Override
} | class FeatureFlagTracing {
private static final String CUSTOM_FILTER = "CSTM";
private static final String PERCENTAGE_FILTER = "PRCNT";
private static final String TIME_WINDOW_FILTER = "TIME";
private static final String TARGETING_FILTER = "TRGT";
private static final String FILTER_TYPE_DELIMITER = "+";
private static final List<String> PERCENTAGE_FILTER_NAMES = Arrays.asList("Percentage", "Microsoft.Percentage",
"PercentageFilter", "Microsoft.PercentageFilter");
private static final List<String> TIME_WINDOW_FILTER_NAMES = Arrays.asList("TimeWindow", "Microsoft.TimeWindow",
"TimeWindowFilter", "Microsoft.TimeWindowFilter");
private static final List<String> TARGETING_FILTER_NAMES = Arrays.asList("Targeting", "Microsoft.Targeting",
"TargetingFilter", "Microsoft.TargetingFilter");
private Boolean usesCustomFilter = false;
private Boolean usesPercentageFilter = false;
private Boolean usesTimeWindowFilter = false;
private Boolean usesTargetingFilter = false;
public boolean usesAnyFilter() {
return usesCustomFilter || usesPercentageFilter || usesTimeWindowFilter || usesTargetingFilter;
}
public void resetFeatureFilterTelemetry() {
usesCustomFilter = false;
usesPercentageFilter = false;
usesTimeWindowFilter = false;
usesTargetingFilter = false;
}
public void updateFeatureFilterTelemetry(String filterName) {
if (PERCENTAGE_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesPercentageFilter = true;
} else if (TIME_WINDOW_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTimeWindowFilter = true;
} else if (TARGETING_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTargetingFilter = true;
} else {
usesCustomFilter = true;
}
}
@Override
} |
Could you please add unit test when the environment variable is? 1. null 2. empty string 3. "false" 4. "true" 5. "random string“ | public String getValue(boolean watchRequests) {
String track = System.getenv(RequestTracingConstants.REQUEST_TRACING_DISABLED_ENVIRONMENT_VARIABLE.toString());
if (track != null && !Boolean.valueOf(track)) {
return "";
}
RequestType requestTypeValue = watchRequests ? RequestType.WATCH : RequestType.STARTUP;
StringBuilder sb = new StringBuilder();
sb.append(RequestTracingConstants.REQUEST_TYPE_KEY + "=" + requestTypeValue);
if (featureFlagTracing != null && featureFlagTracing.usesAnyFilter()) {
sb.append(",Filter=").append(featureFlagTracing.toString());
}
String hostType = getHostType();
if (!hostType.isEmpty()) {
sb.append("," + RequestTracingConstants.HOST_TYPE_KEY + "=" + hostType);
}
if (isDev) {
sb.append(",Env=" + DEV_ENV_TRACING);
}
if (isKeyVaultConfigured) {
sb.append("," + KEY_VAULT_CONFIGURED_TRACING);
}
if (replicaCount > 0) {
sb.append("," + RequestTracingConstants.REPLICA_COUNT + "=" + replicaCount);
}
return sb.toString();
} | if (track != null && !Boolean.valueOf(track)) { | public String getValue(boolean watchRequests) {
String track = configuration.get(RequestTracingConstants.REQUEST_TRACING_DISABLED_ENVIRONMENT_VARIABLE.toString());
if (track != null && Boolean.valueOf(track)) {
return "";
}
RequestType requestTypeValue = watchRequests ? RequestType.WATCH : RequestType.STARTUP;
StringBuilder sb = new StringBuilder();
sb.append(RequestTracingConstants.REQUEST_TYPE_KEY).append("=" + requestTypeValue);
if (featureFlagTracing != null && featureFlagTracing.usesAnyFilter()) {
sb.append(",Filter=").append(featureFlagTracing.toString());
}
String hostType = getHostType();
if (!hostType.isEmpty()) {
sb.append(",").append(RequestTracingConstants.HOST_TYPE_KEY).append("=").append(hostType);
}
if (isDev) {
sb.append(",Env=").append(DEV_ENV_TRACING);
}
if (isKeyVaultConfigured) {
sb.append(",").append(KEY_VAULT_CONFIGURED_TRACING);
}
if (replicaCount > 0) {
sb.append(",").append(RequestTracingConstants.REPLICA_COUNT).append("=").append(replicaCount);
}
return sb.toString();
} | class TracingInfo {
private boolean isDev = false;
private boolean isKeyVaultConfigured = false;
private int replicaCount = 0;
private FeatureFlagTracing featureFlagTracing;
public TracingInfo(boolean isDev, boolean isKeyVaultConfigured, int replicaCount) {
this.isDev = isDev;
this.isKeyVaultConfigured = isKeyVaultConfigured;
this.replicaCount = replicaCount;
this.featureFlagTracing = new FeatureFlagTracing();
}
/**
* Gets the current host machines type; Azure Function, Azure Web App, Kubernetes, or Empty.
*
* @return String of Host Type
*/
private static String getHostType() {
HostType hostType = HostType.UNIDENTIFIED;
if (System.getenv(RequestTracingConstants.AZURE_FUNCTIONS_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_FUNCTION;
} else if (System.getenv(RequestTracingConstants.AZURE_WEB_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_WEB_APP;
} else if (System.getenv(RequestTracingConstants.KUBERNETES_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.KUBERNETES;
} else if (System.getenv(RequestTracingConstants.CONTAINER_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.CONTAINER_APP;
}
return hostType.toString();
}
/**
* @return the featureFlagTracing
*/
public FeatureFlagTracing getFeatureFlagTracing() {
return featureFlagTracing;
}
} | class TracingInfo {
private boolean isDev = false;
private boolean isKeyVaultConfigured = false;
private int replicaCount;
private final FeatureFlagTracing featureFlagTracing;
private final Configuration configuration;
public TracingInfo(boolean isDev, boolean isKeyVaultConfigured, int replicaCount, Configuration configuration) {
this.isDev = isDev;
this.isKeyVaultConfigured = isKeyVaultConfigured;
this.replicaCount = replicaCount;
this.featureFlagTracing = new FeatureFlagTracing();
this.configuration = configuration;
}
/**
* Gets the current host machines type; Azure Function, Azure Web App, Kubernetes, or Empty.
*
* @return String of Host Type
*/
private static String getHostType() {
HostType hostType = HostType.UNIDENTIFIED;
if (System.getenv(RequestTracingConstants.AZURE_FUNCTIONS_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_FUNCTION;
} else if (System.getenv(RequestTracingConstants.AZURE_WEB_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_WEB_APP;
} else if (System.getenv(RequestTracingConstants.KUBERNETES_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.KUBERNETES;
} else if (System.getenv(RequestTracingConstants.CONTAINER_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.CONTAINER_APP;
}
return hostType.toString();
}
/**
* @return the featureFlagTracing
*/
public FeatureFlagTracing getFeatureFlagTracing() {
return featureFlagTracing;
}
} |
Use `append` instead of `+` | public String getValue(boolean watchRequests) {
String track = System.getenv(RequestTracingConstants.REQUEST_TRACING_DISABLED_ENVIRONMENT_VARIABLE.toString());
if (track != null && !Boolean.valueOf(track)) {
return "";
}
RequestType requestTypeValue = watchRequests ? RequestType.WATCH : RequestType.STARTUP;
StringBuilder sb = new StringBuilder();
sb.append(RequestTracingConstants.REQUEST_TYPE_KEY + "=" + requestTypeValue);
if (featureFlagTracing != null && featureFlagTracing.usesAnyFilter()) {
sb.append(",Filter=").append(featureFlagTracing.toString());
}
String hostType = getHostType();
if (!hostType.isEmpty()) {
sb.append("," + RequestTracingConstants.HOST_TYPE_KEY + "=" + hostType);
}
if (isDev) {
sb.append(",Env=" + DEV_ENV_TRACING);
}
if (isKeyVaultConfigured) {
sb.append("," + KEY_VAULT_CONFIGURED_TRACING);
}
if (replicaCount > 0) {
sb.append("," + RequestTracingConstants.REPLICA_COUNT + "=" + replicaCount);
}
return sb.toString();
} | sb.append(RequestTracingConstants.REQUEST_TYPE_KEY + "=" + requestTypeValue); | public String getValue(boolean watchRequests) {
String track = configuration.get(RequestTracingConstants.REQUEST_TRACING_DISABLED_ENVIRONMENT_VARIABLE.toString());
if (track != null && Boolean.valueOf(track)) {
return "";
}
RequestType requestTypeValue = watchRequests ? RequestType.WATCH : RequestType.STARTUP;
StringBuilder sb = new StringBuilder();
sb.append(RequestTracingConstants.REQUEST_TYPE_KEY).append("=" + requestTypeValue);
if (featureFlagTracing != null && featureFlagTracing.usesAnyFilter()) {
sb.append(",Filter=").append(featureFlagTracing.toString());
}
String hostType = getHostType();
if (!hostType.isEmpty()) {
sb.append(",").append(RequestTracingConstants.HOST_TYPE_KEY).append("=").append(hostType);
}
if (isDev) {
sb.append(",Env=").append(DEV_ENV_TRACING);
}
if (isKeyVaultConfigured) {
sb.append(",").append(KEY_VAULT_CONFIGURED_TRACING);
}
if (replicaCount > 0) {
sb.append(",").append(RequestTracingConstants.REPLICA_COUNT).append("=").append(replicaCount);
}
return sb.toString();
} | class TracingInfo {
private boolean isDev = false;
private boolean isKeyVaultConfigured = false;
private int replicaCount = 0;
private FeatureFlagTracing featureFlagTracing;
public TracingInfo(boolean isDev, boolean isKeyVaultConfigured, int replicaCount) {
this.isDev = isDev;
this.isKeyVaultConfigured = isKeyVaultConfigured;
this.replicaCount = replicaCount;
this.featureFlagTracing = new FeatureFlagTracing();
}
/**
* Gets the current host machines type; Azure Function, Azure Web App, Kubernetes, or Empty.
*
* @return String of Host Type
*/
private static String getHostType() {
HostType hostType = HostType.UNIDENTIFIED;
if (System.getenv(RequestTracingConstants.AZURE_FUNCTIONS_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_FUNCTION;
} else if (System.getenv(RequestTracingConstants.AZURE_WEB_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_WEB_APP;
} else if (System.getenv(RequestTracingConstants.KUBERNETES_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.KUBERNETES;
} else if (System.getenv(RequestTracingConstants.CONTAINER_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.CONTAINER_APP;
}
return hostType.toString();
}
/**
* @return the featureFlagTracing
*/
public FeatureFlagTracing getFeatureFlagTracing() {
return featureFlagTracing;
}
} | class TracingInfo {
private boolean isDev = false;
private boolean isKeyVaultConfigured = false;
private int replicaCount;
private final FeatureFlagTracing featureFlagTracing;
private final Configuration configuration;
public TracingInfo(boolean isDev, boolean isKeyVaultConfigured, int replicaCount, Configuration configuration) {
this.isDev = isDev;
this.isKeyVaultConfigured = isKeyVaultConfigured;
this.replicaCount = replicaCount;
this.featureFlagTracing = new FeatureFlagTracing();
this.configuration = configuration;
}
/**
* Gets the current host machines type; Azure Function, Azure Web App, Kubernetes, or Empty.
*
* @return String of Host Type
*/
private static String getHostType() {
HostType hostType = HostType.UNIDENTIFIED;
if (System.getenv(RequestTracingConstants.AZURE_FUNCTIONS_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_FUNCTION;
} else if (System.getenv(RequestTracingConstants.AZURE_WEB_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_WEB_APP;
} else if (System.getenv(RequestTracingConstants.KUBERNETES_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.KUBERNETES;
} else if (System.getenv(RequestTracingConstants.CONTAINER_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.CONTAINER_APP;
}
return hostType.toString();
}
/**
* @return the featureFlagTracing
*/
public FeatureFlagTracing getFeatureFlagTracing() {
return featureFlagTracing;
}
} |
Same to all other places. | public String getValue(boolean watchRequests) {
String track = System.getenv(RequestTracingConstants.REQUEST_TRACING_DISABLED_ENVIRONMENT_VARIABLE.toString());
if (track != null && !Boolean.valueOf(track)) {
return "";
}
RequestType requestTypeValue = watchRequests ? RequestType.WATCH : RequestType.STARTUP;
StringBuilder sb = new StringBuilder();
sb.append(RequestTracingConstants.REQUEST_TYPE_KEY + "=" + requestTypeValue);
if (featureFlagTracing != null && featureFlagTracing.usesAnyFilter()) {
sb.append(",Filter=").append(featureFlagTracing.toString());
}
String hostType = getHostType();
if (!hostType.isEmpty()) {
sb.append("," + RequestTracingConstants.HOST_TYPE_KEY + "=" + hostType);
}
if (isDev) {
sb.append(",Env=" + DEV_ENV_TRACING);
}
if (isKeyVaultConfigured) {
sb.append("," + KEY_VAULT_CONFIGURED_TRACING);
}
if (replicaCount > 0) {
sb.append("," + RequestTracingConstants.REPLICA_COUNT + "=" + replicaCount);
}
return sb.toString();
} | sb.append(RequestTracingConstants.REQUEST_TYPE_KEY + "=" + requestTypeValue); | public String getValue(boolean watchRequests) {
String track = configuration.get(RequestTracingConstants.REQUEST_TRACING_DISABLED_ENVIRONMENT_VARIABLE.toString());
if (track != null && Boolean.valueOf(track)) {
return "";
}
RequestType requestTypeValue = watchRequests ? RequestType.WATCH : RequestType.STARTUP;
StringBuilder sb = new StringBuilder();
sb.append(RequestTracingConstants.REQUEST_TYPE_KEY).append("=" + requestTypeValue);
if (featureFlagTracing != null && featureFlagTracing.usesAnyFilter()) {
sb.append(",Filter=").append(featureFlagTracing.toString());
}
String hostType = getHostType();
if (!hostType.isEmpty()) {
sb.append(",").append(RequestTracingConstants.HOST_TYPE_KEY).append("=").append(hostType);
}
if (isDev) {
sb.append(",Env=").append(DEV_ENV_TRACING);
}
if (isKeyVaultConfigured) {
sb.append(",").append(KEY_VAULT_CONFIGURED_TRACING);
}
if (replicaCount > 0) {
sb.append(",").append(RequestTracingConstants.REPLICA_COUNT).append("=").append(replicaCount);
}
return sb.toString();
} | class TracingInfo {
private boolean isDev = false;
private boolean isKeyVaultConfigured = false;
private int replicaCount = 0;
private FeatureFlagTracing featureFlagTracing;
public TracingInfo(boolean isDev, boolean isKeyVaultConfigured, int replicaCount) {
this.isDev = isDev;
this.isKeyVaultConfigured = isKeyVaultConfigured;
this.replicaCount = replicaCount;
this.featureFlagTracing = new FeatureFlagTracing();
}
/**
* Gets the current host machines type; Azure Function, Azure Web App, Kubernetes, or Empty.
*
* @return String of Host Type
*/
private static String getHostType() {
HostType hostType = HostType.UNIDENTIFIED;
if (System.getenv(RequestTracingConstants.AZURE_FUNCTIONS_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_FUNCTION;
} else if (System.getenv(RequestTracingConstants.AZURE_WEB_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_WEB_APP;
} else if (System.getenv(RequestTracingConstants.KUBERNETES_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.KUBERNETES;
} else if (System.getenv(RequestTracingConstants.CONTAINER_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.CONTAINER_APP;
}
return hostType.toString();
}
/**
* @return the featureFlagTracing
*/
public FeatureFlagTracing getFeatureFlagTracing() {
return featureFlagTracing;
}
} | class TracingInfo {
private boolean isDev = false;
private boolean isKeyVaultConfigured = false;
private int replicaCount;
private final FeatureFlagTracing featureFlagTracing;
private final Configuration configuration;
public TracingInfo(boolean isDev, boolean isKeyVaultConfigured, int replicaCount, Configuration configuration) {
this.isDev = isDev;
this.isKeyVaultConfigured = isKeyVaultConfigured;
this.replicaCount = replicaCount;
this.featureFlagTracing = new FeatureFlagTracing();
this.configuration = configuration;
}
/**
* Gets the current host machines type; Azure Function, Azure Web App, Kubernetes, or Empty.
*
* @return String of Host Type
*/
private static String getHostType() {
HostType hostType = HostType.UNIDENTIFIED;
if (System.getenv(RequestTracingConstants.AZURE_FUNCTIONS_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_FUNCTION;
} else if (System.getenv(RequestTracingConstants.AZURE_WEB_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.AZURE_WEB_APP;
} else if (System.getenv(RequestTracingConstants.KUBERNETES_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.KUBERNETES;
} else if (System.getenv(RequestTracingConstants.CONTAINER_APP_ENVIRONMENT_VARIABLE.toString()) != null) {
hostType = HostType.CONTAINER_APP;
}
return hostType.toString();
}
/**
* @return the featureFlagTracing
*/
public FeatureFlagTracing getFeatureFlagTracing() {
return featureFlagTracing;
}
} |
Multiple of these can be true. | public String toString() {
StringBuilder sb = new StringBuilder();
if (usesCustomFilter) {
sb.append(CUSTOM_FILTER);
}
if (usesPercentageFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER);
}
if (usesTimeWindowFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TIME_WINDOW_FILTER);
}
if (usesTargetingFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TARGETING_FILTER);
}
return sb.toString();
} | if (usesPercentageFilter) { | public String toString() {
StringBuilder sb = new StringBuilder();
if (usesCustomFilter) {
sb.append(CUSTOM_FILTER);
}
if (usesPercentageFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER);
}
if (usesTimeWindowFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TIME_WINDOW_FILTER);
}
if (usesTargetingFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TARGETING_FILTER);
}
return sb.toString();
} | class FeatureFlagTracing {
private static final String CUSTOM_FILTER = "CSTM";
private static final String PERCENTAGE_FILTER = "PRCNT";
private static final String TIME_WINDOW_FILTER = "TIME";
private static final String TARGETING_FILTER = "TRGT";
private static final String FILTER_TYPE_DELIMITER = "+";
private static final List<String> PERCENTAGE_FILTER_NAMES = Arrays.asList("Percentage", "Microsoft.Percentage",
"PercentageFilter", "Microsoft.PercentageFilter");
private static final List<String> TIME_WINDOW_FILTER_NAMES = Arrays.asList("TimeWindow", "Microsoft.TimeWindow",
"TimeWindowFilter", "Microsoft.TimeWindowFilter");
private static final List<String> TARGETING_FILTER_NAMES = Arrays.asList("Targeting", "Microsoft.Targeting",
"TargetingFilter", "Microsoft.TargetingFilter");
private Boolean usesCustomFilter = false;
private Boolean usesPercentageFilter = false;
private Boolean usesTimeWindowFilter = false;
private Boolean usesTargetingFilter = false;
public boolean usesAnyFilter() {
return usesCustomFilter || usesPercentageFilter || usesTimeWindowFilter || usesTargetingFilter;
}
public void resetFeatureFilterTelemetry() {
usesCustomFilter = false;
usesPercentageFilter = false;
usesTimeWindowFilter = false;
usesTargetingFilter = false;
}
public void updateFeatureFilterTelemetry(String filterName) {
if (PERCENTAGE_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesPercentageFilter = true;
} else if (TIME_WINDOW_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTimeWindowFilter = true;
} else if (TARGETING_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTargetingFilter = true;
} else {
usesCustomFilter = true;
}
}
@Override
} | class FeatureFlagTracing {
private static final String CUSTOM_FILTER = "CSTM";
private static final String PERCENTAGE_FILTER = "PRCNT";
private static final String TIME_WINDOW_FILTER = "TIME";
private static final String TARGETING_FILTER = "TRGT";
private static final String FILTER_TYPE_DELIMITER = "+";
private static final List<String> PERCENTAGE_FILTER_NAMES = Arrays.asList("Percentage", "Microsoft.Percentage",
"PercentageFilter", "Microsoft.PercentageFilter");
private static final List<String> TIME_WINDOW_FILTER_NAMES = Arrays.asList("TimeWindow", "Microsoft.TimeWindow",
"TimeWindowFilter", "Microsoft.TimeWindowFilter");
private static final List<String> TARGETING_FILTER_NAMES = Arrays.asList("Targeting", "Microsoft.Targeting",
"TargetingFilter", "Microsoft.TargetingFilter");
private Boolean usesCustomFilter = false;
private Boolean usesPercentageFilter = false;
private Boolean usesTimeWindowFilter = false;
private Boolean usesTargetingFilter = false;
public boolean usesAnyFilter() {
return usesCustomFilter || usesPercentageFilter || usesTimeWindowFilter || usesTargetingFilter;
}
public void resetFeatureFilterTelemetry() {
usesCustomFilter = false;
usesPercentageFilter = false;
usesTimeWindowFilter = false;
usesTargetingFilter = false;
}
public void updateFeatureFilterTelemetry(String filterName) {
if (PERCENTAGE_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesPercentageFilter = true;
} else if (TIME_WINDOW_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTimeWindowFilter = true;
} else if (TARGETING_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTargetingFilter = true;
} else {
usesCustomFilter = true;
}
}
@Override
} |
Seems a bit much, for just those 3 lines. I don't see any more of these being added. | public String toString() {
StringBuilder sb = new StringBuilder();
if (usesCustomFilter) {
sb.append(CUSTOM_FILTER);
}
if (usesPercentageFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER);
}
if (usesTimeWindowFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TIME_WINDOW_FILTER);
}
if (usesTargetingFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TARGETING_FILTER);
}
return sb.toString();
} | sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER); | public String toString() {
StringBuilder sb = new StringBuilder();
if (usesCustomFilter) {
sb.append(CUSTOM_FILTER);
}
if (usesPercentageFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(PERCENTAGE_FILTER);
}
if (usesTimeWindowFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TIME_WINDOW_FILTER);
}
if (usesTargetingFilter) {
sb.append(sb.length() > 0 ? FILTER_TYPE_DELIMITER : "").append(TARGETING_FILTER);
}
return sb.toString();
} | class FeatureFlagTracing {
private static final String CUSTOM_FILTER = "CSTM";
private static final String PERCENTAGE_FILTER = "PRCNT";
private static final String TIME_WINDOW_FILTER = "TIME";
private static final String TARGETING_FILTER = "TRGT";
private static final String FILTER_TYPE_DELIMITER = "+";
private static final List<String> PERCENTAGE_FILTER_NAMES = Arrays.asList("Percentage", "Microsoft.Percentage",
"PercentageFilter", "Microsoft.PercentageFilter");
private static final List<String> TIME_WINDOW_FILTER_NAMES = Arrays.asList("TimeWindow", "Microsoft.TimeWindow",
"TimeWindowFilter", "Microsoft.TimeWindowFilter");
private static final List<String> TARGETING_FILTER_NAMES = Arrays.asList("Targeting", "Microsoft.Targeting",
"TargetingFilter", "Microsoft.TargetingFilter");
private Boolean usesCustomFilter = false;
private Boolean usesPercentageFilter = false;
private Boolean usesTimeWindowFilter = false;
private Boolean usesTargetingFilter = false;
public boolean usesAnyFilter() {
return usesCustomFilter || usesPercentageFilter || usesTimeWindowFilter || usesTargetingFilter;
}
public void resetFeatureFilterTelemetry() {
usesCustomFilter = false;
usesPercentageFilter = false;
usesTimeWindowFilter = false;
usesTargetingFilter = false;
}
public void updateFeatureFilterTelemetry(String filterName) {
if (PERCENTAGE_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesPercentageFilter = true;
} else if (TIME_WINDOW_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTimeWindowFilter = true;
} else if (TARGETING_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTargetingFilter = true;
} else {
usesCustomFilter = true;
}
}
@Override
} | class FeatureFlagTracing {
private static final String CUSTOM_FILTER = "CSTM";
private static final String PERCENTAGE_FILTER = "PRCNT";
private static final String TIME_WINDOW_FILTER = "TIME";
private static final String TARGETING_FILTER = "TRGT";
private static final String FILTER_TYPE_DELIMITER = "+";
private static final List<String> PERCENTAGE_FILTER_NAMES = Arrays.asList("Percentage", "Microsoft.Percentage",
"PercentageFilter", "Microsoft.PercentageFilter");
private static final List<String> TIME_WINDOW_FILTER_NAMES = Arrays.asList("TimeWindow", "Microsoft.TimeWindow",
"TimeWindowFilter", "Microsoft.TimeWindowFilter");
private static final List<String> TARGETING_FILTER_NAMES = Arrays.asList("Targeting", "Microsoft.Targeting",
"TargetingFilter", "Microsoft.TargetingFilter");
private Boolean usesCustomFilter = false;
private Boolean usesPercentageFilter = false;
private Boolean usesTimeWindowFilter = false;
private Boolean usesTargetingFilter = false;
public boolean usesAnyFilter() {
return usesCustomFilter || usesPercentageFilter || usesTimeWindowFilter || usesTargetingFilter;
}
public void resetFeatureFilterTelemetry() {
usesCustomFilter = false;
usesPercentageFilter = false;
usesTimeWindowFilter = false;
usesTargetingFilter = false;
}
public void updateFeatureFilterTelemetry(String filterName) {
if (PERCENTAGE_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesPercentageFilter = true;
} else if (TIME_WINDOW_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTimeWindowFilter = true;
} else if (TARGETING_FILTER_NAMES.stream().anyMatch(name -> name.equalsIgnoreCase(filterName))) {
usesTargetingFilter = true;
} else {
usesCustomFilter = true;
}
}
@Override
} |
Is this needed? The DataFeedIngestionStatus should be correctly serialized and we don't need accessors to make it public. What's the difference between the DataFeedIngestionStatus in implementation package and the one in public package? | private List<DataFeedIngestionStatus> toDataFeedIngestionStatus(List<com.azure.ai.metricsadvisor.implementation.models.DataFeedIngestionStatus> ingestionStatusList) {
return ingestionStatusList
.stream()
.map(ingestionStatus -> {
DataFeedIngestionStatus dataFeedIngestionStatus = new DataFeedIngestionStatus();
DataFeedIngestionStatusHelper.setMessage(dataFeedIngestionStatus, ingestionStatus.getMessage());
DataFeedIngestionStatusHelper.setIngestionStatusType(dataFeedIngestionStatus, IngestionStatusType.fromString(toStringOrNull(ingestionStatus.getStatus())));
DataFeedIngestionStatusHelper.setTimestamp(dataFeedIngestionStatus, ingestionStatus.getTimestamp());
return dataFeedIngestionStatus;
})
.collect(Collectors.toList());
} | return dataFeedIngestionStatus; | private List<DataFeedIngestionStatus> toDataFeedIngestionStatus(List<com.azure.ai.metricsadvisor.implementation.models.DataFeedIngestionStatus> ingestionStatusList) {
return ingestionStatusList
.stream()
.map(ingestionStatus -> {
DataFeedIngestionStatus dataFeedIngestionStatus = new DataFeedIngestionStatus();
DataFeedIngestionStatusHelper.setMessage(dataFeedIngestionStatus, ingestionStatus.getMessage());
DataFeedIngestionStatusHelper.setIngestionStatusType(dataFeedIngestionStatus, IngestionStatusType.fromString(toStringOrNull(ingestionStatus.getStatus())));
DataFeedIngestionStatusHelper.setTimestamp(dataFeedIngestionStatus, ingestionStatus.getTimestamp());
return dataFeedIngestionStatus;
})
.collect(Collectors.toList());
} | class MetricsAdvisorAdministrationAsyncClient {
private final ClientLogger logger = new ClientLogger(MetricsAdvisorAdministrationAsyncClient.class);
private final MetricsAdvisorImpl service;
/**
* Create a {@link MetricsAdvisorAdministrationAsyncClient} that sends requests to the Metrics Advisor
* service's endpoint. Each service call goes through the
* {@link MetricsAdvisorAdministrationClientBuilder
*
* @param service The proxy service used to perform REST calls.
* @param serviceVersion The versions of Azure Metrics Advisor supported by this client library.
*/
MetricsAdvisorAdministrationAsyncClient(MetricsAdvisorImpl service,
MetricsAdvisorServiceVersion serviceVersion) {
this.service = service;
}
/**
* Create a new data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeed
* <pre>
* DataFeed dataFeed = new DataFeed&
* .setName&
* .setSource&
* .setGranularity&
* .setSchema&
* Arrays.asList&
* new DataFeedMetric&
* new DataFeedMetric&
* &
* Arrays.asList&
* new DataFeedDimension&
* new DataFeedDimension&
* &
* &
* .setIngestionSettings&
* .setOptions&
* .setDescription&
* .setRollupSettings&
* .setRollupType&
*
* metricsAdvisorAdminAsyncClient.createDataFeed&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeed
*
* @param dataFeed The data feed to be created.
* @return A {@link Mono} containing the created data feed.
* @throws NullPointerException If {@code dataFeed}, {@code dataFeedName}, {@code dataFeedSource}, {@code metrics},
* {@code granularityType} or {@code ingestionStartTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> createDataFeed(DataFeed dataFeed) {
return createDataFeedWithResponse(dataFeed).flatMap(FluxUtil::toMono);
}
/**
* Create a new data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeedWithResponse
* <pre>
* DataFeed dataFeed = new DataFeed&
* .setName&
* .setSource&
* .setGranularity&
* .setSchema&
* Arrays.asList&
* new DataFeedMetric&
* new DataFeedMetric&
* &
* &
* .setIngestionSettings&
* .setOptions&
* .setDescription&
* .setRollupSettings&
* .setRollupType&
*
* metricsAdvisorAdminAsyncClient.createDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* DataFeed createdDataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeedWithResponse
* @param dataFeed The data feed to be created.
* @return A {@link Response} of a {@link Mono} containing the created {@link DataFeed data feed}.
* @throws NullPointerException If {@code dataFeed}, {@code dataFeedName}, {@code dataFeedSource}, {@code metrics},
* {@code granularityType} or {@code ingestionStartTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> createDataFeedWithResponse(DataFeed dataFeed) {
try {
return withContext(context -> createDataFeedWithResponse(dataFeed, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> createDataFeedWithResponse(DataFeed dataFeed, Context context) {
Objects.requireNonNull(dataFeed, "'dataFeed' is required and cannot be null.");
Objects.requireNonNull(dataFeed.getSource(), "'dataFeedSource' is required and cannot be null.");
Objects.requireNonNull(dataFeed.getName(), "'dataFeedName' cannot be null or empty.");
final DataFeedSchema dataFeedSchema = dataFeed.getSchema();
final DataFeedGranularity dataFeedGranularity = dataFeed.getGranularity();
final DataFeedIngestionSettings dataFeedIngestionSettings = dataFeed.getIngestionSettings();
if (dataFeedSchema == null) {
throw logger.logExceptionAsError(
new NullPointerException("'dataFeedSchema.metrics' cannot be null or empty."));
} else {
Objects.requireNonNull(dataFeedSchema.getMetrics(),
"'dataFeedSchema.metrics' cannot be null or empty.");
}
if (dataFeedGranularity == null) {
throw logger.logExceptionAsError(
new NullPointerException("'dataFeedGranularity.granularityType' is required and cannot be null."));
} else {
Objects.requireNonNull(dataFeedGranularity.getGranularityType(),
"'dataFeedGranularity.granularityType' is required.");
if (CUSTOM.equals(dataFeedGranularity.getGranularityType())) {
Objects.requireNonNull(dataFeedGranularity.getCustomGranularityValue(),
"'dataFeedGranularity.customGranularityValue' is required when granularity type is CUSTOM");
}
}
if (dataFeedIngestionSettings == null) {
throw logger.logExceptionAsError(
new NullPointerException(
"'dataFeedIngestionSettings.ingestionStartTime' is required and cannot be null."));
} else {
Objects.requireNonNull(dataFeedIngestionSettings.getIngestionStartTime(),
"'dataFeedIngestionSettings.ingestionStartTime' is required and cannot be null.");
}
final DataFeedOptions finalDataFeedOptions = dataFeed.getOptions() == null
? new DataFeedOptions() : dataFeed.getOptions();
final DataFeedRollupSettings dataFeedRollupSettings = finalDataFeedOptions.getRollupSettings() == null
? new DataFeedRollupSettings() : finalDataFeedOptions.getRollupSettings();
final DataFeedMissingDataPointFillSettings dataFeedMissingDataPointFillSettings =
finalDataFeedOptions.getMissingDataPointFillSettings() == null
? new DataFeedMissingDataPointFillSettings() : finalDataFeedOptions.getMissingDataPointFillSettings();
return service.createDataFeedWithResponseAsync(DataFeedTransforms.toDataFeedDetailSource(dataFeed.getSource())
.setDataFeedName(dataFeed.getName())
.setDataFeedDescription(finalDataFeedOptions.getDescription())
.setGranularityName(Granularity.fromString(dataFeedGranularity.getGranularityType() == null
? null : dataFeedGranularity.getGranularityType().toString()))
.setGranularityAmount(dataFeedGranularity.getCustomGranularityValue())
.setDimension(DataFeedTransforms.toInnerDimensionsListForCreate(dataFeedSchema.getDimensions()))
.setMetrics(DataFeedTransforms.toInnerMetricsListForCreate(dataFeedSchema.getMetrics()))
.setTimestampColumn(dataFeedSchema.getTimestampColumn())
.setDataStartFrom(dataFeedIngestionSettings.getIngestionStartTime())
.setStartOffsetInSeconds(dataFeedIngestionSettings.getIngestionStartOffset() == null
? null : dataFeedIngestionSettings.getIngestionStartOffset().getSeconds())
.setMaxConcurrency(dataFeedIngestionSettings.getDataSourceRequestConcurrency())
.setStopRetryAfterInSeconds(dataFeedIngestionSettings.getStopRetryAfter() == null
? null : dataFeedIngestionSettings.getStopRetryAfter().getSeconds())
.setMinRetryIntervalInSeconds(dataFeedIngestionSettings.getIngestionRetryDelay() == null
? null : dataFeedIngestionSettings.getIngestionRetryDelay().getSeconds())
.setRollUpColumns(dataFeedRollupSettings.getAutoRollupGroupByColumnNames())
.setRollUpMethod(RollUpMethod.fromString(dataFeedRollupSettings
.getDataFeedAutoRollUpMethod() == null
? null : dataFeedRollupSettings.getDataFeedAutoRollUpMethod().toString()))
.setNeedRollup(NeedRollupEnum.fromString(dataFeedRollupSettings.getRollupType() == null
? null : dataFeedRollupSettings.getRollupType().toString()))
.setAllUpIdentification(dataFeedRollupSettings.getRollupIdentificationValue())
.setFillMissingPointType(FillMissingPointType.fromString(
dataFeedMissingDataPointFillSettings.getFillType() == null
? null : dataFeedMissingDataPointFillSettings.getFillType().toString()))
.setFillMissingPointValue(dataFeedMissingDataPointFillSettings.getCustomFillValue())
.setViewMode(ViewMode.fromString(finalDataFeedOptions.getAccessMode() == null
? null : finalDataFeedOptions.getAccessMode().toString()))
.setViewers(finalDataFeedOptions.getViewers())
.setAdmins(finalDataFeedOptions.getAdmins())
.setActionLinkTemplate(finalDataFeedOptions.getActionLinkTemplate()), context)
.flatMap(createDataFeedResponse -> {
final String dataFeedId =
parseOperationId(createDataFeedResponse.getDeserializedHeaders().getLocation());
return getDataFeedWithResponse(dataFeedId);
});
}
/**
* Get a data feed by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeed
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeed
*
* @param dataFeedId The data feed unique id.
*
* @return The data feed for the provided id.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> getDataFeed(String dataFeedId) {
return getDataFeedWithResponse(dataFeedId).flatMap(FluxUtil::toMono);
}
/**
* Get a data feed by its id with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedWithResponse
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* DataFeed dataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedWithResponse
*
* @param dataFeedId The data feed unique id.
*
* @return The data feed for the provided id.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> getDataFeedWithResponse(String dataFeedId) {
try {
return withContext(context -> getDataFeedWithResponse(dataFeedId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> getDataFeedWithResponse(String dataFeedId, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' cannot be null.");
return service.getDataFeedByIdWithResponseAsync(UUID.fromString(dataFeedId), context)
.map(response -> new SimpleResponse<>(response, DataFeedTransforms.fromInner(response.getValue())));
}
/**
* Update an existing data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeed
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .flatMap&
* return metricsAdvisorAdminAsyncClient.updateDataFeed&
* existingDataFeed
* .setOptions&
* .setDescription&
* &
* &
* .subscribe&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeed
*
* @param dataFeed the data feed that needs to be updated.
*
* @return the updated data feed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> updateDataFeed(DataFeed dataFeed) {
return updateDataFeedWithResponse(dataFeed).flatMap(FluxUtil::toMono);
}
/**
* Update an existing data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeedWithResponse
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .flatMap&
* return metricsAdvisorAdminAsyncClient.updateDataFeedWithResponse&
* existingDataFeed
* .setOptions&
* .setDescription&
* &
* &
* .subscribe&
* System.out.printf&
* DataFeed updatedDataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeedWithResponse
*
* @param dataFeed the data feed that needs to be updated.
*
* @return the {@link Response} of a {@link Mono} containing the updated {@link DataFeed data feed}.
**/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> updateDataFeedWithResponse(DataFeed dataFeed) {
try {
return withContext(context -> updateDataFeedWithResponse(dataFeed, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> updateDataFeedWithResponse(DataFeed dataFeed, Context context) {
final DataFeedIngestionSettings dataFeedIngestionSettings = dataFeed.getIngestionSettings();
final DataFeedOptions dataFeedOptions = dataFeed.getOptions() == null
? new DataFeedOptions() : dataFeed.getOptions();
final DataFeedRollupSettings dataFeedRollupSettings = dataFeedOptions.getRollupSettings() == null
? new DataFeedRollupSettings() : dataFeedOptions.getRollupSettings();
final DataFeedMissingDataPointFillSettings dataFeedMissingDataPointFillSettings =
dataFeedOptions.getMissingDataPointFillSettings() == null
? new DataFeedMissingDataPointFillSettings() : dataFeedOptions.getMissingDataPointFillSettings();
return service.updateDataFeedWithResponseAsync(UUID.fromString(dataFeed.getId()),
DataFeedTransforms.toInnerForUpdate(dataFeed.getSource())
.setDataFeedName(dataFeed.getName())
.setDataFeedDescription(dataFeedOptions.getDescription())
.setTimestampColumn(dataFeed.getSchema() == null
? null : dataFeed.getSchema().getTimestampColumn())
.setDataStartFrom(dataFeed.getIngestionSettings().getIngestionStartTime())
.setStartOffsetInSeconds(dataFeedIngestionSettings.getIngestionStartOffset() == null
? null : dataFeedIngestionSettings.getIngestionStartOffset().getSeconds())
.setMaxConcurrency(dataFeedIngestionSettings.getDataSourceRequestConcurrency())
.setStopRetryAfterInSeconds(dataFeedIngestionSettings.getStopRetryAfter() == null
? null : dataFeedIngestionSettings.getStopRetryAfter().getSeconds())
.setMinRetryIntervalInSeconds(dataFeedIngestionSettings.getIngestionRetryDelay() == null
? null : dataFeedIngestionSettings.getIngestionRetryDelay().getSeconds())
.setNeedRollup(
dataFeedRollupSettings.getRollupType() != null
? NeedRollupEnum.fromString(dataFeedRollupSettings.getRollupType().toString())
: null)
.setRollUpColumns(dataFeedRollupSettings.getAutoRollupGroupByColumnNames())
.setRollUpMethod(
dataFeedRollupSettings.getDataFeedAutoRollUpMethod() != null
? RollUpMethod.fromString(
dataFeedRollupSettings.getDataFeedAutoRollUpMethod().toString())
: null)
.setAllUpIdentification(dataFeedRollupSettings.getRollupIdentificationValue())
.setFillMissingPointType(
dataFeedMissingDataPointFillSettings.getFillType() != null
? FillMissingPointType.fromString(
dataFeedMissingDataPointFillSettings.getFillType().toString())
: null)
.setFillMissingPointValue(
dataFeedMissingDataPointFillSettings.getFillType() == DataFeedMissingDataPointFillType.CUSTOM_VALUE
? dataFeedMissingDataPointFillSettings.getCustomFillValue()
: null)
.setViewMode(
dataFeedOptions.getAccessMode() != null
? ViewMode.fromString(dataFeedOptions.getAccessMode().toString())
: null)
.setViewers(dataFeedOptions.getViewers())
.setAdmins(dataFeedOptions.getAdmins())
.setStatus(
dataFeed.getStatus() != null
? EntityStatus.fromString(dataFeed.getStatus().toString())
: null)
.setActionLinkTemplate(dataFeedOptions.getActionLinkTemplate()), context)
.flatMap(updatedDataFeedResponse -> getDataFeedWithResponse(dataFeed.getId()));
}
/**
* Delete a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeed
* <pre>
* final String dataFeedId = "t00853f1-9080-447f-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.deleteDataFeed&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeed
*
* @param dataFeedId The data feed unique id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDataFeed(String dataFeedId) {
return deleteDataFeedWithResponse(dataFeedId).flatMap(FluxUtil::toMono);
}
/**
* Delete a data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeedWithResponse
* <pre>
* final String dataFeedId = "eh0854f1-8927-447f-bacf-8dccf2e86fwe";
* metricsAdvisorAdminAsyncClient.deleteDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeedWithResponse
*
* @param dataFeedId The data feed unique id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDataFeedWithResponse(String dataFeedId) {
try {
return withContext(context -> deleteDataFeedWithResponse(dataFeedId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteDataFeedWithResponse(String dataFeedId, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' cannot be null.");
return service.deleteDataFeedWithResponseAsync(UUID.fromString(dataFeedId), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* List information of all data feeds on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds -->
* <pre>
* metricsAdvisorAdminAsyncClient.listDataFeeds&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds -->
*
* @return A {@link PagedFlux} containing information of all the {@link DataFeed data feeds} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeed> listDataFeeds() {
return listDataFeeds(new ListDataFeedOptions());
}
/**
* List information of all data feeds on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds
* <pre>
* metricsAdvisorAdminAsyncClient.listDataFeeds&
* new ListDataFeedOptions&
* .setListDataFeedFilter&
* new ListDataFeedFilter&
* .setDataFeedStatus&
* .setDataFeedGranularityType&
* .setMaxPageSize&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds
*
* @param listDataFeedOptions The configurable {@link ListDataFeedOptions options} to pass for filtering the output result.
*
* @return A {@link PagedFlux} containing information of all the {@link DataFeed data feeds} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeed> listDataFeeds(ListDataFeedOptions listDataFeedOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listDataFeedsSinglePageAsync(listDataFeedOptions, context)),
continuationToken ->
withContext(context -> listDataFeedsNextPageAsync(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DataFeed> listDataFeeds(ListDataFeedOptions options, Context context) {
return new PagedFlux<>(() ->
listDataFeedsSinglePageAsync(options, context),
continuationToken ->
listDataFeedsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<DataFeed>> listDataFeedsSinglePageAsync(ListDataFeedOptions options, Context context) {
options = options != null ? options : new ListDataFeedOptions();
final ListDataFeedFilter dataFeedFilter =
options.getListDataFeedFilter() != null ? options.getListDataFeedFilter() : new ListDataFeedFilter();
return service.listDataFeedsSinglePageAsync(dataFeedFilter.getName(),
dataFeedFilter.getSourceType() != null
? DataSourceType.fromString(dataFeedFilter.getSourceType().toString()) : null,
dataFeedFilter.getGranularityType() != null
? Granularity.fromString(dataFeedFilter.getGranularityType().toString()) : null,
dataFeedFilter.getStatus() != null
? EntityStatus.fromString(dataFeedFilter.getStatus().toString()) : null,
dataFeedFilter.getCreator(),
options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing information for all data feeds"))
.doOnSuccess(response -> logger.info("Listed data feeds {}", response))
.doOnError(error -> logger.warning("Failed to list all data feeds information - {}", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream().map(DataFeedTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataFeed>> listDataFeedsNextPageAsync(String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listDataFeedsNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream().map(DataFeedTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
/**
* Fetch the ingestion status of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeedIngestionStatus
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* final ListDataFeedIngestionOptions options = new ListDataFeedIngestionOptions&
* metricsAdvisorAdminAsyncClient.listDataFeedIngestionStatus&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeedIngestionStatus
*
* @param dataFeedId The data feed id.
* @param listDataFeedIngestionOptions The additional parameters.
*
* @return The ingestion statuses.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code options}, {@code options.startTime},
* {@code options.endTime} is null.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeedIngestionStatus> listDataFeedIngestionStatus(
String dataFeedId,
ListDataFeedIngestionOptions listDataFeedIngestionOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listDataFeedIngestionStatusSinglePageAsync(dataFeedId, listDataFeedIngestionOptions, context)),
continuationToken ->
withContext(context -> listDataFeedIngestionStatusNextPageAsync(continuationToken,
listDataFeedIngestionOptions,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<DataFeedIngestionStatus> listDataFeedIngestionStatus(
String dataFeedId,
ListDataFeedIngestionOptions options, Context context) {
return new PagedFlux<>(() ->
listDataFeedIngestionStatusSinglePageAsync(dataFeedId, options, context),
continuationToken ->
listDataFeedIngestionStatusNextPageAsync(continuationToken,
options,
context));
}
private Mono<PagedResponse<DataFeedIngestionStatus>> listDataFeedIngestionStatusSinglePageAsync(
String dataFeedId,
ListDataFeedIngestionOptions options, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
Objects.requireNonNull(options, "'options' is required.");
Objects.requireNonNull(options.getStartTime(), "'options.startTime' is required.");
Objects.requireNonNull(options.getEndTime(), "'options.endTime' is required.");
IngestionStatusQueryOptions queryOptions = new IngestionStatusQueryOptions()
.setStartTime(options.getStartTime())
.setEndTime(options.getEndTime());
return service.getDataFeedIngestionStatusSinglePageAsync(
UUID.fromString(dataFeedId),
queryOptions,
options.getSkip(),
options.getMaxPageSize(),
context)
.doOnRequest(ignoredValue -> logger.info("Listing ingestion status for data feed"))
.doOnSuccess(response -> logger.info("Listed ingestion status {}", response))
.doOnError(error -> logger.warning("Failed to ingestion status for data feed", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
toDataFeedIngestionStatus(res.getValue()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataFeedIngestionStatus>> listDataFeedIngestionStatusNextPageAsync(
String nextPageLink,
ListDataFeedIngestionOptions options,
Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
IngestionStatusQueryOptions queryOptions = new IngestionStatusQueryOptions()
.setStartTime(options.getStartTime())
.setEndTime(options.getEndTime());
return service.getDataFeedIngestionStatusNextSinglePageAsync(nextPageLink, queryOptions, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink, response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
toDataFeedIngestionStatus(res.getValue()),
res.getContinuationToken(),
null));
}
/**
* Refresh data ingestion for a period.
* <p>
* The data in the data source for the given period will be re-ingested
* and any ingested data for the same period will be overwritten.
* </p>
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestion
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* metricsAdvisorAdminAsyncClient.refreshDataFeedIngestion&
* startTime,
* endTime&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestion
*
* @param dataFeedId The data feed id.
* @param startTime The start point of the period.
* @param endTime The end point of of the period.
*
* @return A {@link Mono} indicating ingestion reset success or failure.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code startTime}, {@code endTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> refreshDataFeedIngestion(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime) {
return refreshDataFeedIngestionWithResponse(dataFeedId,
startTime,
endTime).then();
}
/**
* Refresh data ingestion for a period.
* <p>
* The data in the data source for the given period will be re-ingested
* and any ingested data for the same period will be overwritten.
* </p>
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestionWithResponse
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* metricsAdvisorAdminAsyncClient.refreshDataFeedIngestionWithResponse&
* startTime,
* endTime&
* .subscribe&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestionWithResponse
*
* @param dataFeedId The data feed id.
* @param startTime The start point of the period.
* @param endTime The end point of of the period.
*
* @return A {@link Response} of a {@link Mono} with result of reset request.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code startTime}, {@code endTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> refreshDataFeedIngestionWithResponse(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime) {
try {
return withContext(context -> refreshDataFeedIngestionWithResponse(dataFeedId,
startTime,
endTime, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> refreshDataFeedIngestionWithResponse(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
Objects.requireNonNull(startTime, "'startTime' is required.");
Objects.requireNonNull(endTime, "'endTime' is required.");
return service.resetDataFeedIngestionStatusWithResponseAsync(UUID.fromString(dataFeedId),
new IngestionProgressResetOptions()
.setStartTime(startTime)
.setEndTime(endTime),
context)
.doOnRequest(ignoredValue -> logger.info("Resetting ingestion status for the data feed"))
.doOnSuccess(response -> logger.info("Ingestion status got reset {}", response))
.doOnError(error -> logger.warning("Failed to reset ingestion status for the data feed", error));
}
/**
* Retrieve the ingestion progress of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgress
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* metricsAdvisorAdminAsyncClient.getDataFeedIngestionProgress&
* .subscribe&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgress
*
* @param dataFeedId The data feed id.
*
* @return A {@link Mono} containing {@link DataFeedIngestionProgress} of the data feed.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeedIngestionProgress> getDataFeedIngestionProgress(String dataFeedId) {
return getDataFeedIngestionProgressWithResponse(dataFeedId, Context.NONE)
.map(Response::getValue);
}
/**
* Retrieve the ingestion progress of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgressWithResponse
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* metricsAdvisorAdminAsyncClient.getDataFeedIngestionProgressWithResponse&
* .subscribe&
* System.out.printf&
* DataFeedIngestionProgress ingestionProgress = response.getValue&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgressWithResponse
*
* @param dataFeedId The data feed id.
*
* @return A {@link Response} of a {@link Mono} containing {@link DataFeedIngestionProgress} of the data feed.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeedIngestionProgress>> getDataFeedIngestionProgressWithResponse(String dataFeedId) {
try {
return withContext(context -> getDataFeedIngestionProgressWithResponse(dataFeedId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataFeedIngestionProgress>> getDataFeedIngestionProgressWithResponse(String dataFeedId,
Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
return service.getIngestionProgressWithResponseAsync(UUID.fromString(dataFeedId), context)
.doOnRequest(ignoredValue -> logger.info("Retrieving ingestion progress for metric"))
.doOnSuccess(response -> logger.info("Retrieved ingestion progress {}", response))
.doOnError(error -> logger.warning("Failed to retrieve ingestion progress for metric", error))
.map(response -> new SimpleResponse<>(response, toDataFeedIngestionProgress(response.getValue())));
}
private DataFeedIngestionProgress toDataFeedIngestionProgress(
com.azure.ai.metricsadvisor.implementation.models.DataFeedIngestionProgress dataFeedIngestionProgressResponse) {
DataFeedIngestionProgress dataFeedIngestionProgress = new DataFeedIngestionProgress();
DataFeedIngestionProgressHelper.setLatestActiveTimestamp(dataFeedIngestionProgress, dataFeedIngestionProgressResponse.getLatestActiveTimestamp());
DataFeedIngestionProgressHelper.setLatestSuccessTimestamp(dataFeedIngestionProgress, dataFeedIngestionProgressResponse.getLatestSuccessTimestamp());
return dataFeedIngestionProgress;
}
/**
* Create a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfig
* <pre>
* final MetricWholeSeriesDetectionCondition wholeSeriesCondition = new MetricWholeSeriesDetectionCondition&
* .setConditionOperator&
* .setSmartDetectionCondition&
* 50,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setHardThresholdCondition&
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setLowerBound&
* .setUpperBound&
* .setChangeThresholdCondition&
* 50,
* 30,
* true,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
*
* final String detectionConfigName = "my_detection_config";
* final String detectionConfigDescription = "anomaly detection config for metric";
* final AnomalyDetectionConfiguration detectionConfig
* = new AnomalyDetectionConfiguration&
* .setDescription&
* .setWholeSeriesDetectionCondition&
*
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient
* .createDetectionConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfig
*
* @param metricId The metric id to associate the configuration with.
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Mono} containing the created {@link AnomalyDetectionConfiguration}.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID
* format specification, or {@code detectionConfiguration.name} is not set.
* @throws NullPointerException thrown if the {@code metricId} is null
* or {@code detectionConfiguration} is null
* or {@code detectionConfiguration.wholeSeriesCondition} is null
* or {@code seriesKey} is missing for any {@code MetricSingleSeriesDetectionCondition} in the configuration
* or {@code seriesGroupKey} is missing for any {@code MetricSeriesGroupDetectionCondition} in the configuration
* or {@code conditionOperator} is missing when multiple nested conditions are set in a
* {@code MetricSingleSeriesDetectionCondition} or {@code MetricSeriesGroupDetectionCondition}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> createDetectionConfig(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration) {
return createDetectionConfigWithResponse(metricId, detectionConfiguration)
.map(Response::getValue);
}
/**
* Create a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfigWithResponse
* <pre>
* final MetricWholeSeriesDetectionCondition wholeSeriesCondition = new MetricWholeSeriesDetectionCondition&
* .setConditionOperator&
* .setSmartDetectionCondition&
* 50,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setHardThresholdCondition&
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setLowerBound&
* .setUpperBound&
* .setChangeThresholdCondition&
* 50,
* 30,
* true,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
*
* final String detectionConfigName = "my_detection_config";
* final String detectionConfigDescription = "anomaly detection config for metric";
* final AnomalyDetectionConfiguration detectionConfig
* = new AnomalyDetectionConfiguration&
* .setDescription&
* .setWholeSeriesDetectionCondition&
*
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient
* .createDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
* AnomalyDetectionConfiguration createdDetectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfigWithResponse
*
* @param metricId The metric id to associate the configuration with.
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Response} of a {@link Mono} containing the created {@link AnomalyDetectionConfiguration}.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID
* format specification, or {@code detectionConfiguration.name} is not set.
* @throws NullPointerException thrown if the {@code metricId} is null
* or {@code detectionConfiguration} is null
* or {@code detectionConfiguration.wholeSeriesCondition} is null
* or {@code seriesKey} is missing for any {@code MetricSingleSeriesDetectionCondition} in the configuration
* or {@code seriesGroupKey} is missing for any {@code MetricSeriesGroupDetectionCondition} in the configuration
* or {@code conditionOperator} is missing when multiple nested conditions are set in a
* {@code MetricSingleSeriesDetectionCondition} or {@code MetricSeriesGroupDetectionCondition}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> createDetectionConfigWithResponse(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration) {
try {
return withContext(context -> createDetectionConfigWithResponse(metricId,
detectionConfiguration,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> createDetectionConfigWithResponse(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration,
Context context) {
Objects.requireNonNull(metricId, "metricId is required");
Objects.requireNonNull(detectionConfiguration, "detectionConfiguration is required");
final com.azure.ai.metricsadvisor.implementation.models.AnomalyDetectionConfiguration
innerDetectionConfiguration = DetectionConfigurationTransforms.toInnerForCreate(logger,
metricId,
detectionConfiguration);
return service.createAnomalyDetectionConfigurationWithResponseAsync(innerDetectionConfiguration, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating AnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Created AnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to create AnomalyDetectionConfiguration", error))
.flatMap(response -> {
final String configurationId
= Utility.parseOperationId(response.getDeserializedHeaders().getLocation());
return getDetectionConfigWithResponse(configurationId, context)
.map(configurationResponse -> new ResponseBase<Void, AnomalyDetectionConfiguration>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Get the anomaly detection configuration by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
*
* System.out.printf&
*
* System.out.printf&
* MetricWholeSeriesDetectionCondition wholeSeriesDetectionCondition
* = detectionConfig.getWholeSeriesDetectionCondition&
*
* System.out.printf&
* wholeSeriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
*
* List<MetricSingleSeriesDetectionCondition> seriesDetectionConditions
* = detectionConfig.getSeriesDetectionConditions&
* System.out.printf&
* for &
* DimensionKey seriesKey = seriesDetectionCondition.getSeriesKey&
* final String seriesKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
*
* List<MetricSeriesGroupDetectionCondition> seriesGroupDetectionConditions
* = detectionConfig.getSeriesGroupDetectionConditions&
* System.out.printf&
* for &
* : seriesGroupDetectionConditions&
* DimensionKey seriesGroupKey = seriesGroupDetectionCondition.getSeriesGroupKey&
* final String seriesGroupKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfig
*
* @param detectionConfigurationId The anomaly detection configuration id.
* @return A {@link Mono} containing the {@link AnomalyDetectionConfiguration} for the provided id.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> getDetectionConfig(
String detectionConfigurationId) {
return getDetectionConfigWithResponse(detectionConfigurationId)
.map(Response::getValue);
}
/**
* Get the anomaly detection configuration by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
*
* AnomalyDetectionConfiguration detectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
*
* System.out.printf&
*
* System.out.printf&
* MetricWholeSeriesDetectionCondition wholeSeriesDetectionCondition
* = detectionConfig.getWholeSeriesDetectionCondition&
*
* System.out.printf&
* wholeSeriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
*
* List<MetricSingleSeriesDetectionCondition> seriesDetectionConditions
* = detectionConfig.getSeriesDetectionConditions&
* System.out.printf&
* for &
* DimensionKey seriesKey = seriesDetectionCondition.getSeriesKey&
* final String seriesKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
*
* List<MetricSeriesGroupDetectionCondition> seriesGroupDetectionConditions
* = detectionConfig.getSeriesGroupDetectionConditions&
* System.out.printf&
* for &
* : seriesGroupDetectionConditions&
* DimensionKey seriesGroupKey = seriesGroupDetectionCondition.getSeriesGroupKey&
* final String seriesGroupKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfigWithResponse
*
* @param detectionConfigurationId The anomaly detection configuration id.
* @return A {@link Response} of a {@link Mono} containing the {@link AnomalyDetectionConfiguration}
* for the provided id.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> getDetectionConfigWithResponse(
String detectionConfigurationId) {
try {
return withContext(context -> getDetectionConfigWithResponse(detectionConfigurationId,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> getDetectionConfigWithResponse(
String detectionConfigurationId, Context context) {
Objects.requireNonNull(detectionConfigurationId, "detectionConfigurationId is required.");
return service.getAnomalyDetectionConfigurationWithResponseAsync(UUID.fromString(detectionConfigurationId), context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving AnomalyDetectionConfiguration - {}",
detectionConfigurationId))
.doOnSuccess(response -> logger.info("Retrieved AnomalyDetectionConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to retrieve AnomalyDetectionConfiguration - {}",
detectionConfigurationId, error))
.map(response -> {
AnomalyDetectionConfiguration configuration
= DetectionConfigurationTransforms.fromInner(response.getValue());
return new ResponseBase<Void, AnomalyDetectionConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configuration,
null);
});
}
/**
* Update a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfig&
* .flatMap&
* detectionConfig.setName&
* detectionConfig.setDescription&
*
* DimensionKey seriesGroupKey = new DimensionKey&
* .put&
* detectionConfig.addSeriesGroupDetectionCondition&
* new MetricSeriesGroupDetectionCondition&
* .setSmartDetectionCondition&
* 10.0,
* AnomalyDetectorDirection.UP,
* new SuppressCondition&
* return metricsAdvisorAdminAsyncClient
* .updateDetectionConfig&
* &
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfig
*
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Mono} containing the updated {@link AnomalyDetectionConfiguration}.
* @throws NullPointerException thrown if the {@code detectionConfiguration} is null
* or {@code detectionConfiguration.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> updateDetectionConfig(
AnomalyDetectionConfiguration detectionConfiguration) {
return updateDetectionConfigWithResponse(detectionConfiguration)
.map(Response::getValue);
}
/**
* Update a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfigWithResponse&
* .flatMap&
* AnomalyDetectionConfiguration detectionConfig = response.getValue&
* detectionConfig.setName&
* detectionConfig.setDescription&
* DimensionKey seriesGroupKey = new DimensionKey&
* .put&
* detectionConfig.addSeriesGroupDetectionCondition&
* new MetricSeriesGroupDetectionCondition&
* .setSmartDetectionCondition&
* 10.0,
* AnomalyDetectorDirection.UP,
* new SuppressCondition&
* return metricsAdvisorAdminAsyncClient
* .updateDetectionConfigWithResponse&
* &
* .subscribe&
* AnomalyDetectionConfiguration updatedDetectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfigWithResponse
*
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Response} of a {@link Mono} containing the updated {@link AnomalyDetectionConfiguration}.
* @throws NullPointerException thrown if the {@code detectionConfiguration} is null
* or {@code detectionConfiguration.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> updateDetectionConfigWithResponse(
AnomalyDetectionConfiguration detectionConfiguration) {
try {
return withContext(context -> updateDetectionConfigWithResponse(detectionConfiguration,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> updateDetectionConfigWithResponse(
AnomalyDetectionConfiguration detectionConfiguration,
Context context) {
Objects.requireNonNull(detectionConfiguration, "detectionConfiguration is required");
Objects.requireNonNull(detectionConfiguration.getId(), "detectionConfiguration.id is required");
final AnomalyDetectionConfigurationPatch innerDetectionConfigurationPatch
= DetectionConfigurationTransforms.toInnerForUpdate(logger, detectionConfiguration);
return service.updateAnomalyDetectionConfigurationWithResponseAsync(
UUID.fromString(detectionConfiguration.getId()),
innerDetectionConfigurationPatch,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating AnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Updated AnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to update AnomalyDetectionConfiguration", error))
.flatMap(response -> {
return getDetectionConfigWithResponse(detectionConfiguration.getId(), context)
.map(configurationResponse -> new ResponseBase<Void, AnomalyDetectionConfiguration>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Delete a metric anomaly detection configuration.
*
* @param detectionConfigurationId The metric anomaly detection configuration unique id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .deleteDetectionConfig&
* .subscribe&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfig
*
* @return An empty Mono.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDetectionConfig(String detectionConfigurationId) {
return deleteDetectionConfigWithResponse(detectionConfigurationId).then();
}
/**
* Delete a metric anomaly detection configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .deleteDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfigWithResponse
*
* @param detectionConfigurationId The metric anomaly detection configuration unique id.
*
* @return A {@link Response} of a {@link Mono}.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDetectionConfigWithResponse(
String detectionConfigurationId) {
try {
return withContext(context -> deleteDetectionConfigWithResponse(
detectionConfigurationId,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> deleteDetectionConfigWithResponse(String detectionConfigurationId,
Context context) {
Objects.requireNonNull(detectionConfigurationId, "detectionConfigurationId is required.");
return service.deleteHookWithResponseAsync(UUID.fromString(detectionConfigurationId), context)
.doOnRequest(ignoredValue -> logger.info("Deleting MetricAnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Deleted MetricAnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to delete MetricAnomalyDetectionConfiguration", error));
}
/**
* Given a metric id, retrieve all anomaly detection configurations applied to it.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
* <pre>
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient.listDetectionConfigs&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
*
* @param metricId The metric id.
* @return The anomaly detection configurations.
* @throws NullPointerException thrown if the {@code metricId} is null.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId) {
return listDetectionConfigs(metricId, null);
}
/**
* Given a metric id, retrieve all anomaly detection configurations applied to it.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
* <pre>
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient.listDetectionConfigs&
* new ListDetectionConfigsOptions&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
*
* @param metricId The metric id.
* @param listDetectionConfigsOptions the additional configurable options to specify when querying the result.
* @return The anomaly detection configurations.
* @throws NullPointerException thrown if the {@code metricId} is null.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId,
ListDetectionConfigsOptions listDetectionConfigsOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listAnomalyDetectionConfigsSinglePageAsync(metricId, listDetectionConfigsOptions, context)),
continuationToken ->
withContext(context -> listAnomalyDetectionConfigsNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId,
ListDetectionConfigsOptions options,
Context context) {
return new PagedFlux<>(() ->
listAnomalyDetectionConfigsSinglePageAsync(metricId, options, context),
continuationToken ->
listAnomalyDetectionConfigsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<AnomalyDetectionConfiguration>> listAnomalyDetectionConfigsSinglePageAsync(
String metricId,
ListDetectionConfigsOptions options,
Context context) {
if (options == null) {
options = new ListDetectionConfigsOptions();
}
return service.getAnomalyDetectionConfigurationsByMetricSinglePageAsync(
UUID.fromString(metricId), options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing MetricAnomalyDetectionConfigs"))
.doOnSuccess(response -> logger.info("Listed MetricAnomalyDetectionConfigs {}", response))
.doOnError(error -> logger.warning("Failed to list the MetricAnomalyDetectionConfigs", error))
.map(DetectionConfigurationTransforms::fromInnerPagedResponse);
}
private Mono<PagedResponse<AnomalyDetectionConfiguration>> listAnomalyDetectionConfigsNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.getAnomalyDetectionConfigurationsByMetricNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(DetectionConfigurationTransforms::fromInnerPagedResponse);
}
/**
* Creates a notificationHook that receives anomaly incident alerts.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHook
* <pre>
* NotificationHook emailNotificationHook = new EmailNotificationHook&
* .setDescription&
* .setEmailsToAlert&
* add&
* &
* .setExternalLink&
*
* metricsAdvisorAdminAsyncClient.createHook&
* .subscribe&
* EmailNotificationHook createdEmailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* createdEmailHook.getEmailsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHook
*
* @param notificationHook The notificationHook.
*
* @return A {@link Mono} containing the created {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook}, {@code notificationHook.name},
* {@code notificationHook.endpoint} (for web notificationHook) is null.
* @throws IllegalArgumentException If at least one email not present for email notificationHook.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> createHook(NotificationHook notificationHook) {
return createHookWithResponse(notificationHook)
.map(Response::getValue);
}
/**
* Creates a notificationHook that receives anomaly incident alerts.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHookWithResponse
* <pre>
* NotificationHook emailNotificationHook = new EmailNotificationHook&
* .setDescription&
* .setEmailsToAlert&
* add&
* &
* .setExternalLink&
*
* metricsAdvisorAdminAsyncClient.createHookWithResponse&
* .subscribe&
* System.out.printf&
* EmailNotificationHook createdEmailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* createdEmailHook.getEmailsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHookWithResponse
*
* @param notificationHook The notificationHook.
*
* @return A {@link Response} of a {@link Mono} containing the created {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook}, {@code notificationHook.name},
* {@code notificationHook.endpoint} (for web notificationHook) is null.
* @throws IllegalArgumentException If at least one email not present for email notificationHook.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> createHookWithResponse(NotificationHook notificationHook) {
try {
return withContext(context -> createHookWithResponse(notificationHook, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> createHookWithResponse(NotificationHook notificationHook, Context context) {
Objects.requireNonNull(notificationHook, "'notificationHook' cannot be null.");
return service.createHookWithResponseAsync(HookTransforms.toInnerForCreate(logger, notificationHook), context)
.doOnRequest(ignoredValue -> logger.info("Creating NotificationHook"))
.doOnSuccess(response -> logger.info("Created NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to create notificationHook", error))
.flatMap(response -> {
final String hookUri = response.getDeserializedHeaders().getLocation();
final String hookId = parseOperationId(hookUri);
return getHookWithResponse(hookId, context)
.map(hookResponse -> new ResponseBase<Void, NotificationHook>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
hookResponse.getValue(),
null));
});
}
/**
* Get a hook by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHook
* <pre>
* final String hookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHook&
* .subscribe&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* emailHook.getEmailsToAlert&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHook
*
* @param hookId The hook unique id.
*
* @return A {@link Mono} containing the {@link NotificationHook} for the provided id.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code hookId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> getHook(String hookId) {
return getHookWithResponse(hookId).map(Response::getValue);
}
/**
* Get a hook by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHookWithResponse
* <pre>
* final String hookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHookWithResponse&
* .subscribe&
* System.out.printf&
* NotificationHook notificationHook = response.getValue&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHookWithResponse
*
* @param hookId The hook unique id.
*
* @return A {@link Response} of a {@link Mono} containing the {@link NotificationHook} for the provided id.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code hookId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> getHookWithResponse(String hookId) {
try {
return withContext(context -> getHookWithResponse(hookId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> getHookWithResponse(String hookId, Context context) {
Objects.requireNonNull(hookId, "hookId is required.");
return service.getHookWithResponseAsync(UUID.fromString(hookId), context)
.doOnRequest(ignoredValue -> logger.info("Retrieving NotificationHook"))
.doOnSuccess(response -> logger.info("Retrieved NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to retrieve hook", error))
.map(innerResponse -> new ResponseBase<Void, NotificationHook>(innerResponse.getRequest(),
innerResponse.getStatusCode(),
innerResponse.getHeaders(),
HookTransforms.fromInner(logger, innerResponse.getValue()),
null));
}
/**
* Update an existing notificationHook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHook
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHook&
* .flatMap&
* EmailNotificationHook emailHook = &
* List<String> emailsToUpdate = new ArrayList<>&
* emailsToUpdate.remove&
* emailsToUpdate.add&
* emailsToUpdate.add&
* emailHook.setEmailsToAlert&
* return metricsAdvisorAdminAsyncClient.updateHook&
* &
* .subscribe&
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHook
*
* @param notificationHook The notificationHook to update.
*
* @return A {@link Mono} containing the updated {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> updateHook(NotificationHook notificationHook) {
return updateHookWithResponse(notificationHook).map(Response::getValue);
}
/**
* Update an existing notification hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHookWithResponse
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHookWithResponse&
* .flatMap&
* EmailNotificationHook emailHook = &
* List<String> emailsToUpdate = new ArrayList<>&
* emailsToUpdate.remove&
* emailsToUpdate.add&
* emailsToUpdate.add&
* emailHook.setEmailsToAlert&
* return metricsAdvisorAdminAsyncClient.updateHookWithResponse&
* &
* .subscribe&
* System.out.printf&
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHookWithResponse
*
* @param notificationHook The notificationHook to update.
*
* @return A {@link Response} of a {@link Mono} containing the updated {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook.id} is null.
* @throws IllegalArgumentException If {@code notificationHook.Id} does not conform to the UUID format
* specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> updateHookWithResponse(NotificationHook notificationHook) {
try {
return withContext(context -> updateHookWithResponse(notificationHook, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> updateHookWithResponse(NotificationHook notificationHook, Context context) {
Objects.requireNonNull(notificationHook, "'notificationHook' cannot be null.");
Objects.requireNonNull(notificationHook.getId(), "'notificationHook.id' cannot be null.");
return service.updateHookWithResponseAsync(UUID.fromString(notificationHook.getId()),
HookTransforms.toInnerForUpdate(logger, notificationHook), context)
.doOnRequest(ignoredValue -> logger.info("Updating NotificationHook"))
.doOnSuccess(response -> logger.info("Updated NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to update notificationHook", error))
.flatMap(response -> getHookWithResponse(notificationHook.getId(), context)
.map(hookResponse -> new ResponseBase<Void, NotificationHook>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
hookResponse.getValue(),
null)));
}
/**
* Delete a hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHook
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.deleteHook&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHook
*
* @param hookId The hook unique id.
*
* @return An empty Mono.
* @throws NullPointerException thrown if the {@code hookId} is null.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteHook(String hookId) {
return deleteHookWithResponse(hookId).then();
}
/**
* Delete a hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHookWithResponse
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.deleteHookWithResponse&
* .subscribe&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHookWithResponse
*
* @param hookId The hook unique id.
*
* @return A {@link Response} of a {@link Mono}.
* @throws NullPointerException thrown if the {@code hookId} is null.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteHookWithResponse(String hookId) {
try {
return withContext(context -> deleteHookWithResponse(hookId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> deleteHookWithResponse(String hookId, Context context) {
Objects.requireNonNull(hookId, "hookId is required.");
return service.deleteHookWithResponseAsync(UUID.fromString(hookId), context)
.doOnRequest(ignoredValue -> logger.info("Deleting NotificationHook"))
.doOnSuccess(response -> logger.info("Deleted NotificationHook"))
.doOnError(error -> logger.warning("Failed to delete hook", error));
}
/**
* List information of hooks on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks -->
* <pre>
* metricsAdvisorAdminAsyncClient.listHooks&
* .subscribe&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks -->
*
* @return A {@link PagedFlux} containing information of all the {@link NotificationHook} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<NotificationHook> listHooks() {
return listHooks(new ListHookOptions());
}
/**
* List information of hooks.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks
* <pre>
* ListHookOptions options = new ListHookOptions&
* .setSkip&
* .setMaxPageSize&
* int[] pageCount = new int[1];
* metricsAdvisorAdminAsyncClient.listHooks&
* .subscribe&
* System.out.printf&
* for &
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks
*
* @param listHookOptions the additional configurable options to specify when listing hooks.
*
* @return A {@link PagedFlux} containing information of the {@link NotificationHook} resources.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<NotificationHook> listHooks(ListHookOptions listHookOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listHooksSinglePageAsync(listHookOptions, context)),
continuationToken ->
withContext(context -> listHooksNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<NotificationHook> listHooks(ListHookOptions options, Context context) {
return new PagedFlux<>(() ->
listHooksSinglePageAsync(options, context),
continuationToken ->
listHooksNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<NotificationHook>> listHooksSinglePageAsync(ListHookOptions options, Context context) {
return service.listHooksSinglePageAsync(
options != null ? options.getHookNameFilter() : null,
options != null ? options.getSkip() : null,
options != null ? options.getMaxPageSize() : null,
context)
.doOnRequest(ignoredValue -> logger.info("Listing hooks"))
.doOnSuccess(response -> logger.info("Listed hooks {}", response))
.doOnError(error -> logger.warning("Failed to list the hooks", error))
.map(response -> HookTransforms.fromInnerPagedResponse(logger, response));
}
private Mono<PagedResponse<NotificationHook>> listHooksNextPageAsync(String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listHooksNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(response -> HookTransforms.fromInnerPagedResponse(logger, response));
}
/**
* Create a configuration to trigger alert when anomalies are detected.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfig
* <pre>
* String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.createAlertConfig&
* new AnomalyAlertConfiguration&
* .setDescription&
* .setMetricAlertConfigurations&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* .setAlertConditions&
* .setSeverityRangeCondition&
* .setCrossMetricsOperator&
* .setHookIdsToAlert&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfig
*
* @param alertConfiguration The anomaly alerting configuration.
*
* @return A {@link Mono} containing the created {@link AnomalyAlertConfiguration}.
* @throws NullPointerException thrown if the {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> createAlertConfig(
AnomalyAlertConfiguration alertConfiguration) {
return createAlertConfigWithResponse(alertConfiguration).flatMap(FluxUtil::toMono);
}
/**
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfigWithResponse
* <pre>
*
* String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.createAlertConfigWithResponse&
* new AnomalyAlertConfiguration&
* .setDescription&
* .setMetricAlertConfigurations&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* .setAlertConditions&
* .setSeverityRangeCondition&
* .setCrossMetricsOperator&
* .setHookIdsToAlert&
* .subscribe&
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration anomalyAlertConfiguration = alertConfigurationResponse.getValue&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfigWithResponse
*
* @param alertConfiguration The anomaly alerting configuration.
*
* @return A {@link Response} of a {@link Mono} containing the created {@link AnomalyAlertConfiguration}.
* @throws NullPointerException thrown if the {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> createAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration) {
try {
return withContext(context -> createAlertConfigWithResponse(alertConfiguration, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> createAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration, Context context) {
Objects.requireNonNull(alertConfiguration, "'alertConfiguration' is required.");
if (CoreUtils.isNullOrEmpty(alertConfiguration.getMetricAlertConfigurations())) {
Objects.requireNonNull("'alertConfiguration.metricAnomalyAlertConfigurations' is required");
}
if (alertConfiguration.getCrossMetricsOperator() == null
&& alertConfiguration.getMetricAlertConfigurations().size() > 1) {
throw logger.logExceptionAsError(new IllegalArgumentException("crossMetricsOperator is required"
+ " when there are more than one metric level alert configuration."));
}
final AnomalyAlertingConfiguration innerAlertConfiguration
= AlertConfigurationTransforms.toInnerForCreate(alertConfiguration);
return service.createAnomalyAlertingConfigurationWithResponseAsync(innerAlertConfiguration, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating AnomalyAlertConfiguration - {}",
innerAlertConfiguration))
.doOnSuccess(response -> logger.info("Created AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to create AnomalyAlertConfiguration - {}",
innerAlertConfiguration, error))
.flatMap(response -> {
final String configurationId = parseOperationId(response.getDeserializedHeaders().getLocation());
return getAlertConfigWithResponse(configurationId, context)
.map(getResponse -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
getResponse.getValue(),
null));
});
}
/**
* Get the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfig
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfig
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A {@link Mono} containing the {@link AnomalyAlertConfiguration} identified by the given id.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> getAlertConfig(
String alertConfigurationId) {
return getAlertConfigWithResponse(alertConfigurationId).flatMap(FluxUtil::toMono);
}
/**
* Get the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfigWithResponse
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfigWithResponse&
* .subscribe&
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration anomalyAlertConfiguration = alertConfigurationResponse.getValue&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfigWithResponse
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A {@link Response response} of a {@link Mono}
* containing the {@link AnomalyAlertConfiguration} identified by the given id.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> getAlertConfigWithResponse(
String alertConfigurationId) {
try {
return withContext(context -> getAlertConfigWithResponse(alertConfigurationId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> getAlertConfigWithResponse(
String alertConfigurationId, Context context) {
Objects.requireNonNull(alertConfigurationId, "'alertConfigurationId' is required.");
return service.getAnomalyAlertingConfigurationWithResponseAsync(UUID.fromString(alertConfigurationId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving AnomalyDetectionConfiguration - {}",
alertConfigurationId))
.doOnSuccess(response -> logger.info("Retrieved AnomalyDetectionConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to retrieve AnomalyDetectionConfiguration - {}",
alertConfigurationId, error))
.map(response -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(), AlertConfigurationTransforms.fromInner(response.getValue()), null));
}
/**
* Update anomaly alert configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfig
* <pre>
*
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* String additionalHookId = "2gh8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .flatMap&
* List<String> hookIds = new ArrayList<>&
* hookIds.add&
* return metricsAdvisorAdminAsyncClient.updateAlertConfig&
* existingAnomalyConfig
* .setHookIdsToAlert&
* .setDescription&
* &
* System.out.printf&
* updateAnomalyAlertConfiguration.getId&
* System.out.printf&
* updateAnomalyAlertConfiguration.getDescription&
* System.out.printf&
* updateAnomalyAlertConfiguration.getHookIdsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfig
*
* @param alertConfiguration The anomaly alert configuration to update.
*
* @return A {@link Mono} containing the {@link AnomalyAlertConfiguration} that was updated.
* @throws NullPointerException thrown if {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null or empty.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> updateAlertConfig(
AnomalyAlertConfiguration alertConfiguration) {
return updateAlertConfigWithResponse(alertConfiguration).flatMap(FluxUtil::toMono);
}
/**
* Update anomaly alert configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfigWithResponse
* <pre>
*
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* String additionalHookId = "2gh8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .flatMap&
* List<String> hookIds = new ArrayList<>&
* hookIds.add&
* return metricsAdvisorAdminAsyncClient.updateAlertConfigWithResponse&
* existingAnomalyConfig
* .setHookIdsToAlert&
* .setDescription&
* &
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration updatedAnomalyAlertConfiguration
* = alertConfigurationResponse.getValue&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getId&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getDescription&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getHookIdsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfigWithResponse
*
* @param alertConfiguration The anomaly alert configuration to update.
*
* @return A {@link Response} of a {@link Mono} containing the {@link AnomalyAlertConfiguration} that was updated.
* @throws NullPointerException thrown if {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null or empty.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> updateAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration) {
try {
return withContext(context -> updateAlertConfigWithResponse(alertConfiguration, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> updateAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration, Context context) {
Objects.requireNonNull(alertConfiguration, "'alertConfiguration' is required");
if (CoreUtils.isNullOrEmpty(alertConfiguration.getMetricAlertConfigurations())) {
throw logger.logExceptionAsError(new NullPointerException(
"'alertConfiguration.metricAnomalyAlertConfigurations' is required and cannot be empty"));
}
final AnomalyAlertingConfigurationPatch innerAlertConfiguration
= AlertConfigurationTransforms.toInnerForUpdate(alertConfiguration);
return service.updateAnomalyAlertingConfigurationWithResponseAsync(
UUID.fromString(alertConfiguration.getId()),
innerAlertConfiguration,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating AnomalyAlertConfiguration - {}",
innerAlertConfiguration))
.doOnSuccess(response -> logger.info("Updated AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to update AnomalyAlertConfiguration - {}",
innerAlertConfiguration, error))
.flatMap(response -> getAlertConfigWithResponse(alertConfiguration.getId(), context)
.map(getResponse -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
getResponse.getValue(),
null)));
}
/**
* Deletes the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfig
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* metricsAdvisorAdminAsyncClient.deleteAlertConfig&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfig
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteAlertConfig(String alertConfigurationId) {
return deleteAlertConfigWithResponse(alertConfigurationId).flatMap(FluxUtil::toMono);
}
/**
* Deletes the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfigWithResponse
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.deleteAlertConfigWithResponse&
* .subscribe&
* System.out.printf&
* response.getStatusCode&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfigWithResponse
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteAlertConfigWithResponse(String alertConfigurationId) {
try {
return withContext(context -> deleteAlertConfigWithResponse(alertConfigurationId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteAlertConfigWithResponse(String alertConfigurationId, Context context) {
Objects.requireNonNull(alertConfigurationId, "'alertConfigurationId' is required.");
return service.deleteAnomalyAlertingConfigurationWithResponseAsync(UUID.fromString(alertConfigurationId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting AnomalyAlertConfiguration - {}", alertConfigurationId))
.doOnSuccess(response -> logger.info("Deleted AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to delete AnomalyAlertConfiguration - {}",
alertConfigurationId, error));
}
/**
* Fetch the anomaly alert configurations associated with a detection configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listAlertConfigs
* <pre>
* String detectionConfigId = "3rt98er30-6e6e-4391-b78f-bpfdfee1e6f5";
* metricsAdvisorAdminAsyncClient.listAlertConfigs&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listAlertConfigs
*
* @param detectionConfigurationId The id of the detection configuration.
* @param listAnomalyAlertConfigsOptions th e additional configurable options to specify when querying the result.
*
* @return A {@link PagedFlux} containing information of all the
* {@link AnomalyAlertConfiguration anomaly alert configurations} for the specified detection configuration.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the
* UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyAlertConfiguration> listAlertConfigs(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions listAnomalyAlertConfigsOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listAnomalyAlertConfigsSinglePageAsync(detectionConfigurationId,
listAnomalyAlertConfigsOptions,
context)),
continuationToken ->
withContext(context -> listAnomalyAlertConfigsNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<AnomalyAlertConfiguration> listAlertConfigs(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions options, Context context) {
return new PagedFlux<>(() ->
listAnomalyAlertConfigsSinglePageAsync(detectionConfigurationId,
options,
context),
continuationToken ->
listAnomalyAlertConfigsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<AnomalyAlertConfiguration>> listAnomalyAlertConfigsSinglePageAsync(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions options, Context context) {
Objects.requireNonNull(detectionConfigurationId, "'detectionConfigurationId' is required.");
if (options == null) {
options = new ListAnomalyAlertConfigsOptions();
}
return service.getAnomalyAlertingConfigurationsByAnomalyDetectionConfigurationSinglePageAsync(
UUID.fromString(detectionConfigurationId), options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing AnomalyAlertConfigs"))
.doOnSuccess(response -> logger.info("Listed AnomalyAlertConfigs {}", response))
.doOnError(error -> logger.warning("Failed to list the AnomalyAlertConfigs", error))
.map(AlertConfigurationTransforms::fromInnerPagedResponse);
}
private Mono<PagedResponse<AnomalyAlertConfiguration>> listAnomalyAlertConfigsNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.getAnomalyAlertingConfigurationsByAnomalyDetectionConfigurationNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(AlertConfigurationTransforms::fromInnerPagedResponse);
}
/**
* Create a data source credential entity.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredential
* <pre>
* DataSourceCredentialEntity datasourceCredential;
* final String name = "sample_name" + UUID.randomUUID&
* final String cId = "f45668b2-bffa-11eb-8529-0246ac130003";
* final String tId = "67890ded-5e07-4e52-b225-4ae8f905afb5";
* final String mockSecret = "890hy69-5e07-4e52-b225-4ae8f905afb5";
*
* datasourceCredential = new DataSourceServicePrincipalInKeyVault&
* .setName&
* .setKeyVaultForDataSourceSecrets&
* .setTenantId&
* .setSecretNameForDataSourceClientId&
* .setSecretNameForDataSourceClientSecret&
*
* metricsAdvisorAdminAsyncClient.createDataSourceCredential&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredential
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the created {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> createDataSourceCredential(
DataSourceCredentialEntity dataSourceCredential) {
return createDataSourceCredentialWithResponse(dataSourceCredential)
.map(Response::getValue);
}
/**
* Create a data source credential entity with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredentialWithResponse
* <pre>
* DataSourceCredentialEntity datasourceCredential;
* final String name = "sample_name" + UUID.randomUUID&
* final String cId = "f45668b2-bffa-11eb-8529-0246ac130003";
* final String tId = "67890ded-5e07-4e52-b225-4ae8f905afb5";
* final String mockSecret = "890hy69-5e07-4e52-b225-4ae8f905afb5";
*
* datasourceCredential = new DataSourceServicePrincipalInKeyVault&
* .setName&
* .setKeyVaultForDataSourceSecrets&
* .setTenantId&
* .setSecretNameForDataSourceClientId&
* .setSecretNameForDataSourceClientSecret&
*
* metricsAdvisorAdminAsyncClient.createDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredentialWithResponse
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the created {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> createDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential) {
try {
return withContext(context -> createDataSourceCredentialWithResponse(dataSourceCredential,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataSourceCredentialEntity>> createDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential,
Context context) {
Objects.requireNonNull(dataSourceCredential, "dataSourceCredential is required");
final DataSourceCredential
innerDataSourceCredential = DataSourceCredentialEntityTransforms.toInnerForCreate(dataSourceCredential);
return service.createCredentialWithResponseAsync(innerDataSourceCredential, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating DataSourceCredentialEntity"))
.doOnSuccess(response -> logger.info("Created DataSourceCredentialEntity"))
.doOnError(error -> logger.warning("Failed to create DataSourceCredentialEntity", error))
.flatMap(response -> {
final String credentialId
= Utility.parseOperationId(response.getDeserializedHeaders().getLocation());
return this.getDataSourceCredentialWithResponse(credentialId, context)
.map(configurationResponse -> new ResponseBase<Void, DataSourceCredentialEntity>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Update a data source credential entity.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredential
* <pre>
* String credentialId = "";
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .flatMap&
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV = null;
* if &
* actualCredentialSPInKV = &
* &
* return metricsAdvisorAdminAsyncClient.updateDataSourceCredential&
* actualCredentialSPInKV.setDescription&
* &
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getDescription&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredential
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the updated {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> updateDataSourceCredential(
DataSourceCredentialEntity dataSourceCredential) {
return updateDataSourceCredentialWithResponse(dataSourceCredential)
.map(Response::getValue);
}
/**
* Update a data source credential entity with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredentialWithResponse
* <pre>
* String credentialId = "";
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .flatMap&
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV = null;
* if &
* actualCredentialSPInKV = &
* &
* return metricsAdvisorAdminAsyncClient.updateDataSourceCredentialWithResponse&
* actualCredentialSPInKV.setDescription&
* &
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getDescription&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredentialWithResponse
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the updated {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> updateDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential) {
try {
return withContext(context -> updateDataSourceCredentialWithResponse(dataSourceCredential,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataSourceCredentialEntity>> updateDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential,
Context context) {
Objects.requireNonNull(dataSourceCredential, "dataSourceCredential is required");
final DataSourceCredentialPatch
innerDataSourceCredential = DataSourceCredentialEntityTransforms.toInnerForUpdate(dataSourceCredential);
return service.updateCredentialWithResponseAsync(UUID.fromString(dataSourceCredential.getId()),
innerDataSourceCredential,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating DataSourceCredentialEntity"))
.doOnSuccess(response -> logger.info("Updated DataSourceCredentialEntity"))
.doOnError(error -> logger.warning("Failed to update DataSourceCredentialEntity", error))
.flatMap(response -> {
return this.getDataSourceCredentialWithResponse(dataSourceCredential.getId(), context)
.map(configurationResponse -> new ResponseBase<Void, DataSourceCredentialEntity>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Get a data source credential entity by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredential
* <pre>
* final String datasourceCredentialId = "f45668b2-bffa-11eb-8529-0246ac130003";
*
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredential
*
* @param credentialId The data source credential entity unique id.
*
* @return The data source credential entity for the provided id.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> getDataSourceCredential(String credentialId) {
return getDataSourceCredentialWithResponse(credentialId).flatMap(FluxUtil::toMono);
}
/**
* Get a data source credential entity by its id with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredentialWithResponse
* <pre>
* final String datasourceCredentialId = "f45668b2-bffa-11eb-8529-0246ac130003";
*
* metricsAdvisorAdminAsyncClient.getDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredentialWithResponse
*
* @param credentialId The data source credential entity unique id.
*
* @return The data source credential entity for the provided id.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> getDataSourceCredentialWithResponse(
String credentialId) {
try {
return withContext(context -> getDataSourceCredentialWithResponse(credentialId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataSourceCredentialEntity>> getDataSourceCredentialWithResponse(String credentialId,
Context context) {
Objects.requireNonNull(credentialId, "'credentialId' cannot be null.");
return service.getCredentialWithResponseAsync(UUID.fromString(credentialId), context)
.map(response -> new SimpleResponse<>(response,
DataSourceCredentialEntityTransforms.fromInner(response.getValue())));
}
/**
* Deletes the data source credential entity identified by {@code credentialId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredential
* <pre>
* final String datasourceCredentialId = "t00853f1-9080-447f-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.deleteDataFeed&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredential
*
* @param credentialId The data source credential entity id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDataSourceCredential(String credentialId) {
return deleteDataSourceCredentialWithResponse(credentialId).flatMap(FluxUtil::toMono);
}
/**
* Deletes the data source credential entity identified by {@code credentialId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredentialWithResponse
* <pre>
* final String datasourceCredentialId = "eh0854f1-8927-447f-bacf-8dccf2e86fwe";
* metricsAdvisorAdminAsyncClient.deleteDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredentialWithResponse
*
* @param credentialId The data source credential entity id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDataSourceCredentialWithResponse(String credentialId) {
try {
return withContext(context -> deleteDataSourceCredentialWithResponse(credentialId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteDataSourceCredentialWithResponse(String credentialId, Context context) {
Objects.requireNonNull(credentialId, "'credentialId' is required.");
return service.deleteCredentialWithResponseAsync(UUID.fromString(credentialId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting deleteDataSourceCredentialEntity - {}",
credentialId))
.doOnSuccess(response -> logger.info("Deleted deleteDataSourceCredentialEntity - {}", response))
.doOnError(error -> logger.warning("Failed to delete deleteDataSourceCredentialEntity - {}",
credentialId, error));
}
/**
* List information of all data source credential entities on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials -->
* <pre>
* metricsAdvisorAdminAsyncClient.listDataSourceCredentials&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials -->
*
* @return A {@link PagedFlux} containing information of all the {@link DataSourceCredentialEntity data feeds}
* in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials() {
return listDataSourceCredentials(new ListCredentialEntityOptions());
}
/**
* List information of all data source credential entities on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials
* <pre>
* metricsAdvisorAdminAsyncClient.listDataSourceCredentials&
* new ListCredentialEntityOptions&
* .setMaxPageSize&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials
*
* @param listCredentialEntityOptions The configurable {@link ListCredentialEntityOptions options} to pass for filtering
* the output result.
*
* @return A {@link PagedFlux} containing information of all the {@link DataSourceCredentialEntity data feeds}
* in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials(ListCredentialEntityOptions listCredentialEntityOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listCredentialEntitiesSinglePageAsync(listCredentialEntityOptions, context)),
continuationToken ->
withContext(context -> listCredentialEntitiesSNextPageAsync(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials(ListCredentialEntityOptions options,
Context context) {
return new PagedFlux<>(() ->
listCredentialEntitiesSinglePageAsync(options, context),
continuationToken ->
listCredentialEntitiesSNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<DataSourceCredentialEntity>> listCredentialEntitiesSinglePageAsync(
ListCredentialEntityOptions options, Context context) {
options = options != null ? options : new ListCredentialEntityOptions();
return service.listCredentialsSinglePageAsync(options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing information for all data source credentials"))
.doOnSuccess(response -> logger.info("Listed data source credentials {}", response))
.doOnError(error -> logger.warning("Failed to list all data source credential information - {}", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream()
.map(DataSourceCredentialEntityTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataSourceCredentialEntity>> listCredentialEntitiesSNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listCredentialsNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream()
.map(DataSourceCredentialEntityTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
} | class MetricsAdvisorAdministrationAsyncClient {
private final ClientLogger logger = new ClientLogger(MetricsAdvisorAdministrationAsyncClient.class);
private final MetricsAdvisorImpl service;
/**
* Create a {@link MetricsAdvisorAdministrationAsyncClient} that sends requests to the Metrics Advisor
* service's endpoint. Each service call goes through the
* {@link MetricsAdvisorAdministrationClientBuilder
*
* @param service The proxy service used to perform REST calls.
* @param serviceVersion The versions of Azure Metrics Advisor supported by this client library.
*/
MetricsAdvisorAdministrationAsyncClient(MetricsAdvisorImpl service,
MetricsAdvisorServiceVersion serviceVersion) {
this.service = service;
}
/**
* Create a new data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeed
* <pre>
* DataFeed dataFeed = new DataFeed&
* .setName&
* .setSource&
* .setGranularity&
* .setSchema&
* Arrays.asList&
* new DataFeedMetric&
* new DataFeedMetric&
* &
* Arrays.asList&
* new DataFeedDimension&
* new DataFeedDimension&
* &
* &
* .setIngestionSettings&
* .setOptions&
* .setDescription&
* .setRollupSettings&
* .setRollupType&
*
* metricsAdvisorAdminAsyncClient.createDataFeed&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeed
*
* @param dataFeed The data feed to be created.
* @return A {@link Mono} containing the created data feed.
* @throws NullPointerException If {@code dataFeed}, {@code dataFeedName}, {@code dataFeedSource}, {@code metrics},
* {@code granularityType} or {@code ingestionStartTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> createDataFeed(DataFeed dataFeed) {
return createDataFeedWithResponse(dataFeed).flatMap(FluxUtil::toMono);
}
/**
* Create a new data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeedWithResponse
* <pre>
* DataFeed dataFeed = new DataFeed&
* .setName&
* .setSource&
* .setGranularity&
* .setSchema&
* Arrays.asList&
* new DataFeedMetric&
* new DataFeedMetric&
* &
* &
* .setIngestionSettings&
* .setOptions&
* .setDescription&
* .setRollupSettings&
* .setRollupType&
*
* metricsAdvisorAdminAsyncClient.createDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* DataFeed createdDataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeedWithResponse
* @param dataFeed The data feed to be created.
* @return A {@link Response} of a {@link Mono} containing the created {@link DataFeed data feed}.
* @throws NullPointerException If {@code dataFeed}, {@code dataFeedName}, {@code dataFeedSource}, {@code metrics},
* {@code granularityType} or {@code ingestionStartTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> createDataFeedWithResponse(DataFeed dataFeed) {
try {
return withContext(context -> createDataFeedWithResponse(dataFeed, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> createDataFeedWithResponse(DataFeed dataFeed, Context context) {
Objects.requireNonNull(dataFeed, "'dataFeed' is required and cannot be null.");
Objects.requireNonNull(dataFeed.getSource(), "'dataFeedSource' is required and cannot be null.");
Objects.requireNonNull(dataFeed.getName(), "'dataFeedName' cannot be null or empty.");
final DataFeedSchema dataFeedSchema = dataFeed.getSchema();
final DataFeedGranularity dataFeedGranularity = dataFeed.getGranularity();
final DataFeedIngestionSettings dataFeedIngestionSettings = dataFeed.getIngestionSettings();
if (dataFeedSchema == null) {
throw logger.logExceptionAsError(
new NullPointerException("'dataFeedSchema.metrics' cannot be null or empty."));
} else {
Objects.requireNonNull(dataFeedSchema.getMetrics(),
"'dataFeedSchema.metrics' cannot be null or empty.");
}
if (dataFeedGranularity == null) {
throw logger.logExceptionAsError(
new NullPointerException("'dataFeedGranularity.granularityType' is required and cannot be null."));
} else {
Objects.requireNonNull(dataFeedGranularity.getGranularityType(),
"'dataFeedGranularity.granularityType' is required.");
if (CUSTOM.equals(dataFeedGranularity.getGranularityType())) {
Objects.requireNonNull(dataFeedGranularity.getCustomGranularityValue(),
"'dataFeedGranularity.customGranularityValue' is required when granularity type is CUSTOM");
}
}
if (dataFeedIngestionSettings == null) {
throw logger.logExceptionAsError(
new NullPointerException(
"'dataFeedIngestionSettings.ingestionStartTime' is required and cannot be null."));
} else {
Objects.requireNonNull(dataFeedIngestionSettings.getIngestionStartTime(),
"'dataFeedIngestionSettings.ingestionStartTime' is required and cannot be null.");
}
final DataFeedOptions finalDataFeedOptions = dataFeed.getOptions() == null
? new DataFeedOptions() : dataFeed.getOptions();
final DataFeedRollupSettings dataFeedRollupSettings = finalDataFeedOptions.getRollupSettings() == null
? new DataFeedRollupSettings() : finalDataFeedOptions.getRollupSettings();
final DataFeedMissingDataPointFillSettings dataFeedMissingDataPointFillSettings =
finalDataFeedOptions.getMissingDataPointFillSettings() == null
? new DataFeedMissingDataPointFillSettings() : finalDataFeedOptions.getMissingDataPointFillSettings();
return service.createDataFeedWithResponseAsync(DataFeedTransforms.toDataFeedDetailSource(dataFeed.getSource())
.setDataFeedName(dataFeed.getName())
.setDataFeedDescription(finalDataFeedOptions.getDescription())
.setGranularityName(Granularity.fromString(dataFeedGranularity.getGranularityType() == null
? null : dataFeedGranularity.getGranularityType().toString()))
.setGranularityAmount(dataFeedGranularity.getCustomGranularityValue())
.setDimension(DataFeedTransforms.toInnerDimensionsListForCreate(dataFeedSchema.getDimensions()))
.setMetrics(DataFeedTransforms.toInnerMetricsListForCreate(dataFeedSchema.getMetrics()))
.setTimestampColumn(dataFeedSchema.getTimestampColumn())
.setDataStartFrom(dataFeedIngestionSettings.getIngestionStartTime())
.setStartOffsetInSeconds(dataFeedIngestionSettings.getIngestionStartOffset() == null
? null : dataFeedIngestionSettings.getIngestionStartOffset().getSeconds())
.setMaxConcurrency(dataFeedIngestionSettings.getDataSourceRequestConcurrency())
.setStopRetryAfterInSeconds(dataFeedIngestionSettings.getStopRetryAfter() == null
? null : dataFeedIngestionSettings.getStopRetryAfter().getSeconds())
.setMinRetryIntervalInSeconds(dataFeedIngestionSettings.getIngestionRetryDelay() == null
? null : dataFeedIngestionSettings.getIngestionRetryDelay().getSeconds())
.setRollUpColumns(dataFeedRollupSettings.getAutoRollupGroupByColumnNames())
.setRollUpMethod(RollUpMethod.fromString(dataFeedRollupSettings
.getDataFeedAutoRollUpMethod() == null
? null : dataFeedRollupSettings.getDataFeedAutoRollUpMethod().toString()))
.setNeedRollup(NeedRollupEnum.fromString(dataFeedRollupSettings.getRollupType() == null
? null : dataFeedRollupSettings.getRollupType().toString()))
.setAllUpIdentification(dataFeedRollupSettings.getRollupIdentificationValue())
.setFillMissingPointType(FillMissingPointType.fromString(
dataFeedMissingDataPointFillSettings.getFillType() == null
? null : dataFeedMissingDataPointFillSettings.getFillType().toString()))
.setFillMissingPointValue(dataFeedMissingDataPointFillSettings.getCustomFillValue())
.setViewMode(ViewMode.fromString(finalDataFeedOptions.getAccessMode() == null
? null : finalDataFeedOptions.getAccessMode().toString()))
.setViewers(finalDataFeedOptions.getViewers())
.setAdmins(finalDataFeedOptions.getAdmins())
.setActionLinkTemplate(finalDataFeedOptions.getActionLinkTemplate()), context)
.flatMap(createDataFeedResponse -> {
final String dataFeedId =
parseOperationId(createDataFeedResponse.getDeserializedHeaders().getLocation());
return getDataFeedWithResponse(dataFeedId);
});
}
/**
* Get a data feed by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeed
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeed
*
* @param dataFeedId The data feed unique id.
*
* @return The data feed for the provided id.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> getDataFeed(String dataFeedId) {
return getDataFeedWithResponse(dataFeedId).flatMap(FluxUtil::toMono);
}
/**
* Get a data feed by its id with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedWithResponse
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* DataFeed dataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedWithResponse
*
* @param dataFeedId The data feed unique id.
*
* @return The data feed for the provided id.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> getDataFeedWithResponse(String dataFeedId) {
try {
return withContext(context -> getDataFeedWithResponse(dataFeedId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> getDataFeedWithResponse(String dataFeedId, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' cannot be null.");
return service.getDataFeedByIdWithResponseAsync(UUID.fromString(dataFeedId), context)
.map(response -> new SimpleResponse<>(response, DataFeedTransforms.fromInner(response.getValue())));
}
/**
* Update an existing data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeed
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .flatMap&
* return metricsAdvisorAdminAsyncClient.updateDataFeed&
* existingDataFeed
* .setOptions&
* .setDescription&
* &
* &
* .subscribe&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeed
*
* @param dataFeed the data feed that needs to be updated.
*
* @return the updated data feed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> updateDataFeed(DataFeed dataFeed) {
return updateDataFeedWithResponse(dataFeed).flatMap(FluxUtil::toMono);
}
/**
* Update an existing data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeedWithResponse
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .flatMap&
* return metricsAdvisorAdminAsyncClient.updateDataFeedWithResponse&
* existingDataFeed
* .setOptions&
* .setDescription&
* &
* &
* .subscribe&
* System.out.printf&
* DataFeed updatedDataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeedWithResponse
*
* @param dataFeed the data feed that needs to be updated.
*
* @return the {@link Response} of a {@link Mono} containing the updated {@link DataFeed data feed}.
**/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> updateDataFeedWithResponse(DataFeed dataFeed) {
try {
return withContext(context -> updateDataFeedWithResponse(dataFeed, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> updateDataFeedWithResponse(DataFeed dataFeed, Context context) {
final DataFeedIngestionSettings dataFeedIngestionSettings = dataFeed.getIngestionSettings();
final DataFeedOptions dataFeedOptions = dataFeed.getOptions() == null
? new DataFeedOptions() : dataFeed.getOptions();
final DataFeedRollupSettings dataFeedRollupSettings = dataFeedOptions.getRollupSettings() == null
? new DataFeedRollupSettings() : dataFeedOptions.getRollupSettings();
final DataFeedMissingDataPointFillSettings dataFeedMissingDataPointFillSettings =
dataFeedOptions.getMissingDataPointFillSettings() == null
? new DataFeedMissingDataPointFillSettings() : dataFeedOptions.getMissingDataPointFillSettings();
return service.updateDataFeedWithResponseAsync(UUID.fromString(dataFeed.getId()),
DataFeedTransforms.toInnerForUpdate(dataFeed.getSource())
.setDataFeedName(dataFeed.getName())
.setDataFeedDescription(dataFeedOptions.getDescription())
.setTimestampColumn(dataFeed.getSchema() == null
? null : dataFeed.getSchema().getTimestampColumn())
.setDataStartFrom(dataFeed.getIngestionSettings().getIngestionStartTime())
.setStartOffsetInSeconds(dataFeedIngestionSettings.getIngestionStartOffset() == null
? null : dataFeedIngestionSettings.getIngestionStartOffset().getSeconds())
.setMaxConcurrency(dataFeedIngestionSettings.getDataSourceRequestConcurrency())
.setStopRetryAfterInSeconds(dataFeedIngestionSettings.getStopRetryAfter() == null
? null : dataFeedIngestionSettings.getStopRetryAfter().getSeconds())
.setMinRetryIntervalInSeconds(dataFeedIngestionSettings.getIngestionRetryDelay() == null
? null : dataFeedIngestionSettings.getIngestionRetryDelay().getSeconds())
.setNeedRollup(
dataFeedRollupSettings.getRollupType() != null
? NeedRollupEnum.fromString(dataFeedRollupSettings.getRollupType().toString())
: null)
.setRollUpColumns(dataFeedRollupSettings.getAutoRollupGroupByColumnNames())
.setRollUpMethod(
dataFeedRollupSettings.getDataFeedAutoRollUpMethod() != null
? RollUpMethod.fromString(
dataFeedRollupSettings.getDataFeedAutoRollUpMethod().toString())
: null)
.setAllUpIdentification(dataFeedRollupSettings.getRollupIdentificationValue())
.setFillMissingPointType(
dataFeedMissingDataPointFillSettings.getFillType() != null
? FillMissingPointType.fromString(
dataFeedMissingDataPointFillSettings.getFillType().toString())
: null)
.setFillMissingPointValue(
dataFeedMissingDataPointFillSettings.getFillType() == DataFeedMissingDataPointFillType.CUSTOM_VALUE
? dataFeedMissingDataPointFillSettings.getCustomFillValue()
: null)
.setViewMode(
dataFeedOptions.getAccessMode() != null
? ViewMode.fromString(dataFeedOptions.getAccessMode().toString())
: null)
.setViewers(dataFeedOptions.getViewers())
.setAdmins(dataFeedOptions.getAdmins())
.setStatus(
dataFeed.getStatus() != null
? EntityStatus.fromString(dataFeed.getStatus().toString())
: null)
.setActionLinkTemplate(dataFeedOptions.getActionLinkTemplate()), context)
.flatMap(updatedDataFeedResponse -> getDataFeedWithResponse(dataFeed.getId()));
}
/**
* Delete a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeed
* <pre>
* final String dataFeedId = "t00853f1-9080-447f-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.deleteDataFeed&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeed
*
* @param dataFeedId The data feed unique id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDataFeed(String dataFeedId) {
return deleteDataFeedWithResponse(dataFeedId).flatMap(FluxUtil::toMono);
}
/**
* Delete a data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeedWithResponse
* <pre>
* final String dataFeedId = "eh0854f1-8927-447f-bacf-8dccf2e86fwe";
* metricsAdvisorAdminAsyncClient.deleteDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeedWithResponse
*
* @param dataFeedId The data feed unique id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDataFeedWithResponse(String dataFeedId) {
try {
return withContext(context -> deleteDataFeedWithResponse(dataFeedId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteDataFeedWithResponse(String dataFeedId, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' cannot be null.");
return service.deleteDataFeedWithResponseAsync(UUID.fromString(dataFeedId), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* List information of all data feeds on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds -->
* <pre>
* metricsAdvisorAdminAsyncClient.listDataFeeds&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds -->
*
* @return A {@link PagedFlux} containing information of all the {@link DataFeed data feeds} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeed> listDataFeeds() {
return listDataFeeds(new ListDataFeedOptions());
}
/**
* List information of all data feeds on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds
* <pre>
* metricsAdvisorAdminAsyncClient.listDataFeeds&
* new ListDataFeedOptions&
* .setListDataFeedFilter&
* new ListDataFeedFilter&
* .setDataFeedStatus&
* .setDataFeedGranularityType&
* .setMaxPageSize&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds
*
* @param listDataFeedOptions The configurable {@link ListDataFeedOptions options} to pass for filtering the output result.
*
* @return A {@link PagedFlux} containing information of all the {@link DataFeed data feeds} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeed> listDataFeeds(ListDataFeedOptions listDataFeedOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listDataFeedsSinglePageAsync(listDataFeedOptions, context)),
continuationToken ->
withContext(context -> listDataFeedsNextPageAsync(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DataFeed> listDataFeeds(ListDataFeedOptions options, Context context) {
return new PagedFlux<>(() ->
listDataFeedsSinglePageAsync(options, context),
continuationToken ->
listDataFeedsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<DataFeed>> listDataFeedsSinglePageAsync(ListDataFeedOptions options, Context context) {
options = options != null ? options : new ListDataFeedOptions();
final ListDataFeedFilter dataFeedFilter =
options.getListDataFeedFilter() != null ? options.getListDataFeedFilter() : new ListDataFeedFilter();
return service.listDataFeedsSinglePageAsync(dataFeedFilter.getName(),
dataFeedFilter.getSourceType() != null
? DataSourceType.fromString(dataFeedFilter.getSourceType().toString()) : null,
dataFeedFilter.getGranularityType() != null
? Granularity.fromString(dataFeedFilter.getGranularityType().toString()) : null,
dataFeedFilter.getStatus() != null
? EntityStatus.fromString(dataFeedFilter.getStatus().toString()) : null,
dataFeedFilter.getCreator(),
options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing information for all data feeds"))
.doOnSuccess(response -> logger.info("Listed data feeds {}", response))
.doOnError(error -> logger.warning("Failed to list all data feeds information - {}", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream().map(DataFeedTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataFeed>> listDataFeedsNextPageAsync(String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listDataFeedsNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream().map(DataFeedTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
/**
* Fetch the ingestion status of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeedIngestionStatus
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* final ListDataFeedIngestionOptions options = new ListDataFeedIngestionOptions&
* metricsAdvisorAdminAsyncClient.listDataFeedIngestionStatus&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeedIngestionStatus
*
* @param dataFeedId The data feed id.
* @param listDataFeedIngestionOptions The additional parameters.
*
* @return The ingestion statuses.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code options}, {@code options.startTime},
* {@code options.endTime} is null.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeedIngestionStatus> listDataFeedIngestionStatus(
String dataFeedId,
ListDataFeedIngestionOptions listDataFeedIngestionOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listDataFeedIngestionStatusSinglePageAsync(dataFeedId, listDataFeedIngestionOptions, context)),
continuationToken ->
withContext(context -> listDataFeedIngestionStatusNextPageAsync(continuationToken,
listDataFeedIngestionOptions,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<DataFeedIngestionStatus> listDataFeedIngestionStatus(
String dataFeedId,
ListDataFeedIngestionOptions options, Context context) {
return new PagedFlux<>(() ->
listDataFeedIngestionStatusSinglePageAsync(dataFeedId, options, context),
continuationToken ->
listDataFeedIngestionStatusNextPageAsync(continuationToken,
options,
context));
}
private Mono<PagedResponse<DataFeedIngestionStatus>> listDataFeedIngestionStatusSinglePageAsync(
String dataFeedId,
ListDataFeedIngestionOptions options, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
Objects.requireNonNull(options, "'options' is required.");
Objects.requireNonNull(options.getStartTime(), "'options.startTime' is required.");
Objects.requireNonNull(options.getEndTime(), "'options.endTime' is required.");
IngestionStatusQueryOptions queryOptions = new IngestionStatusQueryOptions()
.setStartTime(options.getStartTime())
.setEndTime(options.getEndTime());
return service.getDataFeedIngestionStatusSinglePageAsync(
UUID.fromString(dataFeedId),
queryOptions,
options.getSkip(),
options.getMaxPageSize(),
context)
.doOnRequest(ignoredValue -> logger.info("Listing ingestion status for data feed"))
.doOnSuccess(response -> logger.info("Listed ingestion status {}", response))
.doOnError(error -> logger.warning("Failed to ingestion status for data feed", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
toDataFeedIngestionStatus(res.getValue()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataFeedIngestionStatus>> listDataFeedIngestionStatusNextPageAsync(
String nextPageLink,
ListDataFeedIngestionOptions options,
Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
IngestionStatusQueryOptions queryOptions = new IngestionStatusQueryOptions()
.setStartTime(options.getStartTime())
.setEndTime(options.getEndTime());
return service.getDataFeedIngestionStatusNextSinglePageAsync(nextPageLink, queryOptions, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink, response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
toDataFeedIngestionStatus(res.getValue()),
res.getContinuationToken(),
null));
}
/**
* Refresh data ingestion for a period.
* <p>
* The data in the data source for the given period will be re-ingested
* and any ingested data for the same period will be overwritten.
* </p>
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestion
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* metricsAdvisorAdminAsyncClient.refreshDataFeedIngestion&
* startTime,
* endTime&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestion
*
* @param dataFeedId The data feed id.
* @param startTime The start point of the period.
* @param endTime The end point of of the period.
*
* @return A {@link Mono} indicating ingestion reset success or failure.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code startTime}, {@code endTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> refreshDataFeedIngestion(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime) {
return refreshDataFeedIngestionWithResponse(dataFeedId,
startTime,
endTime).then();
}
/**
* Refresh data ingestion for a period.
* <p>
* The data in the data source for the given period will be re-ingested
* and any ingested data for the same period will be overwritten.
* </p>
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestionWithResponse
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* metricsAdvisorAdminAsyncClient.refreshDataFeedIngestionWithResponse&
* startTime,
* endTime&
* .subscribe&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestionWithResponse
*
* @param dataFeedId The data feed id.
* @param startTime The start point of the period.
* @param endTime The end point of of the period.
*
* @return A {@link Response} of a {@link Mono} with result of reset request.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code startTime}, {@code endTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> refreshDataFeedIngestionWithResponse(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime) {
try {
return withContext(context -> refreshDataFeedIngestionWithResponse(dataFeedId,
startTime,
endTime, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> refreshDataFeedIngestionWithResponse(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
Objects.requireNonNull(startTime, "'startTime' is required.");
Objects.requireNonNull(endTime, "'endTime' is required.");
return service.resetDataFeedIngestionStatusWithResponseAsync(UUID.fromString(dataFeedId),
new IngestionProgressResetOptions()
.setStartTime(startTime)
.setEndTime(endTime),
context)
.doOnRequest(ignoredValue -> logger.info("Resetting ingestion status for the data feed"))
.doOnSuccess(response -> logger.info("Ingestion status got reset {}", response))
.doOnError(error -> logger.warning("Failed to reset ingestion status for the data feed", error));
}
/**
* Retrieve the ingestion progress of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgress
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* metricsAdvisorAdminAsyncClient.getDataFeedIngestionProgress&
* .subscribe&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgress
*
* @param dataFeedId The data feed id.
*
* @return A {@link Mono} containing {@link DataFeedIngestionProgress} of the data feed.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeedIngestionProgress> getDataFeedIngestionProgress(String dataFeedId) {
return getDataFeedIngestionProgressWithResponse(dataFeedId, Context.NONE)
.map(Response::getValue);
}
/**
* Retrieve the ingestion progress of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgressWithResponse
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* metricsAdvisorAdminAsyncClient.getDataFeedIngestionProgressWithResponse&
* .subscribe&
* System.out.printf&
* DataFeedIngestionProgress ingestionProgress = response.getValue&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgressWithResponse
*
* @param dataFeedId The data feed id.
*
* @return A {@link Response} of a {@link Mono} containing {@link DataFeedIngestionProgress} of the data feed.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeedIngestionProgress>> getDataFeedIngestionProgressWithResponse(String dataFeedId) {
try {
return withContext(context -> getDataFeedIngestionProgressWithResponse(dataFeedId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataFeedIngestionProgress>> getDataFeedIngestionProgressWithResponse(String dataFeedId,
Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
return service.getIngestionProgressWithResponseAsync(UUID.fromString(dataFeedId), context)
.doOnRequest(ignoredValue -> logger.info("Retrieving ingestion progress for metric"))
.doOnSuccess(response -> logger.info("Retrieved ingestion progress {}", response))
.doOnError(error -> logger.warning("Failed to retrieve ingestion progress for metric", error))
.map(response -> new SimpleResponse<>(response, toDataFeedIngestionProgress(response.getValue())));
}
private DataFeedIngestionProgress toDataFeedIngestionProgress(
com.azure.ai.metricsadvisor.implementation.models.DataFeedIngestionProgress dataFeedIngestionProgressResponse) {
DataFeedIngestionProgress dataFeedIngestionProgress = new DataFeedIngestionProgress();
DataFeedIngestionProgressHelper.setLatestActiveTimestamp(dataFeedIngestionProgress, dataFeedIngestionProgressResponse.getLatestActiveTimestamp());
DataFeedIngestionProgressHelper.setLatestSuccessTimestamp(dataFeedIngestionProgress, dataFeedIngestionProgressResponse.getLatestSuccessTimestamp());
return dataFeedIngestionProgress;
}
/**
* Create a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfig
* <pre>
* final MetricWholeSeriesDetectionCondition wholeSeriesCondition = new MetricWholeSeriesDetectionCondition&
* .setConditionOperator&
* .setSmartDetectionCondition&
* 50,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setHardThresholdCondition&
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setLowerBound&
* .setUpperBound&
* .setChangeThresholdCondition&
* 50,
* 30,
* true,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
*
* final String detectionConfigName = "my_detection_config";
* final String detectionConfigDescription = "anomaly detection config for metric";
* final AnomalyDetectionConfiguration detectionConfig
* = new AnomalyDetectionConfiguration&
* .setDescription&
* .setWholeSeriesDetectionCondition&
*
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient
* .createDetectionConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfig
*
* @param metricId The metric id to associate the configuration with.
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Mono} containing the created {@link AnomalyDetectionConfiguration}.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID
* format specification, or {@code detectionConfiguration.name} is not set.
* @throws NullPointerException thrown if the {@code metricId} is null
* or {@code detectionConfiguration} is null
* or {@code detectionConfiguration.wholeSeriesCondition} is null
* or {@code seriesKey} is missing for any {@code MetricSingleSeriesDetectionCondition} in the configuration
* or {@code seriesGroupKey} is missing for any {@code MetricSeriesGroupDetectionCondition} in the configuration
* or {@code conditionOperator} is missing when multiple nested conditions are set in a
* {@code MetricSingleSeriesDetectionCondition} or {@code MetricSeriesGroupDetectionCondition}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> createDetectionConfig(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration) {
return createDetectionConfigWithResponse(metricId, detectionConfiguration)
.map(Response::getValue);
}
/**
* Create a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfigWithResponse
* <pre>
* final MetricWholeSeriesDetectionCondition wholeSeriesCondition = new MetricWholeSeriesDetectionCondition&
* .setConditionOperator&
* .setSmartDetectionCondition&
* 50,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setHardThresholdCondition&
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setLowerBound&
* .setUpperBound&
* .setChangeThresholdCondition&
* 50,
* 30,
* true,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
*
* final String detectionConfigName = "my_detection_config";
* final String detectionConfigDescription = "anomaly detection config for metric";
* final AnomalyDetectionConfiguration detectionConfig
* = new AnomalyDetectionConfiguration&
* .setDescription&
* .setWholeSeriesDetectionCondition&
*
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient
* .createDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
* AnomalyDetectionConfiguration createdDetectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfigWithResponse
*
* @param metricId The metric id to associate the configuration with.
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Response} of a {@link Mono} containing the created {@link AnomalyDetectionConfiguration}.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID
* format specification, or {@code detectionConfiguration.name} is not set.
* @throws NullPointerException thrown if the {@code metricId} is null
* or {@code detectionConfiguration} is null
* or {@code detectionConfiguration.wholeSeriesCondition} is null
* or {@code seriesKey} is missing for any {@code MetricSingleSeriesDetectionCondition} in the configuration
* or {@code seriesGroupKey} is missing for any {@code MetricSeriesGroupDetectionCondition} in the configuration
* or {@code conditionOperator} is missing when multiple nested conditions are set in a
* {@code MetricSingleSeriesDetectionCondition} or {@code MetricSeriesGroupDetectionCondition}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> createDetectionConfigWithResponse(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration) {
try {
return withContext(context -> createDetectionConfigWithResponse(metricId,
detectionConfiguration,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> createDetectionConfigWithResponse(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration,
Context context) {
Objects.requireNonNull(metricId, "metricId is required");
Objects.requireNonNull(detectionConfiguration, "detectionConfiguration is required");
final com.azure.ai.metricsadvisor.implementation.models.AnomalyDetectionConfiguration
innerDetectionConfiguration = DetectionConfigurationTransforms.toInnerForCreate(logger,
metricId,
detectionConfiguration);
return service.createAnomalyDetectionConfigurationWithResponseAsync(innerDetectionConfiguration, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating AnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Created AnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to create AnomalyDetectionConfiguration", error))
.flatMap(response -> {
final String configurationId
= Utility.parseOperationId(response.getDeserializedHeaders().getLocation());
return getDetectionConfigWithResponse(configurationId, context)
.map(configurationResponse -> new ResponseBase<Void, AnomalyDetectionConfiguration>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Get the anomaly detection configuration by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
*
* System.out.printf&
*
* System.out.printf&
* MetricWholeSeriesDetectionCondition wholeSeriesDetectionCondition
* = detectionConfig.getWholeSeriesDetectionCondition&
*
* System.out.printf&
* wholeSeriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
*
* List<MetricSingleSeriesDetectionCondition> seriesDetectionConditions
* = detectionConfig.getSeriesDetectionConditions&
* System.out.printf&
* for &
* DimensionKey seriesKey = seriesDetectionCondition.getSeriesKey&
* final String seriesKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
*
* List<MetricSeriesGroupDetectionCondition> seriesGroupDetectionConditions
* = detectionConfig.getSeriesGroupDetectionConditions&
* System.out.printf&
* for &
* : seriesGroupDetectionConditions&
* DimensionKey seriesGroupKey = seriesGroupDetectionCondition.getSeriesGroupKey&
* final String seriesGroupKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfig
*
* @param detectionConfigurationId The anomaly detection configuration id.
* @return A {@link Mono} containing the {@link AnomalyDetectionConfiguration} for the provided id.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> getDetectionConfig(
String detectionConfigurationId) {
return getDetectionConfigWithResponse(detectionConfigurationId)
.map(Response::getValue);
}
/**
* Get the anomaly detection configuration by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
*
* AnomalyDetectionConfiguration detectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
*
* System.out.printf&
*
* System.out.printf&
* MetricWholeSeriesDetectionCondition wholeSeriesDetectionCondition
* = detectionConfig.getWholeSeriesDetectionCondition&
*
* System.out.printf&
* wholeSeriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
*
* List<MetricSingleSeriesDetectionCondition> seriesDetectionConditions
* = detectionConfig.getSeriesDetectionConditions&
* System.out.printf&
* for &
* DimensionKey seriesKey = seriesDetectionCondition.getSeriesKey&
* final String seriesKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
*
* List<MetricSeriesGroupDetectionCondition> seriesGroupDetectionConditions
* = detectionConfig.getSeriesGroupDetectionConditions&
* System.out.printf&
* for &
* : seriesGroupDetectionConditions&
* DimensionKey seriesGroupKey = seriesGroupDetectionCondition.getSeriesGroupKey&
* final String seriesGroupKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfigWithResponse
*
* @param detectionConfigurationId The anomaly detection configuration id.
* @return A {@link Response} of a {@link Mono} containing the {@link AnomalyDetectionConfiguration}
* for the provided id.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> getDetectionConfigWithResponse(
String detectionConfigurationId) {
try {
return withContext(context -> getDetectionConfigWithResponse(detectionConfigurationId,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> getDetectionConfigWithResponse(
String detectionConfigurationId, Context context) {
Objects.requireNonNull(detectionConfigurationId, "detectionConfigurationId is required.");
return service.getAnomalyDetectionConfigurationWithResponseAsync(UUID.fromString(detectionConfigurationId), context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving AnomalyDetectionConfiguration - {}",
detectionConfigurationId))
.doOnSuccess(response -> logger.info("Retrieved AnomalyDetectionConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to retrieve AnomalyDetectionConfiguration - {}",
detectionConfigurationId, error))
.map(response -> {
AnomalyDetectionConfiguration configuration
= DetectionConfigurationTransforms.fromInner(response.getValue());
return new ResponseBase<Void, AnomalyDetectionConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configuration,
null);
});
}
/**
* Update a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfig&
* .flatMap&
* detectionConfig.setName&
* detectionConfig.setDescription&
*
* DimensionKey seriesGroupKey = new DimensionKey&
* .put&
* detectionConfig.addSeriesGroupDetectionCondition&
* new MetricSeriesGroupDetectionCondition&
* .setSmartDetectionCondition&
* 10.0,
* AnomalyDetectorDirection.UP,
* new SuppressCondition&
* return metricsAdvisorAdminAsyncClient
* .updateDetectionConfig&
* &
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfig
*
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Mono} containing the updated {@link AnomalyDetectionConfiguration}.
* @throws NullPointerException thrown if the {@code detectionConfiguration} is null
* or {@code detectionConfiguration.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> updateDetectionConfig(
AnomalyDetectionConfiguration detectionConfiguration) {
return updateDetectionConfigWithResponse(detectionConfiguration)
.map(Response::getValue);
}
/**
* Update a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfigWithResponse&
* .flatMap&
* AnomalyDetectionConfiguration detectionConfig = response.getValue&
* detectionConfig.setName&
* detectionConfig.setDescription&
* DimensionKey seriesGroupKey = new DimensionKey&
* .put&
* detectionConfig.addSeriesGroupDetectionCondition&
* new MetricSeriesGroupDetectionCondition&
* .setSmartDetectionCondition&
* 10.0,
* AnomalyDetectorDirection.UP,
* new SuppressCondition&
* return metricsAdvisorAdminAsyncClient
* .updateDetectionConfigWithResponse&
* &
* .subscribe&
* AnomalyDetectionConfiguration updatedDetectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfigWithResponse
*
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Response} of a {@link Mono} containing the updated {@link AnomalyDetectionConfiguration}.
* @throws NullPointerException thrown if the {@code detectionConfiguration} is null
* or {@code detectionConfiguration.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> updateDetectionConfigWithResponse(
AnomalyDetectionConfiguration detectionConfiguration) {
try {
return withContext(context -> updateDetectionConfigWithResponse(detectionConfiguration,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> updateDetectionConfigWithResponse(
AnomalyDetectionConfiguration detectionConfiguration,
Context context) {
Objects.requireNonNull(detectionConfiguration, "detectionConfiguration is required");
Objects.requireNonNull(detectionConfiguration.getId(), "detectionConfiguration.id is required");
final AnomalyDetectionConfigurationPatch innerDetectionConfigurationPatch
= DetectionConfigurationTransforms.toInnerForUpdate(logger, detectionConfiguration);
return service.updateAnomalyDetectionConfigurationWithResponseAsync(
UUID.fromString(detectionConfiguration.getId()),
innerDetectionConfigurationPatch,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating AnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Updated AnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to update AnomalyDetectionConfiguration", error))
.flatMap(response -> {
return getDetectionConfigWithResponse(detectionConfiguration.getId(), context)
.map(configurationResponse -> new ResponseBase<Void, AnomalyDetectionConfiguration>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Delete a metric anomaly detection configuration.
*
* @param detectionConfigurationId The metric anomaly detection configuration unique id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .deleteDetectionConfig&
* .subscribe&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfig
*
* @return An empty Mono.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDetectionConfig(String detectionConfigurationId) {
return deleteDetectionConfigWithResponse(detectionConfigurationId).then();
}
/**
* Delete a metric anomaly detection configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .deleteDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfigWithResponse
*
* @param detectionConfigurationId The metric anomaly detection configuration unique id.
*
* @return A {@link Response} of a {@link Mono}.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDetectionConfigWithResponse(
String detectionConfigurationId) {
try {
return withContext(context -> deleteDetectionConfigWithResponse(
detectionConfigurationId,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> deleteDetectionConfigWithResponse(String detectionConfigurationId,
Context context) {
Objects.requireNonNull(detectionConfigurationId, "detectionConfigurationId is required.");
return service.deleteHookWithResponseAsync(UUID.fromString(detectionConfigurationId), context)
.doOnRequest(ignoredValue -> logger.info("Deleting MetricAnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Deleted MetricAnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to delete MetricAnomalyDetectionConfiguration", error));
}
/**
* Given a metric id, retrieve all anomaly detection configurations applied to it.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
* <pre>
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient.listDetectionConfigs&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
*
* @param metricId The metric id.
* @return The anomaly detection configurations.
* @throws NullPointerException thrown if the {@code metricId} is null.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId) {
return listDetectionConfigs(metricId, null);
}
/**
* Given a metric id, retrieve all anomaly detection configurations applied to it.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
* <pre>
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient.listDetectionConfigs&
* new ListDetectionConfigsOptions&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
*
* @param metricId The metric id.
* @param listDetectionConfigsOptions the additional configurable options to specify when querying the result.
* @return The anomaly detection configurations.
* @throws NullPointerException thrown if the {@code metricId} is null.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId,
ListDetectionConfigsOptions listDetectionConfigsOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listAnomalyDetectionConfigsSinglePageAsync(metricId, listDetectionConfigsOptions, context)),
continuationToken ->
withContext(context -> listAnomalyDetectionConfigsNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId,
ListDetectionConfigsOptions options,
Context context) {
return new PagedFlux<>(() ->
listAnomalyDetectionConfigsSinglePageAsync(metricId, options, context),
continuationToken ->
listAnomalyDetectionConfigsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<AnomalyDetectionConfiguration>> listAnomalyDetectionConfigsSinglePageAsync(
String metricId,
ListDetectionConfigsOptions options,
Context context) {
if (options == null) {
options = new ListDetectionConfigsOptions();
}
return service.getAnomalyDetectionConfigurationsByMetricSinglePageAsync(
UUID.fromString(metricId), options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing MetricAnomalyDetectionConfigs"))
.doOnSuccess(response -> logger.info("Listed MetricAnomalyDetectionConfigs {}", response))
.doOnError(error -> logger.warning("Failed to list the MetricAnomalyDetectionConfigs", error))
.map(DetectionConfigurationTransforms::fromInnerPagedResponse);
}
private Mono<PagedResponse<AnomalyDetectionConfiguration>> listAnomalyDetectionConfigsNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.getAnomalyDetectionConfigurationsByMetricNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(DetectionConfigurationTransforms::fromInnerPagedResponse);
}
/**
* Creates a notificationHook that receives anomaly incident alerts.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHook
* <pre>
* NotificationHook emailNotificationHook = new EmailNotificationHook&
* .setDescription&
* .setEmailsToAlert&
* add&
* &
* .setExternalLink&
*
* metricsAdvisorAdminAsyncClient.createHook&
* .subscribe&
* EmailNotificationHook createdEmailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* createdEmailHook.getEmailsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHook
*
* @param notificationHook The notificationHook.
*
* @return A {@link Mono} containing the created {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook}, {@code notificationHook.name},
* {@code notificationHook.endpoint} (for web notificationHook) is null.
* @throws IllegalArgumentException If at least one email not present for email notificationHook.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> createHook(NotificationHook notificationHook) {
return createHookWithResponse(notificationHook)
.map(Response::getValue);
}
/**
* Creates a notificationHook that receives anomaly incident alerts.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHookWithResponse
* <pre>
* NotificationHook emailNotificationHook = new EmailNotificationHook&
* .setDescription&
* .setEmailsToAlert&
* add&
* &
* .setExternalLink&
*
* metricsAdvisorAdminAsyncClient.createHookWithResponse&
* .subscribe&
* System.out.printf&
* EmailNotificationHook createdEmailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* createdEmailHook.getEmailsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHookWithResponse
*
* @param notificationHook The notificationHook.
*
* @return A {@link Response} of a {@link Mono} containing the created {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook}, {@code notificationHook.name},
* {@code notificationHook.endpoint} (for web notificationHook) is null.
* @throws IllegalArgumentException If at least one email not present for email notificationHook.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> createHookWithResponse(NotificationHook notificationHook) {
try {
return withContext(context -> createHookWithResponse(notificationHook, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> createHookWithResponse(NotificationHook notificationHook, Context context) {
Objects.requireNonNull(notificationHook, "'notificationHook' cannot be null.");
return service.createHookWithResponseAsync(HookTransforms.toInnerForCreate(logger, notificationHook), context)
.doOnRequest(ignoredValue -> logger.info("Creating NotificationHook"))
.doOnSuccess(response -> logger.info("Created NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to create notificationHook", error))
.flatMap(response -> {
final String hookUri = response.getDeserializedHeaders().getLocation();
final String hookId = parseOperationId(hookUri);
return getHookWithResponse(hookId, context)
.map(hookResponse -> new ResponseBase<Void, NotificationHook>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
hookResponse.getValue(),
null));
});
}
/**
* Get a hook by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHook
* <pre>
* final String hookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHook&
* .subscribe&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* emailHook.getEmailsToAlert&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHook
*
* @param hookId The hook unique id.
*
* @return A {@link Mono} containing the {@link NotificationHook} for the provided id.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code hookId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> getHook(String hookId) {
return getHookWithResponse(hookId).map(Response::getValue);
}
/**
* Get a hook by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHookWithResponse
* <pre>
* final String hookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHookWithResponse&
* .subscribe&
* System.out.printf&
* NotificationHook notificationHook = response.getValue&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHookWithResponse
*
* @param hookId The hook unique id.
*
* @return A {@link Response} of a {@link Mono} containing the {@link NotificationHook} for the provided id.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code hookId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> getHookWithResponse(String hookId) {
try {
return withContext(context -> getHookWithResponse(hookId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> getHookWithResponse(String hookId, Context context) {
Objects.requireNonNull(hookId, "hookId is required.");
return service.getHookWithResponseAsync(UUID.fromString(hookId), context)
.doOnRequest(ignoredValue -> logger.info("Retrieving NotificationHook"))
.doOnSuccess(response -> logger.info("Retrieved NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to retrieve hook", error))
.map(innerResponse -> new ResponseBase<Void, NotificationHook>(innerResponse.getRequest(),
innerResponse.getStatusCode(),
innerResponse.getHeaders(),
HookTransforms.fromInner(logger, innerResponse.getValue()),
null));
}
/**
* Update an existing notificationHook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHook
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHook&
* .flatMap&
* EmailNotificationHook emailHook = &
* List<String> emailsToUpdate = new ArrayList<>&
* emailsToUpdate.remove&
* emailsToUpdate.add&
* emailsToUpdate.add&
* emailHook.setEmailsToAlert&
* return metricsAdvisorAdminAsyncClient.updateHook&
* &
* .subscribe&
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHook
*
* @param notificationHook The notificationHook to update.
*
* @return A {@link Mono} containing the updated {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> updateHook(NotificationHook notificationHook) {
return updateHookWithResponse(notificationHook).map(Response::getValue);
}
/**
* Update an existing notification hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHookWithResponse
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHookWithResponse&
* .flatMap&
* EmailNotificationHook emailHook = &
* List<String> emailsToUpdate = new ArrayList<>&
* emailsToUpdate.remove&
* emailsToUpdate.add&
* emailsToUpdate.add&
* emailHook.setEmailsToAlert&
* return metricsAdvisorAdminAsyncClient.updateHookWithResponse&
* &
* .subscribe&
* System.out.printf&
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHookWithResponse
*
* @param notificationHook The notificationHook to update.
*
* @return A {@link Response} of a {@link Mono} containing the updated {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook.id} is null.
* @throws IllegalArgumentException If {@code notificationHook.Id} does not conform to the UUID format
* specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> updateHookWithResponse(NotificationHook notificationHook) {
try {
return withContext(context -> updateHookWithResponse(notificationHook, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> updateHookWithResponse(NotificationHook notificationHook, Context context) {
Objects.requireNonNull(notificationHook, "'notificationHook' cannot be null.");
Objects.requireNonNull(notificationHook.getId(), "'notificationHook.id' cannot be null.");
return service.updateHookWithResponseAsync(UUID.fromString(notificationHook.getId()),
HookTransforms.toInnerForUpdate(logger, notificationHook), context)
.doOnRequest(ignoredValue -> logger.info("Updating NotificationHook"))
.doOnSuccess(response -> logger.info("Updated NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to update notificationHook", error))
.flatMap(response -> getHookWithResponse(notificationHook.getId(), context)
.map(hookResponse -> new ResponseBase<Void, NotificationHook>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
hookResponse.getValue(),
null)));
}
/**
* Delete a hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHook
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.deleteHook&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHook
*
* @param hookId The hook unique id.
*
* @return An empty Mono.
* @throws NullPointerException thrown if the {@code hookId} is null.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteHook(String hookId) {
return deleteHookWithResponse(hookId).then();
}
/**
* Delete a hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHookWithResponse
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.deleteHookWithResponse&
* .subscribe&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHookWithResponse
*
* @param hookId The hook unique id.
*
* @return A {@link Response} of a {@link Mono}.
* @throws NullPointerException thrown if the {@code hookId} is null.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteHookWithResponse(String hookId) {
try {
return withContext(context -> deleteHookWithResponse(hookId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> deleteHookWithResponse(String hookId, Context context) {
Objects.requireNonNull(hookId, "hookId is required.");
return service.deleteHookWithResponseAsync(UUID.fromString(hookId), context)
.doOnRequest(ignoredValue -> logger.info("Deleting NotificationHook"))
.doOnSuccess(response -> logger.info("Deleted NotificationHook"))
.doOnError(error -> logger.warning("Failed to delete hook", error));
}
/**
* List information of hooks on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks -->
* <pre>
* metricsAdvisorAdminAsyncClient.listHooks&
* .subscribe&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks -->
*
* @return A {@link PagedFlux} containing information of all the {@link NotificationHook} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<NotificationHook> listHooks() {
return listHooks(new ListHookOptions());
}
/**
* List information of hooks.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks
* <pre>
* ListHookOptions options = new ListHookOptions&
* .setSkip&
* .setMaxPageSize&
* int[] pageCount = new int[1];
* metricsAdvisorAdminAsyncClient.listHooks&
* .subscribe&
* System.out.printf&
* for &
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks
*
* @param listHookOptions the additional configurable options to specify when listing hooks.
*
* @return A {@link PagedFlux} containing information of the {@link NotificationHook} resources.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<NotificationHook> listHooks(ListHookOptions listHookOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listHooksSinglePageAsync(listHookOptions, context)),
continuationToken ->
withContext(context -> listHooksNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<NotificationHook> listHooks(ListHookOptions options, Context context) {
return new PagedFlux<>(() ->
listHooksSinglePageAsync(options, context),
continuationToken ->
listHooksNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<NotificationHook>> listHooksSinglePageAsync(ListHookOptions options, Context context) {
return service.listHooksSinglePageAsync(
options != null ? options.getHookNameFilter() : null,
options != null ? options.getSkip() : null,
options != null ? options.getMaxPageSize() : null,
context)
.doOnRequest(ignoredValue -> logger.info("Listing hooks"))
.doOnSuccess(response -> logger.info("Listed hooks {}", response))
.doOnError(error -> logger.warning("Failed to list the hooks", error))
.map(response -> HookTransforms.fromInnerPagedResponse(logger, response));
}
private Mono<PagedResponse<NotificationHook>> listHooksNextPageAsync(String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listHooksNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(response -> HookTransforms.fromInnerPagedResponse(logger, response));
}
/**
* Create a configuration to trigger alert when anomalies are detected.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfig
* <pre>
* String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.createAlertConfig&
* new AnomalyAlertConfiguration&
* .setDescription&
* .setMetricAlertConfigurations&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* .setAlertConditions&
* .setSeverityRangeCondition&
* .setCrossMetricsOperator&
* .setHookIdsToAlert&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfig
*
* @param alertConfiguration The anomaly alerting configuration.
*
* @return A {@link Mono} containing the created {@link AnomalyAlertConfiguration}.
* @throws NullPointerException thrown if the {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> createAlertConfig(
AnomalyAlertConfiguration alertConfiguration) {
return createAlertConfigWithResponse(alertConfiguration).flatMap(FluxUtil::toMono);
}
/**
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfigWithResponse
* <pre>
*
* String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.createAlertConfigWithResponse&
* new AnomalyAlertConfiguration&
* .setDescription&
* .setMetricAlertConfigurations&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* .setAlertConditions&
* .setSeverityRangeCondition&
* .setCrossMetricsOperator&
* .setHookIdsToAlert&
* .subscribe&
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration anomalyAlertConfiguration = alertConfigurationResponse.getValue&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfigWithResponse
*
* @param alertConfiguration The anomaly alerting configuration.
*
* @return A {@link Response} of a {@link Mono} containing the created {@link AnomalyAlertConfiguration}.
* @throws NullPointerException thrown if the {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> createAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration) {
try {
return withContext(context -> createAlertConfigWithResponse(alertConfiguration, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> createAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration, Context context) {
Objects.requireNonNull(alertConfiguration, "'alertConfiguration' is required.");
if (CoreUtils.isNullOrEmpty(alertConfiguration.getMetricAlertConfigurations())) {
Objects.requireNonNull("'alertConfiguration.metricAnomalyAlertConfigurations' is required");
}
if (alertConfiguration.getCrossMetricsOperator() == null
&& alertConfiguration.getMetricAlertConfigurations().size() > 1) {
throw logger.logExceptionAsError(new IllegalArgumentException("crossMetricsOperator is required"
+ " when there are more than one metric level alert configuration."));
}
final AnomalyAlertingConfiguration innerAlertConfiguration
= AlertConfigurationTransforms.toInnerForCreate(alertConfiguration);
return service.createAnomalyAlertingConfigurationWithResponseAsync(innerAlertConfiguration, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating AnomalyAlertConfiguration - {}",
innerAlertConfiguration))
.doOnSuccess(response -> logger.info("Created AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to create AnomalyAlertConfiguration - {}",
innerAlertConfiguration, error))
.flatMap(response -> {
final String configurationId = parseOperationId(response.getDeserializedHeaders().getLocation());
return getAlertConfigWithResponse(configurationId, context)
.map(getResponse -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
getResponse.getValue(),
null));
});
}
/**
* Get the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfig
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfig
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A {@link Mono} containing the {@link AnomalyAlertConfiguration} identified by the given id.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> getAlertConfig(
String alertConfigurationId) {
return getAlertConfigWithResponse(alertConfigurationId).flatMap(FluxUtil::toMono);
}
/**
* Get the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfigWithResponse
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfigWithResponse&
* .subscribe&
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration anomalyAlertConfiguration = alertConfigurationResponse.getValue&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfigWithResponse
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A {@link Response response} of a {@link Mono}
* containing the {@link AnomalyAlertConfiguration} identified by the given id.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> getAlertConfigWithResponse(
String alertConfigurationId) {
try {
return withContext(context -> getAlertConfigWithResponse(alertConfigurationId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> getAlertConfigWithResponse(
String alertConfigurationId, Context context) {
Objects.requireNonNull(alertConfigurationId, "'alertConfigurationId' is required.");
return service.getAnomalyAlertingConfigurationWithResponseAsync(UUID.fromString(alertConfigurationId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving AnomalyDetectionConfiguration - {}",
alertConfigurationId))
.doOnSuccess(response -> logger.info("Retrieved AnomalyDetectionConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to retrieve AnomalyDetectionConfiguration - {}",
alertConfigurationId, error))
.map(response -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(), AlertConfigurationTransforms.fromInner(response.getValue()), null));
}
/**
* Update anomaly alert configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfig
* <pre>
*
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* String additionalHookId = "2gh8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .flatMap&
* List<String> hookIds = new ArrayList<>&
* hookIds.add&
* return metricsAdvisorAdminAsyncClient.updateAlertConfig&
* existingAnomalyConfig
* .setHookIdsToAlert&
* .setDescription&
* &
* System.out.printf&
* updateAnomalyAlertConfiguration.getId&
* System.out.printf&
* updateAnomalyAlertConfiguration.getDescription&
* System.out.printf&
* updateAnomalyAlertConfiguration.getHookIdsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfig
*
* @param alertConfiguration The anomaly alert configuration to update.
*
* @return A {@link Mono} containing the {@link AnomalyAlertConfiguration} that was updated.
* @throws NullPointerException thrown if {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null or empty.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> updateAlertConfig(
AnomalyAlertConfiguration alertConfiguration) {
return updateAlertConfigWithResponse(alertConfiguration).flatMap(FluxUtil::toMono);
}
/**
* Update anomaly alert configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfigWithResponse
* <pre>
*
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* String additionalHookId = "2gh8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .flatMap&
* List<String> hookIds = new ArrayList<>&
* hookIds.add&
* return metricsAdvisorAdminAsyncClient.updateAlertConfigWithResponse&
* existingAnomalyConfig
* .setHookIdsToAlert&
* .setDescription&
* &
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration updatedAnomalyAlertConfiguration
* = alertConfigurationResponse.getValue&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getId&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getDescription&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getHookIdsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfigWithResponse
*
* @param alertConfiguration The anomaly alert configuration to update.
*
* @return A {@link Response} of a {@link Mono} containing the {@link AnomalyAlertConfiguration} that was updated.
* @throws NullPointerException thrown if {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null or empty.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> updateAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration) {
try {
return withContext(context -> updateAlertConfigWithResponse(alertConfiguration, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> updateAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration, Context context) {
Objects.requireNonNull(alertConfiguration, "'alertConfiguration' is required");
if (CoreUtils.isNullOrEmpty(alertConfiguration.getMetricAlertConfigurations())) {
throw logger.logExceptionAsError(new NullPointerException(
"'alertConfiguration.metricAnomalyAlertConfigurations' is required and cannot be empty"));
}
final AnomalyAlertingConfigurationPatch innerAlertConfiguration
= AlertConfigurationTransforms.toInnerForUpdate(alertConfiguration);
return service.updateAnomalyAlertingConfigurationWithResponseAsync(
UUID.fromString(alertConfiguration.getId()),
innerAlertConfiguration,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating AnomalyAlertConfiguration - {}",
innerAlertConfiguration))
.doOnSuccess(response -> logger.info("Updated AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to update AnomalyAlertConfiguration - {}",
innerAlertConfiguration, error))
.flatMap(response -> getAlertConfigWithResponse(alertConfiguration.getId(), context)
.map(getResponse -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
getResponse.getValue(),
null)));
}
/**
* Deletes the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfig
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* metricsAdvisorAdminAsyncClient.deleteAlertConfig&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfig
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteAlertConfig(String alertConfigurationId) {
return deleteAlertConfigWithResponse(alertConfigurationId).flatMap(FluxUtil::toMono);
}
/**
* Deletes the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfigWithResponse
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.deleteAlertConfigWithResponse&
* .subscribe&
* System.out.printf&
* response.getStatusCode&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfigWithResponse
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteAlertConfigWithResponse(String alertConfigurationId) {
try {
return withContext(context -> deleteAlertConfigWithResponse(alertConfigurationId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteAlertConfigWithResponse(String alertConfigurationId, Context context) {
Objects.requireNonNull(alertConfigurationId, "'alertConfigurationId' is required.");
return service.deleteAnomalyAlertingConfigurationWithResponseAsync(UUID.fromString(alertConfigurationId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting AnomalyAlertConfiguration - {}", alertConfigurationId))
.doOnSuccess(response -> logger.info("Deleted AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to delete AnomalyAlertConfiguration - {}",
alertConfigurationId, error));
}
/**
* Fetch the anomaly alert configurations associated with a detection configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listAlertConfigs
* <pre>
* String detectionConfigId = "3rt98er30-6e6e-4391-b78f-bpfdfee1e6f5";
* metricsAdvisorAdminAsyncClient.listAlertConfigs&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listAlertConfigs
*
* @param detectionConfigurationId The id of the detection configuration.
* @param listAnomalyAlertConfigsOptions th e additional configurable options to specify when querying the result.
*
* @return A {@link PagedFlux} containing information of all the
* {@link AnomalyAlertConfiguration anomaly alert configurations} for the specified detection configuration.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the
* UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyAlertConfiguration> listAlertConfigs(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions listAnomalyAlertConfigsOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listAnomalyAlertConfigsSinglePageAsync(detectionConfigurationId,
listAnomalyAlertConfigsOptions,
context)),
continuationToken ->
withContext(context -> listAnomalyAlertConfigsNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<AnomalyAlertConfiguration> listAlertConfigs(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions options, Context context) {
return new PagedFlux<>(() ->
listAnomalyAlertConfigsSinglePageAsync(detectionConfigurationId,
options,
context),
continuationToken ->
listAnomalyAlertConfigsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<AnomalyAlertConfiguration>> listAnomalyAlertConfigsSinglePageAsync(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions options, Context context) {
Objects.requireNonNull(detectionConfigurationId, "'detectionConfigurationId' is required.");
if (options == null) {
options = new ListAnomalyAlertConfigsOptions();
}
return service.getAnomalyAlertingConfigurationsByAnomalyDetectionConfigurationSinglePageAsync(
UUID.fromString(detectionConfigurationId), options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing AnomalyAlertConfigs"))
.doOnSuccess(response -> logger.info("Listed AnomalyAlertConfigs {}", response))
.doOnError(error -> logger.warning("Failed to list the AnomalyAlertConfigs", error))
.map(AlertConfigurationTransforms::fromInnerPagedResponse);
}
private Mono<PagedResponse<AnomalyAlertConfiguration>> listAnomalyAlertConfigsNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.getAnomalyAlertingConfigurationsByAnomalyDetectionConfigurationNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(AlertConfigurationTransforms::fromInnerPagedResponse);
}
/**
* Create a data source credential entity.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredential
* <pre>
* DataSourceCredentialEntity datasourceCredential;
* final String name = "sample_name" + UUID.randomUUID&
* final String cId = "f45668b2-bffa-11eb-8529-0246ac130003";
* final String tId = "67890ded-5e07-4e52-b225-4ae8f905afb5";
* final String mockSecret = "890hy69-5e07-4e52-b225-4ae8f905afb5";
*
* datasourceCredential = new DataSourceServicePrincipalInKeyVault&
* .setName&
* .setKeyVaultForDataSourceSecrets&
* .setTenantId&
* .setSecretNameForDataSourceClientId&
* .setSecretNameForDataSourceClientSecret&
*
* metricsAdvisorAdminAsyncClient.createDataSourceCredential&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredential
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the created {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> createDataSourceCredential(
DataSourceCredentialEntity dataSourceCredential) {
return createDataSourceCredentialWithResponse(dataSourceCredential)
.map(Response::getValue);
}
/**
* Create a data source credential entity with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredentialWithResponse
* <pre>
* DataSourceCredentialEntity datasourceCredential;
* final String name = "sample_name" + UUID.randomUUID&
* final String cId = "f45668b2-bffa-11eb-8529-0246ac130003";
* final String tId = "67890ded-5e07-4e52-b225-4ae8f905afb5";
* final String mockSecret = "890hy69-5e07-4e52-b225-4ae8f905afb5";
*
* datasourceCredential = new DataSourceServicePrincipalInKeyVault&
* .setName&
* .setKeyVaultForDataSourceSecrets&
* .setTenantId&
* .setSecretNameForDataSourceClientId&
* .setSecretNameForDataSourceClientSecret&
*
* metricsAdvisorAdminAsyncClient.createDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredentialWithResponse
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the created {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> createDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential) {
try {
return withContext(context -> createDataSourceCredentialWithResponse(dataSourceCredential,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataSourceCredentialEntity>> createDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential,
Context context) {
Objects.requireNonNull(dataSourceCredential, "dataSourceCredential is required");
final DataSourceCredential
innerDataSourceCredential = DataSourceCredentialEntityTransforms.toInnerForCreate(dataSourceCredential);
return service.createCredentialWithResponseAsync(innerDataSourceCredential, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating DataSourceCredentialEntity"))
.doOnSuccess(response -> logger.info("Created DataSourceCredentialEntity"))
.doOnError(error -> logger.warning("Failed to create DataSourceCredentialEntity", error))
.flatMap(response -> {
final String credentialId
= Utility.parseOperationId(response.getDeserializedHeaders().getLocation());
return this.getDataSourceCredentialWithResponse(credentialId, context)
.map(configurationResponse -> new ResponseBase<Void, DataSourceCredentialEntity>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Update a data source credential entity.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredential
* <pre>
* String credentialId = "";
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .flatMap&
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV = null;
* if &
* actualCredentialSPInKV = &
* &
* return metricsAdvisorAdminAsyncClient.updateDataSourceCredential&
* actualCredentialSPInKV.setDescription&
* &
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getDescription&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredential
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the updated {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> updateDataSourceCredential(
DataSourceCredentialEntity dataSourceCredential) {
return updateDataSourceCredentialWithResponse(dataSourceCredential)
.map(Response::getValue);
}
/**
* Update a data source credential entity with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredentialWithResponse
* <pre>
* String credentialId = "";
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .flatMap&
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV = null;
* if &
* actualCredentialSPInKV = &
* &
* return metricsAdvisorAdminAsyncClient.updateDataSourceCredentialWithResponse&
* actualCredentialSPInKV.setDescription&
* &
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getDescription&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredentialWithResponse
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the updated {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> updateDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential) {
try {
return withContext(context -> updateDataSourceCredentialWithResponse(dataSourceCredential,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataSourceCredentialEntity>> updateDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential,
Context context) {
Objects.requireNonNull(dataSourceCredential, "dataSourceCredential is required");
final DataSourceCredentialPatch
innerDataSourceCredential = DataSourceCredentialEntityTransforms.toInnerForUpdate(dataSourceCredential);
return service.updateCredentialWithResponseAsync(UUID.fromString(dataSourceCredential.getId()),
innerDataSourceCredential,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating DataSourceCredentialEntity"))
.doOnSuccess(response -> logger.info("Updated DataSourceCredentialEntity"))
.doOnError(error -> logger.warning("Failed to update DataSourceCredentialEntity", error))
.flatMap(response -> {
return this.getDataSourceCredentialWithResponse(dataSourceCredential.getId(), context)
.map(configurationResponse -> new ResponseBase<Void, DataSourceCredentialEntity>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Get a data source credential entity by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredential
* <pre>
* final String datasourceCredentialId = "f45668b2-bffa-11eb-8529-0246ac130003";
*
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredential
*
* @param credentialId The data source credential entity unique id.
*
* @return The data source credential entity for the provided id.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> getDataSourceCredential(String credentialId) {
return getDataSourceCredentialWithResponse(credentialId).flatMap(FluxUtil::toMono);
}
/**
* Get a data source credential entity by its id with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredentialWithResponse
* <pre>
* final String datasourceCredentialId = "f45668b2-bffa-11eb-8529-0246ac130003";
*
* metricsAdvisorAdminAsyncClient.getDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredentialWithResponse
*
* @param credentialId The data source credential entity unique id.
*
* @return The data source credential entity for the provided id.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> getDataSourceCredentialWithResponse(
String credentialId) {
try {
return withContext(context -> getDataSourceCredentialWithResponse(credentialId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataSourceCredentialEntity>> getDataSourceCredentialWithResponse(String credentialId,
Context context) {
Objects.requireNonNull(credentialId, "'credentialId' cannot be null.");
return service.getCredentialWithResponseAsync(UUID.fromString(credentialId), context)
.map(response -> new SimpleResponse<>(response,
DataSourceCredentialEntityTransforms.fromInner(response.getValue())));
}
/**
* Deletes the data source credential entity identified by {@code credentialId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredential
* <pre>
* final String datasourceCredentialId = "t00853f1-9080-447f-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.deleteDataFeed&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredential
*
* @param credentialId The data source credential entity id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDataSourceCredential(String credentialId) {
return deleteDataSourceCredentialWithResponse(credentialId).flatMap(FluxUtil::toMono);
}
/**
* Deletes the data source credential entity identified by {@code credentialId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredentialWithResponse
* <pre>
* final String datasourceCredentialId = "eh0854f1-8927-447f-bacf-8dccf2e86fwe";
* metricsAdvisorAdminAsyncClient.deleteDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredentialWithResponse
*
* @param credentialId The data source credential entity id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDataSourceCredentialWithResponse(String credentialId) {
try {
return withContext(context -> deleteDataSourceCredentialWithResponse(credentialId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteDataSourceCredentialWithResponse(String credentialId, Context context) {
Objects.requireNonNull(credentialId, "'credentialId' is required.");
return service.deleteCredentialWithResponseAsync(UUID.fromString(credentialId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting deleteDataSourceCredentialEntity - {}",
credentialId))
.doOnSuccess(response -> logger.info("Deleted deleteDataSourceCredentialEntity - {}", response))
.doOnError(error -> logger.warning("Failed to delete deleteDataSourceCredentialEntity - {}",
credentialId, error));
}
/**
* List information of all data source credential entities on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials -->
* <pre>
* metricsAdvisorAdminAsyncClient.listDataSourceCredentials&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials -->
*
* @return A {@link PagedFlux} containing information of all the {@link DataSourceCredentialEntity data feeds}
* in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials() {
return listDataSourceCredentials(new ListCredentialEntityOptions());
}
/**
* List information of all data source credential entities on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials
* <pre>
* metricsAdvisorAdminAsyncClient.listDataSourceCredentials&
* new ListCredentialEntityOptions&
* .setMaxPageSize&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials
*
* @param listCredentialEntityOptions The configurable {@link ListCredentialEntityOptions options} to pass for filtering
* the output result.
*
* @return A {@link PagedFlux} containing information of all the {@link DataSourceCredentialEntity data feeds}
* in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials(ListCredentialEntityOptions listCredentialEntityOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listCredentialEntitiesSinglePageAsync(listCredentialEntityOptions, context)),
continuationToken ->
withContext(context -> listCredentialEntitiesSNextPageAsync(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials(ListCredentialEntityOptions options,
Context context) {
return new PagedFlux<>(() ->
listCredentialEntitiesSinglePageAsync(options, context),
continuationToken ->
listCredentialEntitiesSNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<DataSourceCredentialEntity>> listCredentialEntitiesSinglePageAsync(
ListCredentialEntityOptions options, Context context) {
options = options != null ? options : new ListCredentialEntityOptions();
return service.listCredentialsSinglePageAsync(options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing information for all data source credentials"))
.doOnSuccess(response -> logger.info("Listed data source credentials {}", response))
.doOnError(error -> logger.warning("Failed to list all data source credential information - {}", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream()
.map(DataSourceCredentialEntityTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataSourceCredentialEntity>> listCredentialEntitiesSNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listCredentialsNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream()
.map(DataSourceCredentialEntityTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
} |
I think the issue is we need the `DataFeedIngestionStatus` in `admin.models` and not `models`. I believe earlier it was manually moved. But to make the swagger work as is without manual modifications we needed this transform. are there any other options we can do? | private List<DataFeedIngestionStatus> toDataFeedIngestionStatus(List<com.azure.ai.metricsadvisor.implementation.models.DataFeedIngestionStatus> ingestionStatusList) {
return ingestionStatusList
.stream()
.map(ingestionStatus -> {
DataFeedIngestionStatus dataFeedIngestionStatus = new DataFeedIngestionStatus();
DataFeedIngestionStatusHelper.setMessage(dataFeedIngestionStatus, ingestionStatus.getMessage());
DataFeedIngestionStatusHelper.setIngestionStatusType(dataFeedIngestionStatus, IngestionStatusType.fromString(toStringOrNull(ingestionStatus.getStatus())));
DataFeedIngestionStatusHelper.setTimestamp(dataFeedIngestionStatus, ingestionStatus.getTimestamp());
return dataFeedIngestionStatus;
})
.collect(Collectors.toList());
} | return dataFeedIngestionStatus; | private List<DataFeedIngestionStatus> toDataFeedIngestionStatus(List<com.azure.ai.metricsadvisor.implementation.models.DataFeedIngestionStatus> ingestionStatusList) {
return ingestionStatusList
.stream()
.map(ingestionStatus -> {
DataFeedIngestionStatus dataFeedIngestionStatus = new DataFeedIngestionStatus();
DataFeedIngestionStatusHelper.setMessage(dataFeedIngestionStatus, ingestionStatus.getMessage());
DataFeedIngestionStatusHelper.setIngestionStatusType(dataFeedIngestionStatus, IngestionStatusType.fromString(toStringOrNull(ingestionStatus.getStatus())));
DataFeedIngestionStatusHelper.setTimestamp(dataFeedIngestionStatus, ingestionStatus.getTimestamp());
return dataFeedIngestionStatus;
})
.collect(Collectors.toList());
} | class MetricsAdvisorAdministrationAsyncClient {
private final ClientLogger logger = new ClientLogger(MetricsAdvisorAdministrationAsyncClient.class);
private final MetricsAdvisorImpl service;
/**
* Create a {@link MetricsAdvisorAdministrationAsyncClient} that sends requests to the Metrics Advisor
* service's endpoint. Each service call goes through the
* {@link MetricsAdvisorAdministrationClientBuilder
*
* @param service The proxy service used to perform REST calls.
* @param serviceVersion The versions of Azure Metrics Advisor supported by this client library.
*/
MetricsAdvisorAdministrationAsyncClient(MetricsAdvisorImpl service,
MetricsAdvisorServiceVersion serviceVersion) {
this.service = service;
}
/**
* Create a new data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeed
* <pre>
* DataFeed dataFeed = new DataFeed&
* .setName&
* .setSource&
* .setGranularity&
* .setSchema&
* Arrays.asList&
* new DataFeedMetric&
* new DataFeedMetric&
* &
* Arrays.asList&
* new DataFeedDimension&
* new DataFeedDimension&
* &
* &
* .setIngestionSettings&
* .setOptions&
* .setDescription&
* .setRollupSettings&
* .setRollupType&
*
* metricsAdvisorAdminAsyncClient.createDataFeed&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeed
*
* @param dataFeed The data feed to be created.
* @return A {@link Mono} containing the created data feed.
* @throws NullPointerException If {@code dataFeed}, {@code dataFeedName}, {@code dataFeedSource}, {@code metrics},
* {@code granularityType} or {@code ingestionStartTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> createDataFeed(DataFeed dataFeed) {
return createDataFeedWithResponse(dataFeed).flatMap(FluxUtil::toMono);
}
/**
* Create a new data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeedWithResponse
* <pre>
* DataFeed dataFeed = new DataFeed&
* .setName&
* .setSource&
* .setGranularity&
* .setSchema&
* Arrays.asList&
* new DataFeedMetric&
* new DataFeedMetric&
* &
* &
* .setIngestionSettings&
* .setOptions&
* .setDescription&
* .setRollupSettings&
* .setRollupType&
*
* metricsAdvisorAdminAsyncClient.createDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* DataFeed createdDataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeedWithResponse
* @param dataFeed The data feed to be created.
* @return A {@link Response} of a {@link Mono} containing the created {@link DataFeed data feed}.
* @throws NullPointerException If {@code dataFeed}, {@code dataFeedName}, {@code dataFeedSource}, {@code metrics},
* {@code granularityType} or {@code ingestionStartTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> createDataFeedWithResponse(DataFeed dataFeed) {
try {
return withContext(context -> createDataFeedWithResponse(dataFeed, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> createDataFeedWithResponse(DataFeed dataFeed, Context context) {
Objects.requireNonNull(dataFeed, "'dataFeed' is required and cannot be null.");
Objects.requireNonNull(dataFeed.getSource(), "'dataFeedSource' is required and cannot be null.");
Objects.requireNonNull(dataFeed.getName(), "'dataFeedName' cannot be null or empty.");
final DataFeedSchema dataFeedSchema = dataFeed.getSchema();
final DataFeedGranularity dataFeedGranularity = dataFeed.getGranularity();
final DataFeedIngestionSettings dataFeedIngestionSettings = dataFeed.getIngestionSettings();
if (dataFeedSchema == null) {
throw logger.logExceptionAsError(
new NullPointerException("'dataFeedSchema.metrics' cannot be null or empty."));
} else {
Objects.requireNonNull(dataFeedSchema.getMetrics(),
"'dataFeedSchema.metrics' cannot be null or empty.");
}
if (dataFeedGranularity == null) {
throw logger.logExceptionAsError(
new NullPointerException("'dataFeedGranularity.granularityType' is required and cannot be null."));
} else {
Objects.requireNonNull(dataFeedGranularity.getGranularityType(),
"'dataFeedGranularity.granularityType' is required.");
if (CUSTOM.equals(dataFeedGranularity.getGranularityType())) {
Objects.requireNonNull(dataFeedGranularity.getCustomGranularityValue(),
"'dataFeedGranularity.customGranularityValue' is required when granularity type is CUSTOM");
}
}
if (dataFeedIngestionSettings == null) {
throw logger.logExceptionAsError(
new NullPointerException(
"'dataFeedIngestionSettings.ingestionStartTime' is required and cannot be null."));
} else {
Objects.requireNonNull(dataFeedIngestionSettings.getIngestionStartTime(),
"'dataFeedIngestionSettings.ingestionStartTime' is required and cannot be null.");
}
final DataFeedOptions finalDataFeedOptions = dataFeed.getOptions() == null
? new DataFeedOptions() : dataFeed.getOptions();
final DataFeedRollupSettings dataFeedRollupSettings = finalDataFeedOptions.getRollupSettings() == null
? new DataFeedRollupSettings() : finalDataFeedOptions.getRollupSettings();
final DataFeedMissingDataPointFillSettings dataFeedMissingDataPointFillSettings =
finalDataFeedOptions.getMissingDataPointFillSettings() == null
? new DataFeedMissingDataPointFillSettings() : finalDataFeedOptions.getMissingDataPointFillSettings();
return service.createDataFeedWithResponseAsync(DataFeedTransforms.toDataFeedDetailSource(dataFeed.getSource())
.setDataFeedName(dataFeed.getName())
.setDataFeedDescription(finalDataFeedOptions.getDescription())
.setGranularityName(Granularity.fromString(dataFeedGranularity.getGranularityType() == null
? null : dataFeedGranularity.getGranularityType().toString()))
.setGranularityAmount(dataFeedGranularity.getCustomGranularityValue())
.setDimension(DataFeedTransforms.toInnerDimensionsListForCreate(dataFeedSchema.getDimensions()))
.setMetrics(DataFeedTransforms.toInnerMetricsListForCreate(dataFeedSchema.getMetrics()))
.setTimestampColumn(dataFeedSchema.getTimestampColumn())
.setDataStartFrom(dataFeedIngestionSettings.getIngestionStartTime())
.setStartOffsetInSeconds(dataFeedIngestionSettings.getIngestionStartOffset() == null
? null : dataFeedIngestionSettings.getIngestionStartOffset().getSeconds())
.setMaxConcurrency(dataFeedIngestionSettings.getDataSourceRequestConcurrency())
.setStopRetryAfterInSeconds(dataFeedIngestionSettings.getStopRetryAfter() == null
? null : dataFeedIngestionSettings.getStopRetryAfter().getSeconds())
.setMinRetryIntervalInSeconds(dataFeedIngestionSettings.getIngestionRetryDelay() == null
? null : dataFeedIngestionSettings.getIngestionRetryDelay().getSeconds())
.setRollUpColumns(dataFeedRollupSettings.getAutoRollupGroupByColumnNames())
.setRollUpMethod(RollUpMethod.fromString(dataFeedRollupSettings
.getDataFeedAutoRollUpMethod() == null
? null : dataFeedRollupSettings.getDataFeedAutoRollUpMethod().toString()))
.setNeedRollup(NeedRollupEnum.fromString(dataFeedRollupSettings.getRollupType() == null
? null : dataFeedRollupSettings.getRollupType().toString()))
.setAllUpIdentification(dataFeedRollupSettings.getRollupIdentificationValue())
.setFillMissingPointType(FillMissingPointType.fromString(
dataFeedMissingDataPointFillSettings.getFillType() == null
? null : dataFeedMissingDataPointFillSettings.getFillType().toString()))
.setFillMissingPointValue(dataFeedMissingDataPointFillSettings.getCustomFillValue())
.setViewMode(ViewMode.fromString(finalDataFeedOptions.getAccessMode() == null
? null : finalDataFeedOptions.getAccessMode().toString()))
.setViewers(finalDataFeedOptions.getViewers())
.setAdmins(finalDataFeedOptions.getAdmins())
.setActionLinkTemplate(finalDataFeedOptions.getActionLinkTemplate()), context)
.flatMap(createDataFeedResponse -> {
final String dataFeedId =
parseOperationId(createDataFeedResponse.getDeserializedHeaders().getLocation());
return getDataFeedWithResponse(dataFeedId);
});
}
/**
* Get a data feed by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeed
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeed
*
* @param dataFeedId The data feed unique id.
*
* @return The data feed for the provided id.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> getDataFeed(String dataFeedId) {
return getDataFeedWithResponse(dataFeedId).flatMap(FluxUtil::toMono);
}
/**
* Get a data feed by its id with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedWithResponse
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* DataFeed dataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedWithResponse
*
* @param dataFeedId The data feed unique id.
*
* @return The data feed for the provided id.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> getDataFeedWithResponse(String dataFeedId) {
try {
return withContext(context -> getDataFeedWithResponse(dataFeedId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> getDataFeedWithResponse(String dataFeedId, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' cannot be null.");
return service.getDataFeedByIdWithResponseAsync(UUID.fromString(dataFeedId), context)
.map(response -> new SimpleResponse<>(response, DataFeedTransforms.fromInner(response.getValue())));
}
/**
* Update an existing data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeed
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .flatMap&
* return metricsAdvisorAdminAsyncClient.updateDataFeed&
* existingDataFeed
* .setOptions&
* .setDescription&
* &
* &
* .subscribe&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeed
*
* @param dataFeed the data feed that needs to be updated.
*
* @return the updated data feed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> updateDataFeed(DataFeed dataFeed) {
return updateDataFeedWithResponse(dataFeed).flatMap(FluxUtil::toMono);
}
/**
* Update an existing data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeedWithResponse
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .flatMap&
* return metricsAdvisorAdminAsyncClient.updateDataFeedWithResponse&
* existingDataFeed
* .setOptions&
* .setDescription&
* &
* &
* .subscribe&
* System.out.printf&
* DataFeed updatedDataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeedWithResponse
*
* @param dataFeed the data feed that needs to be updated.
*
* @return the {@link Response} of a {@link Mono} containing the updated {@link DataFeed data feed}.
**/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> updateDataFeedWithResponse(DataFeed dataFeed) {
try {
return withContext(context -> updateDataFeedWithResponse(dataFeed, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> updateDataFeedWithResponse(DataFeed dataFeed, Context context) {
final DataFeedIngestionSettings dataFeedIngestionSettings = dataFeed.getIngestionSettings();
final DataFeedOptions dataFeedOptions = dataFeed.getOptions() == null
? new DataFeedOptions() : dataFeed.getOptions();
final DataFeedRollupSettings dataFeedRollupSettings = dataFeedOptions.getRollupSettings() == null
? new DataFeedRollupSettings() : dataFeedOptions.getRollupSettings();
final DataFeedMissingDataPointFillSettings dataFeedMissingDataPointFillSettings =
dataFeedOptions.getMissingDataPointFillSettings() == null
? new DataFeedMissingDataPointFillSettings() : dataFeedOptions.getMissingDataPointFillSettings();
return service.updateDataFeedWithResponseAsync(UUID.fromString(dataFeed.getId()),
DataFeedTransforms.toInnerForUpdate(dataFeed.getSource())
.setDataFeedName(dataFeed.getName())
.setDataFeedDescription(dataFeedOptions.getDescription())
.setTimestampColumn(dataFeed.getSchema() == null
? null : dataFeed.getSchema().getTimestampColumn())
.setDataStartFrom(dataFeed.getIngestionSettings().getIngestionStartTime())
.setStartOffsetInSeconds(dataFeedIngestionSettings.getIngestionStartOffset() == null
? null : dataFeedIngestionSettings.getIngestionStartOffset().getSeconds())
.setMaxConcurrency(dataFeedIngestionSettings.getDataSourceRequestConcurrency())
.setStopRetryAfterInSeconds(dataFeedIngestionSettings.getStopRetryAfter() == null
? null : dataFeedIngestionSettings.getStopRetryAfter().getSeconds())
.setMinRetryIntervalInSeconds(dataFeedIngestionSettings.getIngestionRetryDelay() == null
? null : dataFeedIngestionSettings.getIngestionRetryDelay().getSeconds())
.setNeedRollup(
dataFeedRollupSettings.getRollupType() != null
? NeedRollupEnum.fromString(dataFeedRollupSettings.getRollupType().toString())
: null)
.setRollUpColumns(dataFeedRollupSettings.getAutoRollupGroupByColumnNames())
.setRollUpMethod(
dataFeedRollupSettings.getDataFeedAutoRollUpMethod() != null
? RollUpMethod.fromString(
dataFeedRollupSettings.getDataFeedAutoRollUpMethod().toString())
: null)
.setAllUpIdentification(dataFeedRollupSettings.getRollupIdentificationValue())
.setFillMissingPointType(
dataFeedMissingDataPointFillSettings.getFillType() != null
? FillMissingPointType.fromString(
dataFeedMissingDataPointFillSettings.getFillType().toString())
: null)
.setFillMissingPointValue(
dataFeedMissingDataPointFillSettings.getFillType() == DataFeedMissingDataPointFillType.CUSTOM_VALUE
? dataFeedMissingDataPointFillSettings.getCustomFillValue()
: null)
.setViewMode(
dataFeedOptions.getAccessMode() != null
? ViewMode.fromString(dataFeedOptions.getAccessMode().toString())
: null)
.setViewers(dataFeedOptions.getViewers())
.setAdmins(dataFeedOptions.getAdmins())
.setStatus(
dataFeed.getStatus() != null
? EntityStatus.fromString(dataFeed.getStatus().toString())
: null)
.setActionLinkTemplate(dataFeedOptions.getActionLinkTemplate()), context)
.flatMap(updatedDataFeedResponse -> getDataFeedWithResponse(dataFeed.getId()));
}
/**
* Delete a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeed
* <pre>
* final String dataFeedId = "t00853f1-9080-447f-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.deleteDataFeed&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeed
*
* @param dataFeedId The data feed unique id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDataFeed(String dataFeedId) {
return deleteDataFeedWithResponse(dataFeedId).flatMap(FluxUtil::toMono);
}
/**
* Delete a data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeedWithResponse
* <pre>
* final String dataFeedId = "eh0854f1-8927-447f-bacf-8dccf2e86fwe";
* metricsAdvisorAdminAsyncClient.deleteDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeedWithResponse
*
* @param dataFeedId The data feed unique id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDataFeedWithResponse(String dataFeedId) {
try {
return withContext(context -> deleteDataFeedWithResponse(dataFeedId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteDataFeedWithResponse(String dataFeedId, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' cannot be null.");
return service.deleteDataFeedWithResponseAsync(UUID.fromString(dataFeedId), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* List information of all data feeds on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds -->
* <pre>
* metricsAdvisorAdminAsyncClient.listDataFeeds&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds -->
*
* @return A {@link PagedFlux} containing information of all the {@link DataFeed data feeds} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeed> listDataFeeds() {
return listDataFeeds(new ListDataFeedOptions());
}
/**
* List information of all data feeds on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds
* <pre>
* metricsAdvisorAdminAsyncClient.listDataFeeds&
* new ListDataFeedOptions&
* .setListDataFeedFilter&
* new ListDataFeedFilter&
* .setDataFeedStatus&
* .setDataFeedGranularityType&
* .setMaxPageSize&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds
*
* @param listDataFeedOptions The configurable {@link ListDataFeedOptions options} to pass for filtering the output result.
*
* @return A {@link PagedFlux} containing information of all the {@link DataFeed data feeds} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeed> listDataFeeds(ListDataFeedOptions listDataFeedOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listDataFeedsSinglePageAsync(listDataFeedOptions, context)),
continuationToken ->
withContext(context -> listDataFeedsNextPageAsync(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DataFeed> listDataFeeds(ListDataFeedOptions options, Context context) {
return new PagedFlux<>(() ->
listDataFeedsSinglePageAsync(options, context),
continuationToken ->
listDataFeedsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<DataFeed>> listDataFeedsSinglePageAsync(ListDataFeedOptions options, Context context) {
options = options != null ? options : new ListDataFeedOptions();
final ListDataFeedFilter dataFeedFilter =
options.getListDataFeedFilter() != null ? options.getListDataFeedFilter() : new ListDataFeedFilter();
return service.listDataFeedsSinglePageAsync(dataFeedFilter.getName(),
dataFeedFilter.getSourceType() != null
? DataSourceType.fromString(dataFeedFilter.getSourceType().toString()) : null,
dataFeedFilter.getGranularityType() != null
? Granularity.fromString(dataFeedFilter.getGranularityType().toString()) : null,
dataFeedFilter.getStatus() != null
? EntityStatus.fromString(dataFeedFilter.getStatus().toString()) : null,
dataFeedFilter.getCreator(),
options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing information for all data feeds"))
.doOnSuccess(response -> logger.info("Listed data feeds {}", response))
.doOnError(error -> logger.warning("Failed to list all data feeds information - {}", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream().map(DataFeedTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataFeed>> listDataFeedsNextPageAsync(String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listDataFeedsNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream().map(DataFeedTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
/**
* Fetch the ingestion status of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeedIngestionStatus
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* final ListDataFeedIngestionOptions options = new ListDataFeedIngestionOptions&
* metricsAdvisorAdminAsyncClient.listDataFeedIngestionStatus&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeedIngestionStatus
*
* @param dataFeedId The data feed id.
* @param listDataFeedIngestionOptions The additional parameters.
*
* @return The ingestion statuses.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code options}, {@code options.startTime},
* {@code options.endTime} is null.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeedIngestionStatus> listDataFeedIngestionStatus(
String dataFeedId,
ListDataFeedIngestionOptions listDataFeedIngestionOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listDataFeedIngestionStatusSinglePageAsync(dataFeedId, listDataFeedIngestionOptions, context)),
continuationToken ->
withContext(context -> listDataFeedIngestionStatusNextPageAsync(continuationToken,
listDataFeedIngestionOptions,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<DataFeedIngestionStatus> listDataFeedIngestionStatus(
String dataFeedId,
ListDataFeedIngestionOptions options, Context context) {
return new PagedFlux<>(() ->
listDataFeedIngestionStatusSinglePageAsync(dataFeedId, options, context),
continuationToken ->
listDataFeedIngestionStatusNextPageAsync(continuationToken,
options,
context));
}
private Mono<PagedResponse<DataFeedIngestionStatus>> listDataFeedIngestionStatusSinglePageAsync(
String dataFeedId,
ListDataFeedIngestionOptions options, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
Objects.requireNonNull(options, "'options' is required.");
Objects.requireNonNull(options.getStartTime(), "'options.startTime' is required.");
Objects.requireNonNull(options.getEndTime(), "'options.endTime' is required.");
IngestionStatusQueryOptions queryOptions = new IngestionStatusQueryOptions()
.setStartTime(options.getStartTime())
.setEndTime(options.getEndTime());
return service.getDataFeedIngestionStatusSinglePageAsync(
UUID.fromString(dataFeedId),
queryOptions,
options.getSkip(),
options.getMaxPageSize(),
context)
.doOnRequest(ignoredValue -> logger.info("Listing ingestion status for data feed"))
.doOnSuccess(response -> logger.info("Listed ingestion status {}", response))
.doOnError(error -> logger.warning("Failed to ingestion status for data feed", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
toDataFeedIngestionStatus(res.getValue()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataFeedIngestionStatus>> listDataFeedIngestionStatusNextPageAsync(
String nextPageLink,
ListDataFeedIngestionOptions options,
Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
IngestionStatusQueryOptions queryOptions = new IngestionStatusQueryOptions()
.setStartTime(options.getStartTime())
.setEndTime(options.getEndTime());
return service.getDataFeedIngestionStatusNextSinglePageAsync(nextPageLink, queryOptions, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink, response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
toDataFeedIngestionStatus(res.getValue()),
res.getContinuationToken(),
null));
}
/**
* Refresh data ingestion for a period.
* <p>
* The data in the data source for the given period will be re-ingested
* and any ingested data for the same period will be overwritten.
* </p>
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestion
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* metricsAdvisorAdminAsyncClient.refreshDataFeedIngestion&
* startTime,
* endTime&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestion
*
* @param dataFeedId The data feed id.
* @param startTime The start point of the period.
* @param endTime The end point of of the period.
*
* @return A {@link Mono} indicating ingestion reset success or failure.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code startTime}, {@code endTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> refreshDataFeedIngestion(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime) {
return refreshDataFeedIngestionWithResponse(dataFeedId,
startTime,
endTime).then();
}
/**
* Refresh data ingestion for a period.
* <p>
* The data in the data source for the given period will be re-ingested
* and any ingested data for the same period will be overwritten.
* </p>
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestionWithResponse
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* metricsAdvisorAdminAsyncClient.refreshDataFeedIngestionWithResponse&
* startTime,
* endTime&
* .subscribe&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestionWithResponse
*
* @param dataFeedId The data feed id.
* @param startTime The start point of the period.
* @param endTime The end point of of the period.
*
* @return A {@link Response} of a {@link Mono} with result of reset request.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code startTime}, {@code endTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> refreshDataFeedIngestionWithResponse(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime) {
try {
return withContext(context -> refreshDataFeedIngestionWithResponse(dataFeedId,
startTime,
endTime, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> refreshDataFeedIngestionWithResponse(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
Objects.requireNonNull(startTime, "'startTime' is required.");
Objects.requireNonNull(endTime, "'endTime' is required.");
return service.resetDataFeedIngestionStatusWithResponseAsync(UUID.fromString(dataFeedId),
new IngestionProgressResetOptions()
.setStartTime(startTime)
.setEndTime(endTime),
context)
.doOnRequest(ignoredValue -> logger.info("Resetting ingestion status for the data feed"))
.doOnSuccess(response -> logger.info("Ingestion status got reset {}", response))
.doOnError(error -> logger.warning("Failed to reset ingestion status for the data feed", error));
}
/**
* Retrieve the ingestion progress of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgress
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* metricsAdvisorAdminAsyncClient.getDataFeedIngestionProgress&
* .subscribe&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgress
*
* @param dataFeedId The data feed id.
*
* @return A {@link Mono} containing {@link DataFeedIngestionProgress} of the data feed.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeedIngestionProgress> getDataFeedIngestionProgress(String dataFeedId) {
return getDataFeedIngestionProgressWithResponse(dataFeedId, Context.NONE)
.map(Response::getValue);
}
/**
* Retrieve the ingestion progress of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgressWithResponse
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* metricsAdvisorAdminAsyncClient.getDataFeedIngestionProgressWithResponse&
* .subscribe&
* System.out.printf&
* DataFeedIngestionProgress ingestionProgress = response.getValue&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgressWithResponse
*
* @param dataFeedId The data feed id.
*
* @return A {@link Response} of a {@link Mono} containing {@link DataFeedIngestionProgress} of the data feed.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeedIngestionProgress>> getDataFeedIngestionProgressWithResponse(String dataFeedId) {
try {
return withContext(context -> getDataFeedIngestionProgressWithResponse(dataFeedId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataFeedIngestionProgress>> getDataFeedIngestionProgressWithResponse(String dataFeedId,
Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
return service.getIngestionProgressWithResponseAsync(UUID.fromString(dataFeedId), context)
.doOnRequest(ignoredValue -> logger.info("Retrieving ingestion progress for metric"))
.doOnSuccess(response -> logger.info("Retrieved ingestion progress {}", response))
.doOnError(error -> logger.warning("Failed to retrieve ingestion progress for metric", error))
.map(response -> new SimpleResponse<>(response, toDataFeedIngestionProgress(response.getValue())));
}
private DataFeedIngestionProgress toDataFeedIngestionProgress(
com.azure.ai.metricsadvisor.implementation.models.DataFeedIngestionProgress dataFeedIngestionProgressResponse) {
DataFeedIngestionProgress dataFeedIngestionProgress = new DataFeedIngestionProgress();
DataFeedIngestionProgressHelper.setLatestActiveTimestamp(dataFeedIngestionProgress, dataFeedIngestionProgressResponse.getLatestActiveTimestamp());
DataFeedIngestionProgressHelper.setLatestSuccessTimestamp(dataFeedIngestionProgress, dataFeedIngestionProgressResponse.getLatestSuccessTimestamp());
return dataFeedIngestionProgress;
}
/**
* Create a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfig
* <pre>
* final MetricWholeSeriesDetectionCondition wholeSeriesCondition = new MetricWholeSeriesDetectionCondition&
* .setConditionOperator&
* .setSmartDetectionCondition&
* 50,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setHardThresholdCondition&
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setLowerBound&
* .setUpperBound&
* .setChangeThresholdCondition&
* 50,
* 30,
* true,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
*
* final String detectionConfigName = "my_detection_config";
* final String detectionConfigDescription = "anomaly detection config for metric";
* final AnomalyDetectionConfiguration detectionConfig
* = new AnomalyDetectionConfiguration&
* .setDescription&
* .setWholeSeriesDetectionCondition&
*
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient
* .createDetectionConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfig
*
* @param metricId The metric id to associate the configuration with.
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Mono} containing the created {@link AnomalyDetectionConfiguration}.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID
* format specification, or {@code detectionConfiguration.name} is not set.
* @throws NullPointerException thrown if the {@code metricId} is null
* or {@code detectionConfiguration} is null
* or {@code detectionConfiguration.wholeSeriesCondition} is null
* or {@code seriesKey} is missing for any {@code MetricSingleSeriesDetectionCondition} in the configuration
* or {@code seriesGroupKey} is missing for any {@code MetricSeriesGroupDetectionCondition} in the configuration
* or {@code conditionOperator} is missing when multiple nested conditions are set in a
* {@code MetricSingleSeriesDetectionCondition} or {@code MetricSeriesGroupDetectionCondition}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> createDetectionConfig(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration) {
return createDetectionConfigWithResponse(metricId, detectionConfiguration)
.map(Response::getValue);
}
/**
* Create a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfigWithResponse
* <pre>
* final MetricWholeSeriesDetectionCondition wholeSeriesCondition = new MetricWholeSeriesDetectionCondition&
* .setConditionOperator&
* .setSmartDetectionCondition&
* 50,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setHardThresholdCondition&
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setLowerBound&
* .setUpperBound&
* .setChangeThresholdCondition&
* 50,
* 30,
* true,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
*
* final String detectionConfigName = "my_detection_config";
* final String detectionConfigDescription = "anomaly detection config for metric";
* final AnomalyDetectionConfiguration detectionConfig
* = new AnomalyDetectionConfiguration&
* .setDescription&
* .setWholeSeriesDetectionCondition&
*
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient
* .createDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
* AnomalyDetectionConfiguration createdDetectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfigWithResponse
*
* @param metricId The metric id to associate the configuration with.
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Response} of a {@link Mono} containing the created {@link AnomalyDetectionConfiguration}.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID
* format specification, or {@code detectionConfiguration.name} is not set.
* @throws NullPointerException thrown if the {@code metricId} is null
* or {@code detectionConfiguration} is null
* or {@code detectionConfiguration.wholeSeriesCondition} is null
* or {@code seriesKey} is missing for any {@code MetricSingleSeriesDetectionCondition} in the configuration
* or {@code seriesGroupKey} is missing for any {@code MetricSeriesGroupDetectionCondition} in the configuration
* or {@code conditionOperator} is missing when multiple nested conditions are set in a
* {@code MetricSingleSeriesDetectionCondition} or {@code MetricSeriesGroupDetectionCondition}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> createDetectionConfigWithResponse(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration) {
try {
return withContext(context -> createDetectionConfigWithResponse(metricId,
detectionConfiguration,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> createDetectionConfigWithResponse(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration,
Context context) {
Objects.requireNonNull(metricId, "metricId is required");
Objects.requireNonNull(detectionConfiguration, "detectionConfiguration is required");
final com.azure.ai.metricsadvisor.implementation.models.AnomalyDetectionConfiguration
innerDetectionConfiguration = DetectionConfigurationTransforms.toInnerForCreate(logger,
metricId,
detectionConfiguration);
return service.createAnomalyDetectionConfigurationWithResponseAsync(innerDetectionConfiguration, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating AnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Created AnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to create AnomalyDetectionConfiguration", error))
.flatMap(response -> {
final String configurationId
= Utility.parseOperationId(response.getDeserializedHeaders().getLocation());
return getDetectionConfigWithResponse(configurationId, context)
.map(configurationResponse -> new ResponseBase<Void, AnomalyDetectionConfiguration>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Get the anomaly detection configuration by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
*
* System.out.printf&
*
* System.out.printf&
* MetricWholeSeriesDetectionCondition wholeSeriesDetectionCondition
* = detectionConfig.getWholeSeriesDetectionCondition&
*
* System.out.printf&
* wholeSeriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
*
* List<MetricSingleSeriesDetectionCondition> seriesDetectionConditions
* = detectionConfig.getSeriesDetectionConditions&
* System.out.printf&
* for &
* DimensionKey seriesKey = seriesDetectionCondition.getSeriesKey&
* final String seriesKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
*
* List<MetricSeriesGroupDetectionCondition> seriesGroupDetectionConditions
* = detectionConfig.getSeriesGroupDetectionConditions&
* System.out.printf&
* for &
* : seriesGroupDetectionConditions&
* DimensionKey seriesGroupKey = seriesGroupDetectionCondition.getSeriesGroupKey&
* final String seriesGroupKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfig
*
* @param detectionConfigurationId The anomaly detection configuration id.
* @return A {@link Mono} containing the {@link AnomalyDetectionConfiguration} for the provided id.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> getDetectionConfig(
String detectionConfigurationId) {
return getDetectionConfigWithResponse(detectionConfigurationId)
.map(Response::getValue);
}
/**
* Get the anomaly detection configuration by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
*
* AnomalyDetectionConfiguration detectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
*
* System.out.printf&
*
* System.out.printf&
* MetricWholeSeriesDetectionCondition wholeSeriesDetectionCondition
* = detectionConfig.getWholeSeriesDetectionCondition&
*
* System.out.printf&
* wholeSeriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
*
* List<MetricSingleSeriesDetectionCondition> seriesDetectionConditions
* = detectionConfig.getSeriesDetectionConditions&
* System.out.printf&
* for &
* DimensionKey seriesKey = seriesDetectionCondition.getSeriesKey&
* final String seriesKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
*
* List<MetricSeriesGroupDetectionCondition> seriesGroupDetectionConditions
* = detectionConfig.getSeriesGroupDetectionConditions&
* System.out.printf&
* for &
* : seriesGroupDetectionConditions&
* DimensionKey seriesGroupKey = seriesGroupDetectionCondition.getSeriesGroupKey&
* final String seriesGroupKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfigWithResponse
*
* @param detectionConfigurationId The anomaly detection configuration id.
* @return A {@link Response} of a {@link Mono} containing the {@link AnomalyDetectionConfiguration}
* for the provided id.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> getDetectionConfigWithResponse(
String detectionConfigurationId) {
try {
return withContext(context -> getDetectionConfigWithResponse(detectionConfigurationId,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> getDetectionConfigWithResponse(
String detectionConfigurationId, Context context) {
Objects.requireNonNull(detectionConfigurationId, "detectionConfigurationId is required.");
return service.getAnomalyDetectionConfigurationWithResponseAsync(UUID.fromString(detectionConfigurationId), context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving AnomalyDetectionConfiguration - {}",
detectionConfigurationId))
.doOnSuccess(response -> logger.info("Retrieved AnomalyDetectionConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to retrieve AnomalyDetectionConfiguration - {}",
detectionConfigurationId, error))
.map(response -> {
AnomalyDetectionConfiguration configuration
= DetectionConfigurationTransforms.fromInner(response.getValue());
return new ResponseBase<Void, AnomalyDetectionConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configuration,
null);
});
}
/**
* Update a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfig&
* .flatMap&
* detectionConfig.setName&
* detectionConfig.setDescription&
*
* DimensionKey seriesGroupKey = new DimensionKey&
* .put&
* detectionConfig.addSeriesGroupDetectionCondition&
* new MetricSeriesGroupDetectionCondition&
* .setSmartDetectionCondition&
* 10.0,
* AnomalyDetectorDirection.UP,
* new SuppressCondition&
* return metricsAdvisorAdminAsyncClient
* .updateDetectionConfig&
* &
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfig
*
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Mono} containing the updated {@link AnomalyDetectionConfiguration}.
* @throws NullPointerException thrown if the {@code detectionConfiguration} is null
* or {@code detectionConfiguration.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> updateDetectionConfig(
AnomalyDetectionConfiguration detectionConfiguration) {
return updateDetectionConfigWithResponse(detectionConfiguration)
.map(Response::getValue);
}
/**
* Update a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfigWithResponse&
* .flatMap&
* AnomalyDetectionConfiguration detectionConfig = response.getValue&
* detectionConfig.setName&
* detectionConfig.setDescription&
* DimensionKey seriesGroupKey = new DimensionKey&
* .put&
* detectionConfig.addSeriesGroupDetectionCondition&
* new MetricSeriesGroupDetectionCondition&
* .setSmartDetectionCondition&
* 10.0,
* AnomalyDetectorDirection.UP,
* new SuppressCondition&
* return metricsAdvisorAdminAsyncClient
* .updateDetectionConfigWithResponse&
* &
* .subscribe&
* AnomalyDetectionConfiguration updatedDetectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfigWithResponse
*
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Response} of a {@link Mono} containing the updated {@link AnomalyDetectionConfiguration}.
* @throws NullPointerException thrown if the {@code detectionConfiguration} is null
* or {@code detectionConfiguration.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> updateDetectionConfigWithResponse(
AnomalyDetectionConfiguration detectionConfiguration) {
try {
return withContext(context -> updateDetectionConfigWithResponse(detectionConfiguration,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> updateDetectionConfigWithResponse(
AnomalyDetectionConfiguration detectionConfiguration,
Context context) {
Objects.requireNonNull(detectionConfiguration, "detectionConfiguration is required");
Objects.requireNonNull(detectionConfiguration.getId(), "detectionConfiguration.id is required");
final AnomalyDetectionConfigurationPatch innerDetectionConfigurationPatch
= DetectionConfigurationTransforms.toInnerForUpdate(logger, detectionConfiguration);
return service.updateAnomalyDetectionConfigurationWithResponseAsync(
UUID.fromString(detectionConfiguration.getId()),
innerDetectionConfigurationPatch,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating AnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Updated AnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to update AnomalyDetectionConfiguration", error))
.flatMap(response -> {
return getDetectionConfigWithResponse(detectionConfiguration.getId(), context)
.map(configurationResponse -> new ResponseBase<Void, AnomalyDetectionConfiguration>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Delete a metric anomaly detection configuration.
*
* @param detectionConfigurationId The metric anomaly detection configuration unique id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .deleteDetectionConfig&
* .subscribe&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfig
*
* @return An empty Mono.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDetectionConfig(String detectionConfigurationId) {
return deleteDetectionConfigWithResponse(detectionConfigurationId).then();
}
/**
* Delete a metric anomaly detection configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .deleteDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfigWithResponse
*
* @param detectionConfigurationId The metric anomaly detection configuration unique id.
*
* @return A {@link Response} of a {@link Mono}.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDetectionConfigWithResponse(
String detectionConfigurationId) {
try {
return withContext(context -> deleteDetectionConfigWithResponse(
detectionConfigurationId,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> deleteDetectionConfigWithResponse(String detectionConfigurationId,
Context context) {
Objects.requireNonNull(detectionConfigurationId, "detectionConfigurationId is required.");
return service.deleteHookWithResponseAsync(UUID.fromString(detectionConfigurationId), context)
.doOnRequest(ignoredValue -> logger.info("Deleting MetricAnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Deleted MetricAnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to delete MetricAnomalyDetectionConfiguration", error));
}
/**
* Given a metric id, retrieve all anomaly detection configurations applied to it.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
* <pre>
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient.listDetectionConfigs&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
*
* @param metricId The metric id.
* @return The anomaly detection configurations.
* @throws NullPointerException thrown if the {@code metricId} is null.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId) {
return listDetectionConfigs(metricId, null);
}
/**
* Given a metric id, retrieve all anomaly detection configurations applied to it.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
* <pre>
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient.listDetectionConfigs&
* new ListDetectionConfigsOptions&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
*
* @param metricId The metric id.
* @param listDetectionConfigsOptions the additional configurable options to specify when querying the result.
* @return The anomaly detection configurations.
* @throws NullPointerException thrown if the {@code metricId} is null.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId,
ListDetectionConfigsOptions listDetectionConfigsOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listAnomalyDetectionConfigsSinglePageAsync(metricId, listDetectionConfigsOptions, context)),
continuationToken ->
withContext(context -> listAnomalyDetectionConfigsNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId,
ListDetectionConfigsOptions options,
Context context) {
return new PagedFlux<>(() ->
listAnomalyDetectionConfigsSinglePageAsync(metricId, options, context),
continuationToken ->
listAnomalyDetectionConfigsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<AnomalyDetectionConfiguration>> listAnomalyDetectionConfigsSinglePageAsync(
String metricId,
ListDetectionConfigsOptions options,
Context context) {
if (options == null) {
options = new ListDetectionConfigsOptions();
}
return service.getAnomalyDetectionConfigurationsByMetricSinglePageAsync(
UUID.fromString(metricId), options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing MetricAnomalyDetectionConfigs"))
.doOnSuccess(response -> logger.info("Listed MetricAnomalyDetectionConfigs {}", response))
.doOnError(error -> logger.warning("Failed to list the MetricAnomalyDetectionConfigs", error))
.map(DetectionConfigurationTransforms::fromInnerPagedResponse);
}
private Mono<PagedResponse<AnomalyDetectionConfiguration>> listAnomalyDetectionConfigsNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.getAnomalyDetectionConfigurationsByMetricNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(DetectionConfigurationTransforms::fromInnerPagedResponse);
}
/**
* Creates a notificationHook that receives anomaly incident alerts.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHook
* <pre>
* NotificationHook emailNotificationHook = new EmailNotificationHook&
* .setDescription&
* .setEmailsToAlert&
* add&
* &
* .setExternalLink&
*
* metricsAdvisorAdminAsyncClient.createHook&
* .subscribe&
* EmailNotificationHook createdEmailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* createdEmailHook.getEmailsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHook
*
* @param notificationHook The notificationHook.
*
* @return A {@link Mono} containing the created {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook}, {@code notificationHook.name},
* {@code notificationHook.endpoint} (for web notificationHook) is null.
* @throws IllegalArgumentException If at least one email not present for email notificationHook.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> createHook(NotificationHook notificationHook) {
return createHookWithResponse(notificationHook)
.map(Response::getValue);
}
/**
* Creates a notificationHook that receives anomaly incident alerts.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHookWithResponse
* <pre>
* NotificationHook emailNotificationHook = new EmailNotificationHook&
* .setDescription&
* .setEmailsToAlert&
* add&
* &
* .setExternalLink&
*
* metricsAdvisorAdminAsyncClient.createHookWithResponse&
* .subscribe&
* System.out.printf&
* EmailNotificationHook createdEmailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* createdEmailHook.getEmailsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHookWithResponse
*
* @param notificationHook The notificationHook.
*
* @return A {@link Response} of a {@link Mono} containing the created {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook}, {@code notificationHook.name},
* {@code notificationHook.endpoint} (for web notificationHook) is null.
* @throws IllegalArgumentException If at least one email not present for email notificationHook.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> createHookWithResponse(NotificationHook notificationHook) {
try {
return withContext(context -> createHookWithResponse(notificationHook, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> createHookWithResponse(NotificationHook notificationHook, Context context) {
Objects.requireNonNull(notificationHook, "'notificationHook' cannot be null.");
return service.createHookWithResponseAsync(HookTransforms.toInnerForCreate(logger, notificationHook), context)
.doOnRequest(ignoredValue -> logger.info("Creating NotificationHook"))
.doOnSuccess(response -> logger.info("Created NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to create notificationHook", error))
.flatMap(response -> {
final String hookUri = response.getDeserializedHeaders().getLocation();
final String hookId = parseOperationId(hookUri);
return getHookWithResponse(hookId, context)
.map(hookResponse -> new ResponseBase<Void, NotificationHook>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
hookResponse.getValue(),
null));
});
}
/**
* Get a hook by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHook
* <pre>
* final String hookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHook&
* .subscribe&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* emailHook.getEmailsToAlert&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHook
*
* @param hookId The hook unique id.
*
* @return A {@link Mono} containing the {@link NotificationHook} for the provided id.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code hookId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> getHook(String hookId) {
return getHookWithResponse(hookId).map(Response::getValue);
}
/**
* Get a hook by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHookWithResponse
* <pre>
* final String hookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHookWithResponse&
* .subscribe&
* System.out.printf&
* NotificationHook notificationHook = response.getValue&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHookWithResponse
*
* @param hookId The hook unique id.
*
* @return A {@link Response} of a {@link Mono} containing the {@link NotificationHook} for the provided id.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code hookId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> getHookWithResponse(String hookId) {
try {
return withContext(context -> getHookWithResponse(hookId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> getHookWithResponse(String hookId, Context context) {
Objects.requireNonNull(hookId, "hookId is required.");
return service.getHookWithResponseAsync(UUID.fromString(hookId), context)
.doOnRequest(ignoredValue -> logger.info("Retrieving NotificationHook"))
.doOnSuccess(response -> logger.info("Retrieved NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to retrieve hook", error))
.map(innerResponse -> new ResponseBase<Void, NotificationHook>(innerResponse.getRequest(),
innerResponse.getStatusCode(),
innerResponse.getHeaders(),
HookTransforms.fromInner(logger, innerResponse.getValue()),
null));
}
/**
* Update an existing notificationHook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHook
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHook&
* .flatMap&
* EmailNotificationHook emailHook = &
* List<String> emailsToUpdate = new ArrayList<>&
* emailsToUpdate.remove&
* emailsToUpdate.add&
* emailsToUpdate.add&
* emailHook.setEmailsToAlert&
* return metricsAdvisorAdminAsyncClient.updateHook&
* &
* .subscribe&
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHook
*
* @param notificationHook The notificationHook to update.
*
* @return A {@link Mono} containing the updated {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> updateHook(NotificationHook notificationHook) {
return updateHookWithResponse(notificationHook).map(Response::getValue);
}
/**
* Update an existing notification hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHookWithResponse
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHookWithResponse&
* .flatMap&
* EmailNotificationHook emailHook = &
* List<String> emailsToUpdate = new ArrayList<>&
* emailsToUpdate.remove&
* emailsToUpdate.add&
* emailsToUpdate.add&
* emailHook.setEmailsToAlert&
* return metricsAdvisorAdminAsyncClient.updateHookWithResponse&
* &
* .subscribe&
* System.out.printf&
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHookWithResponse
*
* @param notificationHook The notificationHook to update.
*
* @return A {@link Response} of a {@link Mono} containing the updated {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook.id} is null.
* @throws IllegalArgumentException If {@code notificationHook.Id} does not conform to the UUID format
* specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> updateHookWithResponse(NotificationHook notificationHook) {
try {
return withContext(context -> updateHookWithResponse(notificationHook, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> updateHookWithResponse(NotificationHook notificationHook, Context context) {
Objects.requireNonNull(notificationHook, "'notificationHook' cannot be null.");
Objects.requireNonNull(notificationHook.getId(), "'notificationHook.id' cannot be null.");
return service.updateHookWithResponseAsync(UUID.fromString(notificationHook.getId()),
HookTransforms.toInnerForUpdate(logger, notificationHook), context)
.doOnRequest(ignoredValue -> logger.info("Updating NotificationHook"))
.doOnSuccess(response -> logger.info("Updated NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to update notificationHook", error))
.flatMap(response -> getHookWithResponse(notificationHook.getId(), context)
.map(hookResponse -> new ResponseBase<Void, NotificationHook>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
hookResponse.getValue(),
null)));
}
/**
* Delete a hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHook
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.deleteHook&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHook
*
* @param hookId The hook unique id.
*
* @return An empty Mono.
* @throws NullPointerException thrown if the {@code hookId} is null.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteHook(String hookId) {
return deleteHookWithResponse(hookId).then();
}
/**
* Delete a hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHookWithResponse
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.deleteHookWithResponse&
* .subscribe&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHookWithResponse
*
* @param hookId The hook unique id.
*
* @return A {@link Response} of a {@link Mono}.
* @throws NullPointerException thrown if the {@code hookId} is null.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteHookWithResponse(String hookId) {
try {
return withContext(context -> deleteHookWithResponse(hookId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> deleteHookWithResponse(String hookId, Context context) {
Objects.requireNonNull(hookId, "hookId is required.");
return service.deleteHookWithResponseAsync(UUID.fromString(hookId), context)
.doOnRequest(ignoredValue -> logger.info("Deleting NotificationHook"))
.doOnSuccess(response -> logger.info("Deleted NotificationHook"))
.doOnError(error -> logger.warning("Failed to delete hook", error));
}
/**
* List information of hooks on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks -->
* <pre>
* metricsAdvisorAdminAsyncClient.listHooks&
* .subscribe&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks -->
*
* @return A {@link PagedFlux} containing information of all the {@link NotificationHook} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<NotificationHook> listHooks() {
return listHooks(new ListHookOptions());
}
/**
* List information of hooks.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks
* <pre>
* ListHookOptions options = new ListHookOptions&
* .setSkip&
* .setMaxPageSize&
* int[] pageCount = new int[1];
* metricsAdvisorAdminAsyncClient.listHooks&
* .subscribe&
* System.out.printf&
* for &
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks
*
* @param listHookOptions the additional configurable options to specify when listing hooks.
*
* @return A {@link PagedFlux} containing information of the {@link NotificationHook} resources.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<NotificationHook> listHooks(ListHookOptions listHookOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listHooksSinglePageAsync(listHookOptions, context)),
continuationToken ->
withContext(context -> listHooksNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<NotificationHook> listHooks(ListHookOptions options, Context context) {
return new PagedFlux<>(() ->
listHooksSinglePageAsync(options, context),
continuationToken ->
listHooksNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<NotificationHook>> listHooksSinglePageAsync(ListHookOptions options, Context context) {
return service.listHooksSinglePageAsync(
options != null ? options.getHookNameFilter() : null,
options != null ? options.getSkip() : null,
options != null ? options.getMaxPageSize() : null,
context)
.doOnRequest(ignoredValue -> logger.info("Listing hooks"))
.doOnSuccess(response -> logger.info("Listed hooks {}", response))
.doOnError(error -> logger.warning("Failed to list the hooks", error))
.map(response -> HookTransforms.fromInnerPagedResponse(logger, response));
}
private Mono<PagedResponse<NotificationHook>> listHooksNextPageAsync(String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listHooksNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(response -> HookTransforms.fromInnerPagedResponse(logger, response));
}
/**
* Create a configuration to trigger alert when anomalies are detected.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfig
* <pre>
* String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.createAlertConfig&
* new AnomalyAlertConfiguration&
* .setDescription&
* .setMetricAlertConfigurations&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* .setAlertConditions&
* .setSeverityRangeCondition&
* .setCrossMetricsOperator&
* .setHookIdsToAlert&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfig
*
* @param alertConfiguration The anomaly alerting configuration.
*
* @return A {@link Mono} containing the created {@link AnomalyAlertConfiguration}.
* @throws NullPointerException thrown if the {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> createAlertConfig(
AnomalyAlertConfiguration alertConfiguration) {
return createAlertConfigWithResponse(alertConfiguration).flatMap(FluxUtil::toMono);
}
/**
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfigWithResponse
* <pre>
*
* String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.createAlertConfigWithResponse&
* new AnomalyAlertConfiguration&
* .setDescription&
* .setMetricAlertConfigurations&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* .setAlertConditions&
* .setSeverityRangeCondition&
* .setCrossMetricsOperator&
* .setHookIdsToAlert&
* .subscribe&
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration anomalyAlertConfiguration = alertConfigurationResponse.getValue&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfigWithResponse
*
* @param alertConfiguration The anomaly alerting configuration.
*
* @return A {@link Response} of a {@link Mono} containing the created {@link AnomalyAlertConfiguration}.
* @throws NullPointerException thrown if the {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> createAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration) {
try {
return withContext(context -> createAlertConfigWithResponse(alertConfiguration, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> createAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration, Context context) {
Objects.requireNonNull(alertConfiguration, "'alertConfiguration' is required.");
if (CoreUtils.isNullOrEmpty(alertConfiguration.getMetricAlertConfigurations())) {
Objects.requireNonNull("'alertConfiguration.metricAnomalyAlertConfigurations' is required");
}
if (alertConfiguration.getCrossMetricsOperator() == null
&& alertConfiguration.getMetricAlertConfigurations().size() > 1) {
throw logger.logExceptionAsError(new IllegalArgumentException("crossMetricsOperator is required"
+ " when there are more than one metric level alert configuration."));
}
final AnomalyAlertingConfiguration innerAlertConfiguration
= AlertConfigurationTransforms.toInnerForCreate(alertConfiguration);
return service.createAnomalyAlertingConfigurationWithResponseAsync(innerAlertConfiguration, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating AnomalyAlertConfiguration - {}",
innerAlertConfiguration))
.doOnSuccess(response -> logger.info("Created AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to create AnomalyAlertConfiguration - {}",
innerAlertConfiguration, error))
.flatMap(response -> {
final String configurationId = parseOperationId(response.getDeserializedHeaders().getLocation());
return getAlertConfigWithResponse(configurationId, context)
.map(getResponse -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
getResponse.getValue(),
null));
});
}
/**
* Get the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfig
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfig
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A {@link Mono} containing the {@link AnomalyAlertConfiguration} identified by the given id.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> getAlertConfig(
String alertConfigurationId) {
return getAlertConfigWithResponse(alertConfigurationId).flatMap(FluxUtil::toMono);
}
/**
* Get the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfigWithResponse
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfigWithResponse&
* .subscribe&
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration anomalyAlertConfiguration = alertConfigurationResponse.getValue&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfigWithResponse
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A {@link Response response} of a {@link Mono}
* containing the {@link AnomalyAlertConfiguration} identified by the given id.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> getAlertConfigWithResponse(
String alertConfigurationId) {
try {
return withContext(context -> getAlertConfigWithResponse(alertConfigurationId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> getAlertConfigWithResponse(
String alertConfigurationId, Context context) {
Objects.requireNonNull(alertConfigurationId, "'alertConfigurationId' is required.");
return service.getAnomalyAlertingConfigurationWithResponseAsync(UUID.fromString(alertConfigurationId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving AnomalyDetectionConfiguration - {}",
alertConfigurationId))
.doOnSuccess(response -> logger.info("Retrieved AnomalyDetectionConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to retrieve AnomalyDetectionConfiguration - {}",
alertConfigurationId, error))
.map(response -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(), AlertConfigurationTransforms.fromInner(response.getValue()), null));
}
/**
* Update anomaly alert configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfig
* <pre>
*
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* String additionalHookId = "2gh8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .flatMap&
* List<String> hookIds = new ArrayList<>&
* hookIds.add&
* return metricsAdvisorAdminAsyncClient.updateAlertConfig&
* existingAnomalyConfig
* .setHookIdsToAlert&
* .setDescription&
* &
* System.out.printf&
* updateAnomalyAlertConfiguration.getId&
* System.out.printf&
* updateAnomalyAlertConfiguration.getDescription&
* System.out.printf&
* updateAnomalyAlertConfiguration.getHookIdsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfig
*
* @param alertConfiguration The anomaly alert configuration to update.
*
* @return A {@link Mono} containing the {@link AnomalyAlertConfiguration} that was updated.
* @throws NullPointerException thrown if {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null or empty.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> updateAlertConfig(
AnomalyAlertConfiguration alertConfiguration) {
return updateAlertConfigWithResponse(alertConfiguration).flatMap(FluxUtil::toMono);
}
/**
* Update anomaly alert configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfigWithResponse
* <pre>
*
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* String additionalHookId = "2gh8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .flatMap&
* List<String> hookIds = new ArrayList<>&
* hookIds.add&
* return metricsAdvisorAdminAsyncClient.updateAlertConfigWithResponse&
* existingAnomalyConfig
* .setHookIdsToAlert&
* .setDescription&
* &
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration updatedAnomalyAlertConfiguration
* = alertConfigurationResponse.getValue&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getId&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getDescription&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getHookIdsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfigWithResponse
*
* @param alertConfiguration The anomaly alert configuration to update.
*
* @return A {@link Response} of a {@link Mono} containing the {@link AnomalyAlertConfiguration} that was updated.
* @throws NullPointerException thrown if {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null or empty.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> updateAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration) {
try {
return withContext(context -> updateAlertConfigWithResponse(alertConfiguration, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> updateAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration, Context context) {
Objects.requireNonNull(alertConfiguration, "'alertConfiguration' is required");
if (CoreUtils.isNullOrEmpty(alertConfiguration.getMetricAlertConfigurations())) {
throw logger.logExceptionAsError(new NullPointerException(
"'alertConfiguration.metricAnomalyAlertConfigurations' is required and cannot be empty"));
}
final AnomalyAlertingConfigurationPatch innerAlertConfiguration
= AlertConfigurationTransforms.toInnerForUpdate(alertConfiguration);
return service.updateAnomalyAlertingConfigurationWithResponseAsync(
UUID.fromString(alertConfiguration.getId()),
innerAlertConfiguration,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating AnomalyAlertConfiguration - {}",
innerAlertConfiguration))
.doOnSuccess(response -> logger.info("Updated AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to update AnomalyAlertConfiguration - {}",
innerAlertConfiguration, error))
.flatMap(response -> getAlertConfigWithResponse(alertConfiguration.getId(), context)
.map(getResponse -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
getResponse.getValue(),
null)));
}
/**
* Deletes the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfig
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* metricsAdvisorAdminAsyncClient.deleteAlertConfig&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfig
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteAlertConfig(String alertConfigurationId) {
return deleteAlertConfigWithResponse(alertConfigurationId).flatMap(FluxUtil::toMono);
}
/**
* Deletes the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfigWithResponse
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.deleteAlertConfigWithResponse&
* .subscribe&
* System.out.printf&
* response.getStatusCode&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfigWithResponse
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteAlertConfigWithResponse(String alertConfigurationId) {
try {
return withContext(context -> deleteAlertConfigWithResponse(alertConfigurationId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteAlertConfigWithResponse(String alertConfigurationId, Context context) {
Objects.requireNonNull(alertConfigurationId, "'alertConfigurationId' is required.");
return service.deleteAnomalyAlertingConfigurationWithResponseAsync(UUID.fromString(alertConfigurationId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting AnomalyAlertConfiguration - {}", alertConfigurationId))
.doOnSuccess(response -> logger.info("Deleted AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to delete AnomalyAlertConfiguration - {}",
alertConfigurationId, error));
}
/**
* Fetch the anomaly alert configurations associated with a detection configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listAlertConfigs
* <pre>
* String detectionConfigId = "3rt98er30-6e6e-4391-b78f-bpfdfee1e6f5";
* metricsAdvisorAdminAsyncClient.listAlertConfigs&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listAlertConfigs
*
* @param detectionConfigurationId The id of the detection configuration.
* @param listAnomalyAlertConfigsOptions th e additional configurable options to specify when querying the result.
*
* @return A {@link PagedFlux} containing information of all the
* {@link AnomalyAlertConfiguration anomaly alert configurations} for the specified detection configuration.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the
* UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyAlertConfiguration> listAlertConfigs(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions listAnomalyAlertConfigsOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listAnomalyAlertConfigsSinglePageAsync(detectionConfigurationId,
listAnomalyAlertConfigsOptions,
context)),
continuationToken ->
withContext(context -> listAnomalyAlertConfigsNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<AnomalyAlertConfiguration> listAlertConfigs(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions options, Context context) {
return new PagedFlux<>(() ->
listAnomalyAlertConfigsSinglePageAsync(detectionConfigurationId,
options,
context),
continuationToken ->
listAnomalyAlertConfigsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<AnomalyAlertConfiguration>> listAnomalyAlertConfigsSinglePageAsync(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions options, Context context) {
Objects.requireNonNull(detectionConfigurationId, "'detectionConfigurationId' is required.");
if (options == null) {
options = new ListAnomalyAlertConfigsOptions();
}
return service.getAnomalyAlertingConfigurationsByAnomalyDetectionConfigurationSinglePageAsync(
UUID.fromString(detectionConfigurationId), options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing AnomalyAlertConfigs"))
.doOnSuccess(response -> logger.info("Listed AnomalyAlertConfigs {}", response))
.doOnError(error -> logger.warning("Failed to list the AnomalyAlertConfigs", error))
.map(AlertConfigurationTransforms::fromInnerPagedResponse);
}
private Mono<PagedResponse<AnomalyAlertConfiguration>> listAnomalyAlertConfigsNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.getAnomalyAlertingConfigurationsByAnomalyDetectionConfigurationNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(AlertConfigurationTransforms::fromInnerPagedResponse);
}
/**
* Create a data source credential entity.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredential
* <pre>
* DataSourceCredentialEntity datasourceCredential;
* final String name = "sample_name" + UUID.randomUUID&
* final String cId = "f45668b2-bffa-11eb-8529-0246ac130003";
* final String tId = "67890ded-5e07-4e52-b225-4ae8f905afb5";
* final String mockSecret = "890hy69-5e07-4e52-b225-4ae8f905afb5";
*
* datasourceCredential = new DataSourceServicePrincipalInKeyVault&
* .setName&
* .setKeyVaultForDataSourceSecrets&
* .setTenantId&
* .setSecretNameForDataSourceClientId&
* .setSecretNameForDataSourceClientSecret&
*
* metricsAdvisorAdminAsyncClient.createDataSourceCredential&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredential
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the created {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> createDataSourceCredential(
DataSourceCredentialEntity dataSourceCredential) {
return createDataSourceCredentialWithResponse(dataSourceCredential)
.map(Response::getValue);
}
/**
* Create a data source credential entity with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredentialWithResponse
* <pre>
* DataSourceCredentialEntity datasourceCredential;
* final String name = "sample_name" + UUID.randomUUID&
* final String cId = "f45668b2-bffa-11eb-8529-0246ac130003";
* final String tId = "67890ded-5e07-4e52-b225-4ae8f905afb5";
* final String mockSecret = "890hy69-5e07-4e52-b225-4ae8f905afb5";
*
* datasourceCredential = new DataSourceServicePrincipalInKeyVault&
* .setName&
* .setKeyVaultForDataSourceSecrets&
* .setTenantId&
* .setSecretNameForDataSourceClientId&
* .setSecretNameForDataSourceClientSecret&
*
* metricsAdvisorAdminAsyncClient.createDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredentialWithResponse
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the created {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> createDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential) {
try {
return withContext(context -> createDataSourceCredentialWithResponse(dataSourceCredential,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataSourceCredentialEntity>> createDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential,
Context context) {
Objects.requireNonNull(dataSourceCredential, "dataSourceCredential is required");
final DataSourceCredential
innerDataSourceCredential = DataSourceCredentialEntityTransforms.toInnerForCreate(dataSourceCredential);
return service.createCredentialWithResponseAsync(innerDataSourceCredential, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating DataSourceCredentialEntity"))
.doOnSuccess(response -> logger.info("Created DataSourceCredentialEntity"))
.doOnError(error -> logger.warning("Failed to create DataSourceCredentialEntity", error))
.flatMap(response -> {
final String credentialId
= Utility.parseOperationId(response.getDeserializedHeaders().getLocation());
return this.getDataSourceCredentialWithResponse(credentialId, context)
.map(configurationResponse -> new ResponseBase<Void, DataSourceCredentialEntity>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Update a data source credential entity.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredential
* <pre>
* String credentialId = "";
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .flatMap&
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV = null;
* if &
* actualCredentialSPInKV = &
* &
* return metricsAdvisorAdminAsyncClient.updateDataSourceCredential&
* actualCredentialSPInKV.setDescription&
* &
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getDescription&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredential
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the updated {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> updateDataSourceCredential(
DataSourceCredentialEntity dataSourceCredential) {
return updateDataSourceCredentialWithResponse(dataSourceCredential)
.map(Response::getValue);
}
/**
* Update a data source credential entity with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredentialWithResponse
* <pre>
* String credentialId = "";
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .flatMap&
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV = null;
* if &
* actualCredentialSPInKV = &
* &
* return metricsAdvisorAdminAsyncClient.updateDataSourceCredentialWithResponse&
* actualCredentialSPInKV.setDescription&
* &
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getDescription&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredentialWithResponse
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the updated {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> updateDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential) {
try {
return withContext(context -> updateDataSourceCredentialWithResponse(dataSourceCredential,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataSourceCredentialEntity>> updateDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential,
Context context) {
Objects.requireNonNull(dataSourceCredential, "dataSourceCredential is required");
final DataSourceCredentialPatch
innerDataSourceCredential = DataSourceCredentialEntityTransforms.toInnerForUpdate(dataSourceCredential);
return service.updateCredentialWithResponseAsync(UUID.fromString(dataSourceCredential.getId()),
innerDataSourceCredential,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating DataSourceCredentialEntity"))
.doOnSuccess(response -> logger.info("Updated DataSourceCredentialEntity"))
.doOnError(error -> logger.warning("Failed to update DataSourceCredentialEntity", error))
.flatMap(response -> {
return this.getDataSourceCredentialWithResponse(dataSourceCredential.getId(), context)
.map(configurationResponse -> new ResponseBase<Void, DataSourceCredentialEntity>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Get a data source credential entity by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredential
* <pre>
* final String datasourceCredentialId = "f45668b2-bffa-11eb-8529-0246ac130003";
*
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredential
*
* @param credentialId The data source credential entity unique id.
*
* @return The data source credential entity for the provided id.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> getDataSourceCredential(String credentialId) {
return getDataSourceCredentialWithResponse(credentialId).flatMap(FluxUtil::toMono);
}
/**
* Get a data source credential entity by its id with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredentialWithResponse
* <pre>
* final String datasourceCredentialId = "f45668b2-bffa-11eb-8529-0246ac130003";
*
* metricsAdvisorAdminAsyncClient.getDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredentialWithResponse
*
* @param credentialId The data source credential entity unique id.
*
* @return The data source credential entity for the provided id.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> getDataSourceCredentialWithResponse(
String credentialId) {
try {
return withContext(context -> getDataSourceCredentialWithResponse(credentialId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataSourceCredentialEntity>> getDataSourceCredentialWithResponse(String credentialId,
Context context) {
Objects.requireNonNull(credentialId, "'credentialId' cannot be null.");
return service.getCredentialWithResponseAsync(UUID.fromString(credentialId), context)
.map(response -> new SimpleResponse<>(response,
DataSourceCredentialEntityTransforms.fromInner(response.getValue())));
}
/**
* Deletes the data source credential entity identified by {@code credentialId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredential
* <pre>
* final String datasourceCredentialId = "t00853f1-9080-447f-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.deleteDataFeed&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredential
*
* @param credentialId The data source credential entity id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDataSourceCredential(String credentialId) {
return deleteDataSourceCredentialWithResponse(credentialId).flatMap(FluxUtil::toMono);
}
/**
* Deletes the data source credential entity identified by {@code credentialId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredentialWithResponse
* <pre>
* final String datasourceCredentialId = "eh0854f1-8927-447f-bacf-8dccf2e86fwe";
* metricsAdvisorAdminAsyncClient.deleteDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredentialWithResponse
*
* @param credentialId The data source credential entity id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDataSourceCredentialWithResponse(String credentialId) {
try {
return withContext(context -> deleteDataSourceCredentialWithResponse(credentialId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteDataSourceCredentialWithResponse(String credentialId, Context context) {
Objects.requireNonNull(credentialId, "'credentialId' is required.");
return service.deleteCredentialWithResponseAsync(UUID.fromString(credentialId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting deleteDataSourceCredentialEntity - {}",
credentialId))
.doOnSuccess(response -> logger.info("Deleted deleteDataSourceCredentialEntity - {}", response))
.doOnError(error -> logger.warning("Failed to delete deleteDataSourceCredentialEntity - {}",
credentialId, error));
}
/**
* List information of all data source credential entities on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials -->
* <pre>
* metricsAdvisorAdminAsyncClient.listDataSourceCredentials&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials -->
*
* @return A {@link PagedFlux} containing information of all the {@link DataSourceCredentialEntity data feeds}
* in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials() {
return listDataSourceCredentials(new ListCredentialEntityOptions());
}
/**
* List information of all data source credential entities on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials
* <pre>
* metricsAdvisorAdminAsyncClient.listDataSourceCredentials&
* new ListCredentialEntityOptions&
* .setMaxPageSize&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials
*
* @param listCredentialEntityOptions The configurable {@link ListCredentialEntityOptions options} to pass for filtering
* the output result.
*
* @return A {@link PagedFlux} containing information of all the {@link DataSourceCredentialEntity data feeds}
* in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials(ListCredentialEntityOptions listCredentialEntityOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listCredentialEntitiesSinglePageAsync(listCredentialEntityOptions, context)),
continuationToken ->
withContext(context -> listCredentialEntitiesSNextPageAsync(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials(ListCredentialEntityOptions options,
Context context) {
return new PagedFlux<>(() ->
listCredentialEntitiesSinglePageAsync(options, context),
continuationToken ->
listCredentialEntitiesSNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<DataSourceCredentialEntity>> listCredentialEntitiesSinglePageAsync(
ListCredentialEntityOptions options, Context context) {
options = options != null ? options : new ListCredentialEntityOptions();
return service.listCredentialsSinglePageAsync(options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing information for all data source credentials"))
.doOnSuccess(response -> logger.info("Listed data source credentials {}", response))
.doOnError(error -> logger.warning("Failed to list all data source credential information - {}", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream()
.map(DataSourceCredentialEntityTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataSourceCredentialEntity>> listCredentialEntitiesSNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listCredentialsNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream()
.map(DataSourceCredentialEntityTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
} | class MetricsAdvisorAdministrationAsyncClient {
private final ClientLogger logger = new ClientLogger(MetricsAdvisorAdministrationAsyncClient.class);
private final MetricsAdvisorImpl service;
/**
* Create a {@link MetricsAdvisorAdministrationAsyncClient} that sends requests to the Metrics Advisor
* service's endpoint. Each service call goes through the
* {@link MetricsAdvisorAdministrationClientBuilder
*
* @param service The proxy service used to perform REST calls.
* @param serviceVersion The versions of Azure Metrics Advisor supported by this client library.
*/
MetricsAdvisorAdministrationAsyncClient(MetricsAdvisorImpl service,
MetricsAdvisorServiceVersion serviceVersion) {
this.service = service;
}
/**
* Create a new data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeed
* <pre>
* DataFeed dataFeed = new DataFeed&
* .setName&
* .setSource&
* .setGranularity&
* .setSchema&
* Arrays.asList&
* new DataFeedMetric&
* new DataFeedMetric&
* &
* Arrays.asList&
* new DataFeedDimension&
* new DataFeedDimension&
* &
* &
* .setIngestionSettings&
* .setOptions&
* .setDescription&
* .setRollupSettings&
* .setRollupType&
*
* metricsAdvisorAdminAsyncClient.createDataFeed&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeed
*
* @param dataFeed The data feed to be created.
* @return A {@link Mono} containing the created data feed.
* @throws NullPointerException If {@code dataFeed}, {@code dataFeedName}, {@code dataFeedSource}, {@code metrics},
* {@code granularityType} or {@code ingestionStartTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> createDataFeed(DataFeed dataFeed) {
return createDataFeedWithResponse(dataFeed).flatMap(FluxUtil::toMono);
}
/**
* Create a new data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeedWithResponse
* <pre>
* DataFeed dataFeed = new DataFeed&
* .setName&
* .setSource&
* .setGranularity&
* .setSchema&
* Arrays.asList&
* new DataFeedMetric&
* new DataFeedMetric&
* &
* &
* .setIngestionSettings&
* .setOptions&
* .setDescription&
* .setRollupSettings&
* .setRollupType&
*
* metricsAdvisorAdminAsyncClient.createDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* DataFeed createdDataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataFeedWithResponse
* @param dataFeed The data feed to be created.
* @return A {@link Response} of a {@link Mono} containing the created {@link DataFeed data feed}.
* @throws NullPointerException If {@code dataFeed}, {@code dataFeedName}, {@code dataFeedSource}, {@code metrics},
* {@code granularityType} or {@code ingestionStartTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> createDataFeedWithResponse(DataFeed dataFeed) {
try {
return withContext(context -> createDataFeedWithResponse(dataFeed, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> createDataFeedWithResponse(DataFeed dataFeed, Context context) {
Objects.requireNonNull(dataFeed, "'dataFeed' is required and cannot be null.");
Objects.requireNonNull(dataFeed.getSource(), "'dataFeedSource' is required and cannot be null.");
Objects.requireNonNull(dataFeed.getName(), "'dataFeedName' cannot be null or empty.");
final DataFeedSchema dataFeedSchema = dataFeed.getSchema();
final DataFeedGranularity dataFeedGranularity = dataFeed.getGranularity();
final DataFeedIngestionSettings dataFeedIngestionSettings = dataFeed.getIngestionSettings();
if (dataFeedSchema == null) {
throw logger.logExceptionAsError(
new NullPointerException("'dataFeedSchema.metrics' cannot be null or empty."));
} else {
Objects.requireNonNull(dataFeedSchema.getMetrics(),
"'dataFeedSchema.metrics' cannot be null or empty.");
}
if (dataFeedGranularity == null) {
throw logger.logExceptionAsError(
new NullPointerException("'dataFeedGranularity.granularityType' is required and cannot be null."));
} else {
Objects.requireNonNull(dataFeedGranularity.getGranularityType(),
"'dataFeedGranularity.granularityType' is required.");
if (CUSTOM.equals(dataFeedGranularity.getGranularityType())) {
Objects.requireNonNull(dataFeedGranularity.getCustomGranularityValue(),
"'dataFeedGranularity.customGranularityValue' is required when granularity type is CUSTOM");
}
}
if (dataFeedIngestionSettings == null) {
throw logger.logExceptionAsError(
new NullPointerException(
"'dataFeedIngestionSettings.ingestionStartTime' is required and cannot be null."));
} else {
Objects.requireNonNull(dataFeedIngestionSettings.getIngestionStartTime(),
"'dataFeedIngestionSettings.ingestionStartTime' is required and cannot be null.");
}
final DataFeedOptions finalDataFeedOptions = dataFeed.getOptions() == null
? new DataFeedOptions() : dataFeed.getOptions();
final DataFeedRollupSettings dataFeedRollupSettings = finalDataFeedOptions.getRollupSettings() == null
? new DataFeedRollupSettings() : finalDataFeedOptions.getRollupSettings();
final DataFeedMissingDataPointFillSettings dataFeedMissingDataPointFillSettings =
finalDataFeedOptions.getMissingDataPointFillSettings() == null
? new DataFeedMissingDataPointFillSettings() : finalDataFeedOptions.getMissingDataPointFillSettings();
return service.createDataFeedWithResponseAsync(DataFeedTransforms.toDataFeedDetailSource(dataFeed.getSource())
.setDataFeedName(dataFeed.getName())
.setDataFeedDescription(finalDataFeedOptions.getDescription())
.setGranularityName(Granularity.fromString(dataFeedGranularity.getGranularityType() == null
? null : dataFeedGranularity.getGranularityType().toString()))
.setGranularityAmount(dataFeedGranularity.getCustomGranularityValue())
.setDimension(DataFeedTransforms.toInnerDimensionsListForCreate(dataFeedSchema.getDimensions()))
.setMetrics(DataFeedTransforms.toInnerMetricsListForCreate(dataFeedSchema.getMetrics()))
.setTimestampColumn(dataFeedSchema.getTimestampColumn())
.setDataStartFrom(dataFeedIngestionSettings.getIngestionStartTime())
.setStartOffsetInSeconds(dataFeedIngestionSettings.getIngestionStartOffset() == null
? null : dataFeedIngestionSettings.getIngestionStartOffset().getSeconds())
.setMaxConcurrency(dataFeedIngestionSettings.getDataSourceRequestConcurrency())
.setStopRetryAfterInSeconds(dataFeedIngestionSettings.getStopRetryAfter() == null
? null : dataFeedIngestionSettings.getStopRetryAfter().getSeconds())
.setMinRetryIntervalInSeconds(dataFeedIngestionSettings.getIngestionRetryDelay() == null
? null : dataFeedIngestionSettings.getIngestionRetryDelay().getSeconds())
.setRollUpColumns(dataFeedRollupSettings.getAutoRollupGroupByColumnNames())
.setRollUpMethod(RollUpMethod.fromString(dataFeedRollupSettings
.getDataFeedAutoRollUpMethod() == null
? null : dataFeedRollupSettings.getDataFeedAutoRollUpMethod().toString()))
.setNeedRollup(NeedRollupEnum.fromString(dataFeedRollupSettings.getRollupType() == null
? null : dataFeedRollupSettings.getRollupType().toString()))
.setAllUpIdentification(dataFeedRollupSettings.getRollupIdentificationValue())
.setFillMissingPointType(FillMissingPointType.fromString(
dataFeedMissingDataPointFillSettings.getFillType() == null
? null : dataFeedMissingDataPointFillSettings.getFillType().toString()))
.setFillMissingPointValue(dataFeedMissingDataPointFillSettings.getCustomFillValue())
.setViewMode(ViewMode.fromString(finalDataFeedOptions.getAccessMode() == null
? null : finalDataFeedOptions.getAccessMode().toString()))
.setViewers(finalDataFeedOptions.getViewers())
.setAdmins(finalDataFeedOptions.getAdmins())
.setActionLinkTemplate(finalDataFeedOptions.getActionLinkTemplate()), context)
.flatMap(createDataFeedResponse -> {
final String dataFeedId =
parseOperationId(createDataFeedResponse.getDeserializedHeaders().getLocation());
return getDataFeedWithResponse(dataFeedId);
});
}
/**
* Get a data feed by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeed
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeed
*
* @param dataFeedId The data feed unique id.
*
* @return The data feed for the provided id.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> getDataFeed(String dataFeedId) {
return getDataFeedWithResponse(dataFeedId).flatMap(FluxUtil::toMono);
}
/**
* Get a data feed by its id with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedWithResponse
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* DataFeed dataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedWithResponse
*
* @param dataFeedId The data feed unique id.
*
* @return The data feed for the provided id.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> getDataFeedWithResponse(String dataFeedId) {
try {
return withContext(context -> getDataFeedWithResponse(dataFeedId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> getDataFeedWithResponse(String dataFeedId, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' cannot be null.");
return service.getDataFeedByIdWithResponseAsync(UUID.fromString(dataFeedId), context)
.map(response -> new SimpleResponse<>(response, DataFeedTransforms.fromInner(response.getValue())));
}
/**
* Update an existing data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeed
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .flatMap&
* return metricsAdvisorAdminAsyncClient.updateDataFeed&
* existingDataFeed
* .setOptions&
* .setDescription&
* &
* &
* .subscribe&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeed
*
* @param dataFeed the data feed that needs to be updated.
*
* @return the updated data feed.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeed> updateDataFeed(DataFeed dataFeed) {
return updateDataFeedWithResponse(dataFeed).flatMap(FluxUtil::toMono);
}
/**
* Update an existing data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeedWithResponse
* <pre>
* final String dataFeedId = "r47053f1-9080-09lo-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.getDataFeed&
* .flatMap&
* return metricsAdvisorAdminAsyncClient.updateDataFeedWithResponse&
* existingDataFeed
* .setOptions&
* .setDescription&
* &
* &
* .subscribe&
* System.out.printf&
* DataFeed updatedDataFeed = dataFeedResponse.getValue&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataFeedWithResponse
*
* @param dataFeed the data feed that needs to be updated.
*
* @return the {@link Response} of a {@link Mono} containing the updated {@link DataFeed data feed}.
**/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeed>> updateDataFeedWithResponse(DataFeed dataFeed) {
try {
return withContext(context -> updateDataFeedWithResponse(dataFeed, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataFeed>> updateDataFeedWithResponse(DataFeed dataFeed, Context context) {
final DataFeedIngestionSettings dataFeedIngestionSettings = dataFeed.getIngestionSettings();
final DataFeedOptions dataFeedOptions = dataFeed.getOptions() == null
? new DataFeedOptions() : dataFeed.getOptions();
final DataFeedRollupSettings dataFeedRollupSettings = dataFeedOptions.getRollupSettings() == null
? new DataFeedRollupSettings() : dataFeedOptions.getRollupSettings();
final DataFeedMissingDataPointFillSettings dataFeedMissingDataPointFillSettings =
dataFeedOptions.getMissingDataPointFillSettings() == null
? new DataFeedMissingDataPointFillSettings() : dataFeedOptions.getMissingDataPointFillSettings();
return service.updateDataFeedWithResponseAsync(UUID.fromString(dataFeed.getId()),
DataFeedTransforms.toInnerForUpdate(dataFeed.getSource())
.setDataFeedName(dataFeed.getName())
.setDataFeedDescription(dataFeedOptions.getDescription())
.setTimestampColumn(dataFeed.getSchema() == null
? null : dataFeed.getSchema().getTimestampColumn())
.setDataStartFrom(dataFeed.getIngestionSettings().getIngestionStartTime())
.setStartOffsetInSeconds(dataFeedIngestionSettings.getIngestionStartOffset() == null
? null : dataFeedIngestionSettings.getIngestionStartOffset().getSeconds())
.setMaxConcurrency(dataFeedIngestionSettings.getDataSourceRequestConcurrency())
.setStopRetryAfterInSeconds(dataFeedIngestionSettings.getStopRetryAfter() == null
? null : dataFeedIngestionSettings.getStopRetryAfter().getSeconds())
.setMinRetryIntervalInSeconds(dataFeedIngestionSettings.getIngestionRetryDelay() == null
? null : dataFeedIngestionSettings.getIngestionRetryDelay().getSeconds())
.setNeedRollup(
dataFeedRollupSettings.getRollupType() != null
? NeedRollupEnum.fromString(dataFeedRollupSettings.getRollupType().toString())
: null)
.setRollUpColumns(dataFeedRollupSettings.getAutoRollupGroupByColumnNames())
.setRollUpMethod(
dataFeedRollupSettings.getDataFeedAutoRollUpMethod() != null
? RollUpMethod.fromString(
dataFeedRollupSettings.getDataFeedAutoRollUpMethod().toString())
: null)
.setAllUpIdentification(dataFeedRollupSettings.getRollupIdentificationValue())
.setFillMissingPointType(
dataFeedMissingDataPointFillSettings.getFillType() != null
? FillMissingPointType.fromString(
dataFeedMissingDataPointFillSettings.getFillType().toString())
: null)
.setFillMissingPointValue(
dataFeedMissingDataPointFillSettings.getFillType() == DataFeedMissingDataPointFillType.CUSTOM_VALUE
? dataFeedMissingDataPointFillSettings.getCustomFillValue()
: null)
.setViewMode(
dataFeedOptions.getAccessMode() != null
? ViewMode.fromString(dataFeedOptions.getAccessMode().toString())
: null)
.setViewers(dataFeedOptions.getViewers())
.setAdmins(dataFeedOptions.getAdmins())
.setStatus(
dataFeed.getStatus() != null
? EntityStatus.fromString(dataFeed.getStatus().toString())
: null)
.setActionLinkTemplate(dataFeedOptions.getActionLinkTemplate()), context)
.flatMap(updatedDataFeedResponse -> getDataFeedWithResponse(dataFeed.getId()));
}
/**
* Delete a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeed
* <pre>
* final String dataFeedId = "t00853f1-9080-447f-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.deleteDataFeed&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeed
*
* @param dataFeedId The data feed unique id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDataFeed(String dataFeedId) {
return deleteDataFeedWithResponse(dataFeedId).flatMap(FluxUtil::toMono);
}
/**
* Delete a data feed with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeedWithResponse
* <pre>
* final String dataFeedId = "eh0854f1-8927-447f-bacf-8dccf2e86fwe";
* metricsAdvisorAdminAsyncClient.deleteDataFeedWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataFeedWithResponse
*
* @param dataFeedId The data feed unique id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDataFeedWithResponse(String dataFeedId) {
try {
return withContext(context -> deleteDataFeedWithResponse(dataFeedId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteDataFeedWithResponse(String dataFeedId, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' cannot be null.");
return service.deleteDataFeedWithResponseAsync(UUID.fromString(dataFeedId), context)
.map(response -> new SimpleResponse<>(response, null));
}
/**
* List information of all data feeds on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds -->
* <pre>
* metricsAdvisorAdminAsyncClient.listDataFeeds&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds -->
*
* @return A {@link PagedFlux} containing information of all the {@link DataFeed data feeds} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeed> listDataFeeds() {
return listDataFeeds(new ListDataFeedOptions());
}
/**
* List information of all data feeds on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds
* <pre>
* metricsAdvisorAdminAsyncClient.listDataFeeds&
* new ListDataFeedOptions&
* .setListDataFeedFilter&
* new ListDataFeedFilter&
* .setDataFeedStatus&
* .setDataFeedGranularityType&
* .setMaxPageSize&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeeds
*
* @param listDataFeedOptions The configurable {@link ListDataFeedOptions options} to pass for filtering the output result.
*
* @return A {@link PagedFlux} containing information of all the {@link DataFeed data feeds} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeed> listDataFeeds(ListDataFeedOptions listDataFeedOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listDataFeedsSinglePageAsync(listDataFeedOptions, context)),
continuationToken ->
withContext(context -> listDataFeedsNextPageAsync(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DataFeed> listDataFeeds(ListDataFeedOptions options, Context context) {
return new PagedFlux<>(() ->
listDataFeedsSinglePageAsync(options, context),
continuationToken ->
listDataFeedsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<DataFeed>> listDataFeedsSinglePageAsync(ListDataFeedOptions options, Context context) {
options = options != null ? options : new ListDataFeedOptions();
final ListDataFeedFilter dataFeedFilter =
options.getListDataFeedFilter() != null ? options.getListDataFeedFilter() : new ListDataFeedFilter();
return service.listDataFeedsSinglePageAsync(dataFeedFilter.getName(),
dataFeedFilter.getSourceType() != null
? DataSourceType.fromString(dataFeedFilter.getSourceType().toString()) : null,
dataFeedFilter.getGranularityType() != null
? Granularity.fromString(dataFeedFilter.getGranularityType().toString()) : null,
dataFeedFilter.getStatus() != null
? EntityStatus.fromString(dataFeedFilter.getStatus().toString()) : null,
dataFeedFilter.getCreator(),
options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing information for all data feeds"))
.doOnSuccess(response -> logger.info("Listed data feeds {}", response))
.doOnError(error -> logger.warning("Failed to list all data feeds information - {}", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream().map(DataFeedTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataFeed>> listDataFeedsNextPageAsync(String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listDataFeedsNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream().map(DataFeedTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
/**
* Fetch the ingestion status of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeedIngestionStatus
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* final ListDataFeedIngestionOptions options = new ListDataFeedIngestionOptions&
* metricsAdvisorAdminAsyncClient.listDataFeedIngestionStatus&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataFeedIngestionStatus
*
* @param dataFeedId The data feed id.
* @param listDataFeedIngestionOptions The additional parameters.
*
* @return The ingestion statuses.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code options}, {@code options.startTime},
* {@code options.endTime} is null.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataFeedIngestionStatus> listDataFeedIngestionStatus(
String dataFeedId,
ListDataFeedIngestionOptions listDataFeedIngestionOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listDataFeedIngestionStatusSinglePageAsync(dataFeedId, listDataFeedIngestionOptions, context)),
continuationToken ->
withContext(context -> listDataFeedIngestionStatusNextPageAsync(continuationToken,
listDataFeedIngestionOptions,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<DataFeedIngestionStatus> listDataFeedIngestionStatus(
String dataFeedId,
ListDataFeedIngestionOptions options, Context context) {
return new PagedFlux<>(() ->
listDataFeedIngestionStatusSinglePageAsync(dataFeedId, options, context),
continuationToken ->
listDataFeedIngestionStatusNextPageAsync(continuationToken,
options,
context));
}
private Mono<PagedResponse<DataFeedIngestionStatus>> listDataFeedIngestionStatusSinglePageAsync(
String dataFeedId,
ListDataFeedIngestionOptions options, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
Objects.requireNonNull(options, "'options' is required.");
Objects.requireNonNull(options.getStartTime(), "'options.startTime' is required.");
Objects.requireNonNull(options.getEndTime(), "'options.endTime' is required.");
IngestionStatusQueryOptions queryOptions = new IngestionStatusQueryOptions()
.setStartTime(options.getStartTime())
.setEndTime(options.getEndTime());
return service.getDataFeedIngestionStatusSinglePageAsync(
UUID.fromString(dataFeedId),
queryOptions,
options.getSkip(),
options.getMaxPageSize(),
context)
.doOnRequest(ignoredValue -> logger.info("Listing ingestion status for data feed"))
.doOnSuccess(response -> logger.info("Listed ingestion status {}", response))
.doOnError(error -> logger.warning("Failed to ingestion status for data feed", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
toDataFeedIngestionStatus(res.getValue()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataFeedIngestionStatus>> listDataFeedIngestionStatusNextPageAsync(
String nextPageLink,
ListDataFeedIngestionOptions options,
Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
IngestionStatusQueryOptions queryOptions = new IngestionStatusQueryOptions()
.setStartTime(options.getStartTime())
.setEndTime(options.getEndTime());
return service.getDataFeedIngestionStatusNextSinglePageAsync(nextPageLink, queryOptions, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink, response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
toDataFeedIngestionStatus(res.getValue()),
res.getContinuationToken(),
null));
}
/**
* Refresh data ingestion for a period.
* <p>
* The data in the data source for the given period will be re-ingested
* and any ingested data for the same period will be overwritten.
* </p>
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestion
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* metricsAdvisorAdminAsyncClient.refreshDataFeedIngestion&
* startTime,
* endTime&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestion
*
* @param dataFeedId The data feed id.
* @param startTime The start point of the period.
* @param endTime The end point of of the period.
*
* @return A {@link Mono} indicating ingestion reset success or failure.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code startTime}, {@code endTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> refreshDataFeedIngestion(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime) {
return refreshDataFeedIngestionWithResponse(dataFeedId,
startTime,
endTime).then();
}
/**
* Refresh data ingestion for a period.
* <p>
* The data in the data source for the given period will be re-ingested
* and any ingested data for the same period will be overwritten.
* </p>
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestionWithResponse
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* final OffsetDateTime startTime = OffsetDateTime.parse&
* final OffsetDateTime endTime = OffsetDateTime.parse&
* metricsAdvisorAdminAsyncClient.refreshDataFeedIngestionWithResponse&
* startTime,
* endTime&
* .subscribe&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.refreshDataFeedIngestionWithResponse
*
* @param dataFeedId The data feed id.
* @param startTime The start point of the period.
* @param endTime The end point of of the period.
*
* @return A {@link Response} of a {@link Mono} with result of reset request.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException If {@code dataFeedId}, {@code startTime}, {@code endTime} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> refreshDataFeedIngestionWithResponse(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime) {
try {
return withContext(context -> refreshDataFeedIngestionWithResponse(dataFeedId,
startTime,
endTime, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> refreshDataFeedIngestionWithResponse(
String dataFeedId,
OffsetDateTime startTime,
OffsetDateTime endTime, Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
Objects.requireNonNull(startTime, "'startTime' is required.");
Objects.requireNonNull(endTime, "'endTime' is required.");
return service.resetDataFeedIngestionStatusWithResponseAsync(UUID.fromString(dataFeedId),
new IngestionProgressResetOptions()
.setStartTime(startTime)
.setEndTime(endTime),
context)
.doOnRequest(ignoredValue -> logger.info("Resetting ingestion status for the data feed"))
.doOnSuccess(response -> logger.info("Ingestion status got reset {}", response))
.doOnError(error -> logger.warning("Failed to reset ingestion status for the data feed", error));
}
/**
* Retrieve the ingestion progress of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgress
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* metricsAdvisorAdminAsyncClient.getDataFeedIngestionProgress&
* .subscribe&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgress
*
* @param dataFeedId The data feed id.
*
* @return A {@link Mono} containing {@link DataFeedIngestionProgress} of the data feed.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataFeedIngestionProgress> getDataFeedIngestionProgress(String dataFeedId) {
return getDataFeedIngestionProgressWithResponse(dataFeedId, Context.NONE)
.map(Response::getValue);
}
/**
* Retrieve the ingestion progress of a data feed.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgressWithResponse
* <pre>
* final String dataFeedId = "4957a2f7-a0f4-4fc0-b8d7-d866c1df0f4c";
* metricsAdvisorAdminAsyncClient.getDataFeedIngestionProgressWithResponse&
* .subscribe&
* System.out.printf&
* DataFeedIngestionProgress ingestionProgress = response.getValue&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataFeedIngestionProgressWithResponse
*
* @param dataFeedId The data feed id.
*
* @return A {@link Response} of a {@link Mono} containing {@link DataFeedIngestionProgress} of the data feed.
* @throws IllegalArgumentException If {@code dataFeedId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code dataFeedId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataFeedIngestionProgress>> getDataFeedIngestionProgressWithResponse(String dataFeedId) {
try {
return withContext(context -> getDataFeedIngestionProgressWithResponse(dataFeedId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataFeedIngestionProgress>> getDataFeedIngestionProgressWithResponse(String dataFeedId,
Context context) {
Objects.requireNonNull(dataFeedId, "'dataFeedId' is required.");
return service.getIngestionProgressWithResponseAsync(UUID.fromString(dataFeedId), context)
.doOnRequest(ignoredValue -> logger.info("Retrieving ingestion progress for metric"))
.doOnSuccess(response -> logger.info("Retrieved ingestion progress {}", response))
.doOnError(error -> logger.warning("Failed to retrieve ingestion progress for metric", error))
.map(response -> new SimpleResponse<>(response, toDataFeedIngestionProgress(response.getValue())));
}
private DataFeedIngestionProgress toDataFeedIngestionProgress(
com.azure.ai.metricsadvisor.implementation.models.DataFeedIngestionProgress dataFeedIngestionProgressResponse) {
DataFeedIngestionProgress dataFeedIngestionProgress = new DataFeedIngestionProgress();
DataFeedIngestionProgressHelper.setLatestActiveTimestamp(dataFeedIngestionProgress, dataFeedIngestionProgressResponse.getLatestActiveTimestamp());
DataFeedIngestionProgressHelper.setLatestSuccessTimestamp(dataFeedIngestionProgress, dataFeedIngestionProgressResponse.getLatestSuccessTimestamp());
return dataFeedIngestionProgress;
}
/**
* Create a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfig
* <pre>
* final MetricWholeSeriesDetectionCondition wholeSeriesCondition = new MetricWholeSeriesDetectionCondition&
* .setConditionOperator&
* .setSmartDetectionCondition&
* 50,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setHardThresholdCondition&
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setLowerBound&
* .setUpperBound&
* .setChangeThresholdCondition&
* 50,
* 30,
* true,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
*
* final String detectionConfigName = "my_detection_config";
* final String detectionConfigDescription = "anomaly detection config for metric";
* final AnomalyDetectionConfiguration detectionConfig
* = new AnomalyDetectionConfiguration&
* .setDescription&
* .setWholeSeriesDetectionCondition&
*
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient
* .createDetectionConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfig
*
* @param metricId The metric id to associate the configuration with.
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Mono} containing the created {@link AnomalyDetectionConfiguration}.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID
* format specification, or {@code detectionConfiguration.name} is not set.
* @throws NullPointerException thrown if the {@code metricId} is null
* or {@code detectionConfiguration} is null
* or {@code detectionConfiguration.wholeSeriesCondition} is null
* or {@code seriesKey} is missing for any {@code MetricSingleSeriesDetectionCondition} in the configuration
* or {@code seriesGroupKey} is missing for any {@code MetricSeriesGroupDetectionCondition} in the configuration
* or {@code conditionOperator} is missing when multiple nested conditions are set in a
* {@code MetricSingleSeriesDetectionCondition} or {@code MetricSeriesGroupDetectionCondition}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> createDetectionConfig(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration) {
return createDetectionConfigWithResponse(metricId, detectionConfiguration)
.map(Response::getValue);
}
/**
* Create a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfigWithResponse
* <pre>
* final MetricWholeSeriesDetectionCondition wholeSeriesCondition = new MetricWholeSeriesDetectionCondition&
* .setConditionOperator&
* .setSmartDetectionCondition&
* 50,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setHardThresholdCondition&
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
* .setLowerBound&
* .setUpperBound&
* .setChangeThresholdCondition&
* 50,
* 30,
* true,
* AnomalyDetectorDirection.BOTH,
* new SuppressCondition&
*
* final String detectionConfigName = "my_detection_config";
* final String detectionConfigDescription = "anomaly detection config for metric";
* final AnomalyDetectionConfiguration detectionConfig
* = new AnomalyDetectionConfiguration&
* .setDescription&
* .setWholeSeriesDetectionCondition&
*
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient
* .createDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
* AnomalyDetectionConfiguration createdDetectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDetectionConfigWithResponse
*
* @param metricId The metric id to associate the configuration with.
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Response} of a {@link Mono} containing the created {@link AnomalyDetectionConfiguration}.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID
* format specification, or {@code detectionConfiguration.name} is not set.
* @throws NullPointerException thrown if the {@code metricId} is null
* or {@code detectionConfiguration} is null
* or {@code detectionConfiguration.wholeSeriesCondition} is null
* or {@code seriesKey} is missing for any {@code MetricSingleSeriesDetectionCondition} in the configuration
* or {@code seriesGroupKey} is missing for any {@code MetricSeriesGroupDetectionCondition} in the configuration
* or {@code conditionOperator} is missing when multiple nested conditions are set in a
* {@code MetricSingleSeriesDetectionCondition} or {@code MetricSeriesGroupDetectionCondition}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> createDetectionConfigWithResponse(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration) {
try {
return withContext(context -> createDetectionConfigWithResponse(metricId,
detectionConfiguration,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> createDetectionConfigWithResponse(
String metricId,
AnomalyDetectionConfiguration detectionConfiguration,
Context context) {
Objects.requireNonNull(metricId, "metricId is required");
Objects.requireNonNull(detectionConfiguration, "detectionConfiguration is required");
final com.azure.ai.metricsadvisor.implementation.models.AnomalyDetectionConfiguration
innerDetectionConfiguration = DetectionConfigurationTransforms.toInnerForCreate(logger,
metricId,
detectionConfiguration);
return service.createAnomalyDetectionConfigurationWithResponseAsync(innerDetectionConfiguration, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating AnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Created AnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to create AnomalyDetectionConfiguration", error))
.flatMap(response -> {
final String configurationId
= Utility.parseOperationId(response.getDeserializedHeaders().getLocation());
return getDetectionConfigWithResponse(configurationId, context)
.map(configurationResponse -> new ResponseBase<Void, AnomalyDetectionConfiguration>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Get the anomaly detection configuration by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
*
* System.out.printf&
*
* System.out.printf&
* MetricWholeSeriesDetectionCondition wholeSeriesDetectionCondition
* = detectionConfig.getWholeSeriesDetectionCondition&
*
* System.out.printf&
* wholeSeriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
*
* List<MetricSingleSeriesDetectionCondition> seriesDetectionConditions
* = detectionConfig.getSeriesDetectionConditions&
* System.out.printf&
* for &
* DimensionKey seriesKey = seriesDetectionCondition.getSeriesKey&
* final String seriesKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
*
* List<MetricSeriesGroupDetectionCondition> seriesGroupDetectionConditions
* = detectionConfig.getSeriesGroupDetectionConditions&
* System.out.printf&
* for &
* : seriesGroupDetectionConditions&
* DimensionKey seriesGroupKey = seriesGroupDetectionCondition.getSeriesGroupKey&
* final String seriesGroupKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfig
*
* @param detectionConfigurationId The anomaly detection configuration id.
* @return A {@link Mono} containing the {@link AnomalyDetectionConfiguration} for the provided id.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> getDetectionConfig(
String detectionConfigurationId) {
return getDetectionConfigWithResponse(detectionConfigurationId)
.map(Response::getValue);
}
/**
* Get the anomaly detection configuration by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
*
* AnomalyDetectionConfiguration detectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
*
* System.out.printf&
*
* System.out.printf&
* MetricWholeSeriesDetectionCondition wholeSeriesDetectionCondition
* = detectionConfig.getWholeSeriesDetectionCondition&
*
* System.out.printf&
* wholeSeriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* wholeSeriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
*
* List<MetricSingleSeriesDetectionCondition> seriesDetectionConditions
* = detectionConfig.getSeriesDetectionConditions&
* System.out.printf&
* for &
* DimensionKey seriesKey = seriesDetectionCondition.getSeriesKey&
* final String seriesKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
*
* List<MetricSeriesGroupDetectionCondition> seriesGroupDetectionConditions
* = detectionConfig.getSeriesGroupDetectionConditions&
* System.out.printf&
* for &
* : seriesGroupDetectionConditions&
* DimensionKey seriesGroupKey = seriesGroupDetectionCondition.getSeriesGroupKey&
* final String seriesGroupKeyStr
* = Arrays.toString&
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getConditionOperator&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSensitivity&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getAnomalyDetectorDirection&
* System.out.printf&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getSmartDetectionCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getLowerBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getUpperBound&
* System.out.printf&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getHardThresholdCondition&
* .getSuppressCondition&
*
* System.out.printf&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getChangePercentage&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getShiftPoint&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .isWithinRange&
* System.out.printf&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* seriesGroupDetectionCondition.getChangeThresholdCondition&
* .getSuppressCondition&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDetectionConfigWithResponse
*
* @param detectionConfigurationId The anomaly detection configuration id.
* @return A {@link Response} of a {@link Mono} containing the {@link AnomalyDetectionConfiguration}
* for the provided id.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> getDetectionConfigWithResponse(
String detectionConfigurationId) {
try {
return withContext(context -> getDetectionConfigWithResponse(detectionConfigurationId,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> getDetectionConfigWithResponse(
String detectionConfigurationId, Context context) {
Objects.requireNonNull(detectionConfigurationId, "detectionConfigurationId is required.");
return service.getAnomalyDetectionConfigurationWithResponseAsync(UUID.fromString(detectionConfigurationId), context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving AnomalyDetectionConfiguration - {}",
detectionConfigurationId))
.doOnSuccess(response -> logger.info("Retrieved AnomalyDetectionConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to retrieve AnomalyDetectionConfiguration - {}",
detectionConfigurationId, error))
.map(response -> {
AnomalyDetectionConfiguration configuration
= DetectionConfigurationTransforms.fromInner(response.getValue());
return new ResponseBase<Void, AnomalyDetectionConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configuration,
null);
});
}
/**
* Update a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfig&
* .flatMap&
* detectionConfig.setName&
* detectionConfig.setDescription&
*
* DimensionKey seriesGroupKey = new DimensionKey&
* .put&
* detectionConfig.addSeriesGroupDetectionCondition&
* new MetricSeriesGroupDetectionCondition&
* .setSmartDetectionCondition&
* 10.0,
* AnomalyDetectorDirection.UP,
* new SuppressCondition&
* return metricsAdvisorAdminAsyncClient
* .updateDetectionConfig&
* &
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfig
*
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Mono} containing the updated {@link AnomalyDetectionConfiguration}.
* @throws NullPointerException thrown if the {@code detectionConfiguration} is null
* or {@code detectionConfiguration.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyDetectionConfiguration> updateDetectionConfig(
AnomalyDetectionConfiguration detectionConfiguration) {
return updateDetectionConfigWithResponse(detectionConfiguration)
.map(Response::getValue);
}
/**
* Update a configuration to detect anomalies in the time series of a metric.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .getDetectionConfigWithResponse&
* .flatMap&
* AnomalyDetectionConfiguration detectionConfig = response.getValue&
* detectionConfig.setName&
* detectionConfig.setDescription&
* DimensionKey seriesGroupKey = new DimensionKey&
* .put&
* detectionConfig.addSeriesGroupDetectionCondition&
* new MetricSeriesGroupDetectionCondition&
* .setSmartDetectionCondition&
* 10.0,
* AnomalyDetectorDirection.UP,
* new SuppressCondition&
* return metricsAdvisorAdminAsyncClient
* .updateDetectionConfigWithResponse&
* &
* .subscribe&
* AnomalyDetectionConfiguration updatedDetectionConfig = response.getValue&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDetectionConfigWithResponse
*
* @param detectionConfiguration The anomaly detection configuration.
* @return A {@link Response} of a {@link Mono} containing the updated {@link AnomalyDetectionConfiguration}.
* @throws NullPointerException thrown if the {@code detectionConfiguration} is null
* or {@code detectionConfiguration.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyDetectionConfiguration>> updateDetectionConfigWithResponse(
AnomalyDetectionConfiguration detectionConfiguration) {
try {
return withContext(context -> updateDetectionConfigWithResponse(detectionConfiguration,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<AnomalyDetectionConfiguration>> updateDetectionConfigWithResponse(
AnomalyDetectionConfiguration detectionConfiguration,
Context context) {
Objects.requireNonNull(detectionConfiguration, "detectionConfiguration is required");
Objects.requireNonNull(detectionConfiguration.getId(), "detectionConfiguration.id is required");
final AnomalyDetectionConfigurationPatch innerDetectionConfigurationPatch
= DetectionConfigurationTransforms.toInnerForUpdate(logger, detectionConfiguration);
return service.updateAnomalyDetectionConfigurationWithResponseAsync(
UUID.fromString(detectionConfiguration.getId()),
innerDetectionConfigurationPatch,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating AnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Updated AnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to update AnomalyDetectionConfiguration", error))
.flatMap(response -> {
return getDetectionConfigWithResponse(detectionConfiguration.getId(), context)
.map(configurationResponse -> new ResponseBase<Void, AnomalyDetectionConfiguration>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Delete a metric anomaly detection configuration.
*
* @param detectionConfigurationId The metric anomaly detection configuration unique id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfig
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .deleteDetectionConfig&
* .subscribe&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfig
*
* @return An empty Mono.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDetectionConfig(String detectionConfigurationId) {
return deleteDetectionConfigWithResponse(detectionConfigurationId).then();
}
/**
* Delete a metric anomaly detection configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfigWithResponse
* <pre>
* final String detectionConfigId = "7b8069a1-1564-46da-9f50-b5d0dd9129ab";
* metricsAdvisorAdminAsyncClient
* .deleteDetectionConfigWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDetectionConfigWithResponse
*
* @param detectionConfigurationId The metric anomaly detection configuration unique id.
*
* @return A {@link Response} of a {@link Mono}.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the UUID
* format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDetectionConfigWithResponse(
String detectionConfigurationId) {
try {
return withContext(context -> deleteDetectionConfigWithResponse(
detectionConfigurationId,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> deleteDetectionConfigWithResponse(String detectionConfigurationId,
Context context) {
Objects.requireNonNull(detectionConfigurationId, "detectionConfigurationId is required.");
return service.deleteHookWithResponseAsync(UUID.fromString(detectionConfigurationId), context)
.doOnRequest(ignoredValue -> logger.info("Deleting MetricAnomalyDetectionConfiguration"))
.doOnSuccess(response -> logger.info("Deleted MetricAnomalyDetectionConfiguration"))
.doOnError(error -> logger.warning("Failed to delete MetricAnomalyDetectionConfiguration", error));
}
/**
* Given a metric id, retrieve all anomaly detection configurations applied to it.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
* <pre>
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient.listDetectionConfigs&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
*
* @param metricId The metric id.
* @return The anomaly detection configurations.
* @throws NullPointerException thrown if the {@code metricId} is null.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId) {
return listDetectionConfigs(metricId, null);
}
/**
* Given a metric id, retrieve all anomaly detection configurations applied to it.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
* <pre>
* final String metricId = "0b836da8-10e6-46cd-8f4f-28262e113a62";
* metricsAdvisorAdminAsyncClient.listDetectionConfigs&
* new ListDetectionConfigsOptions&
* .subscribe&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDetectionConfigs
*
* @param metricId The metric id.
* @param listDetectionConfigsOptions the additional configurable options to specify when querying the result.
* @return The anomaly detection configurations.
* @throws NullPointerException thrown if the {@code metricId} is null.
* @throws IllegalArgumentException If {@code metricId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId,
ListDetectionConfigsOptions listDetectionConfigsOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listAnomalyDetectionConfigsSinglePageAsync(metricId, listDetectionConfigsOptions, context)),
continuationToken ->
withContext(context -> listAnomalyDetectionConfigsNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<AnomalyDetectionConfiguration> listDetectionConfigs(
String metricId,
ListDetectionConfigsOptions options,
Context context) {
return new PagedFlux<>(() ->
listAnomalyDetectionConfigsSinglePageAsync(metricId, options, context),
continuationToken ->
listAnomalyDetectionConfigsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<AnomalyDetectionConfiguration>> listAnomalyDetectionConfigsSinglePageAsync(
String metricId,
ListDetectionConfigsOptions options,
Context context) {
if (options == null) {
options = new ListDetectionConfigsOptions();
}
return service.getAnomalyDetectionConfigurationsByMetricSinglePageAsync(
UUID.fromString(metricId), options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing MetricAnomalyDetectionConfigs"))
.doOnSuccess(response -> logger.info("Listed MetricAnomalyDetectionConfigs {}", response))
.doOnError(error -> logger.warning("Failed to list the MetricAnomalyDetectionConfigs", error))
.map(DetectionConfigurationTransforms::fromInnerPagedResponse);
}
private Mono<PagedResponse<AnomalyDetectionConfiguration>> listAnomalyDetectionConfigsNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.getAnomalyDetectionConfigurationsByMetricNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(DetectionConfigurationTransforms::fromInnerPagedResponse);
}
/**
* Creates a notificationHook that receives anomaly incident alerts.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHook
* <pre>
* NotificationHook emailNotificationHook = new EmailNotificationHook&
* .setDescription&
* .setEmailsToAlert&
* add&
* &
* .setExternalLink&
*
* metricsAdvisorAdminAsyncClient.createHook&
* .subscribe&
* EmailNotificationHook createdEmailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* createdEmailHook.getEmailsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHook
*
* @param notificationHook The notificationHook.
*
* @return A {@link Mono} containing the created {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook}, {@code notificationHook.name},
* {@code notificationHook.endpoint} (for web notificationHook) is null.
* @throws IllegalArgumentException If at least one email not present for email notificationHook.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> createHook(NotificationHook notificationHook) {
return createHookWithResponse(notificationHook)
.map(Response::getValue);
}
/**
* Creates a notificationHook that receives anomaly incident alerts.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHookWithResponse
* <pre>
* NotificationHook emailNotificationHook = new EmailNotificationHook&
* .setDescription&
* .setEmailsToAlert&
* add&
* &
* .setExternalLink&
*
* metricsAdvisorAdminAsyncClient.createHookWithResponse&
* .subscribe&
* System.out.printf&
* EmailNotificationHook createdEmailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* createdEmailHook.getEmailsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createHookWithResponse
*
* @param notificationHook The notificationHook.
*
* @return A {@link Response} of a {@link Mono} containing the created {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook}, {@code notificationHook.name},
* {@code notificationHook.endpoint} (for web notificationHook) is null.
* @throws IllegalArgumentException If at least one email not present for email notificationHook.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> createHookWithResponse(NotificationHook notificationHook) {
try {
return withContext(context -> createHookWithResponse(notificationHook, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> createHookWithResponse(NotificationHook notificationHook, Context context) {
Objects.requireNonNull(notificationHook, "'notificationHook' cannot be null.");
return service.createHookWithResponseAsync(HookTransforms.toInnerForCreate(logger, notificationHook), context)
.doOnRequest(ignoredValue -> logger.info("Creating NotificationHook"))
.doOnSuccess(response -> logger.info("Created NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to create notificationHook", error))
.flatMap(response -> {
final String hookUri = response.getDeserializedHeaders().getLocation();
final String hookId = parseOperationId(hookUri);
return getHookWithResponse(hookId, context)
.map(hookResponse -> new ResponseBase<Void, NotificationHook>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
hookResponse.getValue(),
null));
});
}
/**
* Get a hook by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHook
* <pre>
* final String hookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHook&
* .subscribe&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* emailHook.getEmailsToAlert&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHook
*
* @param hookId The hook unique id.
*
* @return A {@link Mono} containing the {@link NotificationHook} for the provided id.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code hookId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> getHook(String hookId) {
return getHookWithResponse(hookId).map(Response::getValue);
}
/**
* Get a hook by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHookWithResponse
* <pre>
* final String hookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHookWithResponse&
* .subscribe&
* System.out.printf&
* NotificationHook notificationHook = response.getValue&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getHookWithResponse
*
* @param hookId The hook unique id.
*
* @return A {@link Response} of a {@link Mono} containing the {@link NotificationHook} for the provided id.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code hookId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> getHookWithResponse(String hookId) {
try {
return withContext(context -> getHookWithResponse(hookId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> getHookWithResponse(String hookId, Context context) {
Objects.requireNonNull(hookId, "hookId is required.");
return service.getHookWithResponseAsync(UUID.fromString(hookId), context)
.doOnRequest(ignoredValue -> logger.info("Retrieving NotificationHook"))
.doOnSuccess(response -> logger.info("Retrieved NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to retrieve hook", error))
.map(innerResponse -> new ResponseBase<Void, NotificationHook>(innerResponse.getRequest(),
innerResponse.getStatusCode(),
innerResponse.getHeaders(),
HookTransforms.fromInner(logger, innerResponse.getValue()),
null));
}
/**
* Update an existing notificationHook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHook
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHook&
* .flatMap&
* EmailNotificationHook emailHook = &
* List<String> emailsToUpdate = new ArrayList<>&
* emailsToUpdate.remove&
* emailsToUpdate.add&
* emailsToUpdate.add&
* emailHook.setEmailsToAlert&
* return metricsAdvisorAdminAsyncClient.updateHook&
* &
* .subscribe&
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHook
*
* @param notificationHook The notificationHook to update.
*
* @return A {@link Mono} containing the updated {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook.id} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NotificationHook> updateHook(NotificationHook notificationHook) {
return updateHookWithResponse(notificationHook).map(Response::getValue);
}
/**
* Update an existing notification hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHookWithResponse
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.getHookWithResponse&
* .flatMap&
* EmailNotificationHook emailHook = &
* List<String> emailsToUpdate = new ArrayList<>&
* emailsToUpdate.remove&
* emailsToUpdate.add&
* emailsToUpdate.add&
* emailHook.setEmailsToAlert&
* return metricsAdvisorAdminAsyncClient.updateHookWithResponse&
* &
* .subscribe&
* System.out.printf&
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateHookWithResponse
*
* @param notificationHook The notificationHook to update.
*
* @return A {@link Response} of a {@link Mono} containing the updated {@link NotificationHook}.
* @throws NullPointerException If {@code notificationHook.id} is null.
* @throws IllegalArgumentException If {@code notificationHook.Id} does not conform to the UUID format
* specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NotificationHook>> updateHookWithResponse(NotificationHook notificationHook) {
try {
return withContext(context -> updateHookWithResponse(notificationHook, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<NotificationHook>> updateHookWithResponse(NotificationHook notificationHook, Context context) {
Objects.requireNonNull(notificationHook, "'notificationHook' cannot be null.");
Objects.requireNonNull(notificationHook.getId(), "'notificationHook.id' cannot be null.");
return service.updateHookWithResponseAsync(UUID.fromString(notificationHook.getId()),
HookTransforms.toInnerForUpdate(logger, notificationHook), context)
.doOnRequest(ignoredValue -> logger.info("Updating NotificationHook"))
.doOnSuccess(response -> logger.info("Updated NotificationHook {}", response))
.doOnError(error -> logger.warning("Failed to update notificationHook", error))
.flatMap(response -> getHookWithResponse(notificationHook.getId(), context)
.map(hookResponse -> new ResponseBase<Void, NotificationHook>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
hookResponse.getValue(),
null)));
}
/**
* Delete a hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHook
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.deleteHook&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHook
*
* @param hookId The hook unique id.
*
* @return An empty Mono.
* @throws NullPointerException thrown if the {@code hookId} is null.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteHook(String hookId) {
return deleteHookWithResponse(hookId).then();
}
/**
* Delete a hook.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHookWithResponse
* <pre>
* final String emailHookId = "f00853f1-6627-447f-bacf-8dccf2e86fed";
* metricsAdvisorAdminAsyncClient.deleteHookWithResponse&
* .subscribe&
* System.out.printf&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteHookWithResponse
*
* @param hookId The hook unique id.
*
* @return A {@link Response} of a {@link Mono}.
* @throws NullPointerException thrown if the {@code hookId} is null.
* @throws IllegalArgumentException If {@code hookId} does not conform to the UUID format specification.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteHookWithResponse(String hookId) {
try {
return withContext(context -> deleteHookWithResponse(hookId, context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<Void>> deleteHookWithResponse(String hookId, Context context) {
Objects.requireNonNull(hookId, "hookId is required.");
return service.deleteHookWithResponseAsync(UUID.fromString(hookId), context)
.doOnRequest(ignoredValue -> logger.info("Deleting NotificationHook"))
.doOnSuccess(response -> logger.info("Deleted NotificationHook"))
.doOnError(error -> logger.warning("Failed to delete hook", error));
}
/**
* List information of hooks on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks -->
* <pre>
* metricsAdvisorAdminAsyncClient.listHooks&
* .subscribe&
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks -->
*
* @return A {@link PagedFlux} containing information of all the {@link NotificationHook} in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<NotificationHook> listHooks() {
return listHooks(new ListHookOptions());
}
/**
* List information of hooks.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks
* <pre>
* ListHookOptions options = new ListHookOptions&
* .setSkip&
* .setMaxPageSize&
* int[] pageCount = new int[1];
* metricsAdvisorAdminAsyncClient.listHooks&
* .subscribe&
* System.out.printf&
* for &
* if &
* EmailNotificationHook emailHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* WebNotificationHook webHook = &
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* System.out.printf&
* &
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listHooks
*
* @param listHookOptions the additional configurable options to specify when listing hooks.
*
* @return A {@link PagedFlux} containing information of the {@link NotificationHook} resources.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<NotificationHook> listHooks(ListHookOptions listHookOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listHooksSinglePageAsync(listHookOptions, context)),
continuationToken ->
withContext(context -> listHooksNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<NotificationHook> listHooks(ListHookOptions options, Context context) {
return new PagedFlux<>(() ->
listHooksSinglePageAsync(options, context),
continuationToken ->
listHooksNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<NotificationHook>> listHooksSinglePageAsync(ListHookOptions options, Context context) {
return service.listHooksSinglePageAsync(
options != null ? options.getHookNameFilter() : null,
options != null ? options.getSkip() : null,
options != null ? options.getMaxPageSize() : null,
context)
.doOnRequest(ignoredValue -> logger.info("Listing hooks"))
.doOnSuccess(response -> logger.info("Listed hooks {}", response))
.doOnError(error -> logger.warning("Failed to list the hooks", error))
.map(response -> HookTransforms.fromInnerPagedResponse(logger, response));
}
private Mono<PagedResponse<NotificationHook>> listHooksNextPageAsync(String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listHooksNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(response -> HookTransforms.fromInnerPagedResponse(logger, response));
}
/**
* Create a configuration to trigger alert when anomalies are detected.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfig
* <pre>
* String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.createAlertConfig&
* new AnomalyAlertConfiguration&
* .setDescription&
* .setMetricAlertConfigurations&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* .setAlertConditions&
* .setSeverityRangeCondition&
* .setCrossMetricsOperator&
* .setHookIdsToAlert&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfig
*
* @param alertConfiguration The anomaly alerting configuration.
*
* @return A {@link Mono} containing the created {@link AnomalyAlertConfiguration}.
* @throws NullPointerException thrown if the {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> createAlertConfig(
AnomalyAlertConfiguration alertConfiguration) {
return createAlertConfigWithResponse(alertConfiguration).flatMap(FluxUtil::toMono);
}
/**
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfigWithResponse
* <pre>
*
* String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
* String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.createAlertConfigWithResponse&
* new AnomalyAlertConfiguration&
* .setDescription&
* .setMetricAlertConfigurations&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* new MetricAlertConfiguration&
* MetricAnomalyAlertScope.forWholeSeries&
* .setAlertConditions&
* .setSeverityRangeCondition&
* .setCrossMetricsOperator&
* .setHookIdsToAlert&
* .subscribe&
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration anomalyAlertConfiguration = alertConfigurationResponse.getValue&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createAlertConfigWithResponse
*
* @param alertConfiguration The anomaly alerting configuration.
*
* @return A {@link Response} of a {@link Mono} containing the created {@link AnomalyAlertConfiguration}.
* @throws NullPointerException thrown if the {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> createAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration) {
try {
return withContext(context -> createAlertConfigWithResponse(alertConfiguration, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> createAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration, Context context) {
Objects.requireNonNull(alertConfiguration, "'alertConfiguration' is required.");
if (CoreUtils.isNullOrEmpty(alertConfiguration.getMetricAlertConfigurations())) {
Objects.requireNonNull("'alertConfiguration.metricAnomalyAlertConfigurations' is required");
}
if (alertConfiguration.getCrossMetricsOperator() == null
&& alertConfiguration.getMetricAlertConfigurations().size() > 1) {
throw logger.logExceptionAsError(new IllegalArgumentException("crossMetricsOperator is required"
+ " when there are more than one metric level alert configuration."));
}
final AnomalyAlertingConfiguration innerAlertConfiguration
= AlertConfigurationTransforms.toInnerForCreate(alertConfiguration);
return service.createAnomalyAlertingConfigurationWithResponseAsync(innerAlertConfiguration, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating AnomalyAlertConfiguration - {}",
innerAlertConfiguration))
.doOnSuccess(response -> logger.info("Created AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to create AnomalyAlertConfiguration - {}",
innerAlertConfiguration, error))
.flatMap(response -> {
final String configurationId = parseOperationId(response.getDeserializedHeaders().getLocation());
return getAlertConfigWithResponse(configurationId, context)
.map(getResponse -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
getResponse.getValue(),
null));
});
}
/**
* Get the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfig
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfig
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A {@link Mono} containing the {@link AnomalyAlertConfiguration} identified by the given id.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> getAlertConfig(
String alertConfigurationId) {
return getAlertConfigWithResponse(alertConfigurationId).flatMap(FluxUtil::toMono);
}
/**
* Get the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfigWithResponse
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfigWithResponse&
* .subscribe&
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration anomalyAlertConfiguration = alertConfigurationResponse.getValue&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getAlertConfigWithResponse
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A {@link Response response} of a {@link Mono}
* containing the {@link AnomalyAlertConfiguration} identified by the given id.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> getAlertConfigWithResponse(
String alertConfigurationId) {
try {
return withContext(context -> getAlertConfigWithResponse(alertConfigurationId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> getAlertConfigWithResponse(
String alertConfigurationId, Context context) {
Objects.requireNonNull(alertConfigurationId, "'alertConfigurationId' is required.");
return service.getAnomalyAlertingConfigurationWithResponseAsync(UUID.fromString(alertConfigurationId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving AnomalyDetectionConfiguration - {}",
alertConfigurationId))
.doOnSuccess(response -> logger.info("Retrieved AnomalyDetectionConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to retrieve AnomalyDetectionConfiguration - {}",
alertConfigurationId, error))
.map(response -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(), AlertConfigurationTransforms.fromInner(response.getValue()), null));
}
/**
* Update anomaly alert configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfig
* <pre>
*
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* String additionalHookId = "2gh8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .flatMap&
* List<String> hookIds = new ArrayList<>&
* hookIds.add&
* return metricsAdvisorAdminAsyncClient.updateAlertConfig&
* existingAnomalyConfig
* .setHookIdsToAlert&
* .setDescription&
* &
* System.out.printf&
* updateAnomalyAlertConfiguration.getId&
* System.out.printf&
* updateAnomalyAlertConfiguration.getDescription&
* System.out.printf&
* updateAnomalyAlertConfiguration.getHookIdsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfig
*
* @param alertConfiguration The anomaly alert configuration to update.
*
* @return A {@link Mono} containing the {@link AnomalyAlertConfiguration} that was updated.
* @throws NullPointerException thrown if {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null or empty.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<AnomalyAlertConfiguration> updateAlertConfig(
AnomalyAlertConfiguration alertConfiguration) {
return updateAlertConfigWithResponse(alertConfiguration).flatMap(FluxUtil::toMono);
}
/**
* Update anomaly alert configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfigWithResponse
* <pre>
*
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* String additionalHookId = "2gh8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.getAlertConfig&
* .flatMap&
* List<String> hookIds = new ArrayList<>&
* hookIds.add&
* return metricsAdvisorAdminAsyncClient.updateAlertConfigWithResponse&
* existingAnomalyConfig
* .setHookIdsToAlert&
* .setDescription&
* &
* System.out.printf&
* alertConfigurationResponse.getStatusCode&
* final AnomalyAlertConfiguration updatedAnomalyAlertConfiguration
* = alertConfigurationResponse.getValue&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getId&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getDescription&
* System.out.printf&
* updatedAnomalyAlertConfiguration.getHookIdsToAlert&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateAlertConfigWithResponse
*
* @param alertConfiguration The anomaly alert configuration to update.
*
* @return A {@link Response} of a {@link Mono} containing the {@link AnomalyAlertConfiguration} that was updated.
* @throws NullPointerException thrown if {@code alertConfiguration} or
* {@code alertConfiguration.metricAnomalyAlertConfigurations} is null or empty.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AnomalyAlertConfiguration>> updateAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration) {
try {
return withContext(context -> updateAlertConfigWithResponse(alertConfiguration, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<AnomalyAlertConfiguration>> updateAlertConfigWithResponse(
AnomalyAlertConfiguration alertConfiguration, Context context) {
Objects.requireNonNull(alertConfiguration, "'alertConfiguration' is required");
if (CoreUtils.isNullOrEmpty(alertConfiguration.getMetricAlertConfigurations())) {
throw logger.logExceptionAsError(new NullPointerException(
"'alertConfiguration.metricAnomalyAlertConfigurations' is required and cannot be empty"));
}
final AnomalyAlertingConfigurationPatch innerAlertConfiguration
= AlertConfigurationTransforms.toInnerForUpdate(alertConfiguration);
return service.updateAnomalyAlertingConfigurationWithResponseAsync(
UUID.fromString(alertConfiguration.getId()),
innerAlertConfiguration,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating AnomalyAlertConfiguration - {}",
innerAlertConfiguration))
.doOnSuccess(response -> logger.info("Updated AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to update AnomalyAlertConfiguration - {}",
innerAlertConfiguration, error))
.flatMap(response -> getAlertConfigWithResponse(alertConfiguration.getId(), context)
.map(getResponse -> new ResponseBase<Void, AnomalyAlertConfiguration>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
getResponse.getValue(),
null)));
}
/**
* Deletes the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfig
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
* metricsAdvisorAdminAsyncClient.deleteAlertConfig&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfig
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteAlertConfig(String alertConfigurationId) {
return deleteAlertConfigWithResponse(alertConfigurationId).flatMap(FluxUtil::toMono);
}
/**
* Deletes the anomaly alert configuration identified by {@code alertConfigurationId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfigWithResponse
* <pre>
* String alertConfigId = "1p0f8er30-6e6e-4391-b78f-bpfdfee1e6f5";
*
* metricsAdvisorAdminAsyncClient.deleteAlertConfigWithResponse&
* .subscribe&
* System.out.printf&
* response.getStatusCode&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteAlertConfigWithResponse
*
* @param alertConfigurationId The anomaly alert configuration id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code alertConfigurationId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code alertConfigurationId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteAlertConfigWithResponse(String alertConfigurationId) {
try {
return withContext(context -> deleteAlertConfigWithResponse(alertConfigurationId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteAlertConfigWithResponse(String alertConfigurationId, Context context) {
Objects.requireNonNull(alertConfigurationId, "'alertConfigurationId' is required.");
return service.deleteAnomalyAlertingConfigurationWithResponseAsync(UUID.fromString(alertConfigurationId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting AnomalyAlertConfiguration - {}", alertConfigurationId))
.doOnSuccess(response -> logger.info("Deleted AnomalyAlertConfiguration - {}", response))
.doOnError(error -> logger.warning("Failed to delete AnomalyAlertConfiguration - {}",
alertConfigurationId, error));
}
/**
* Fetch the anomaly alert configurations associated with a detection configuration.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listAlertConfigs
* <pre>
* String detectionConfigId = "3rt98er30-6e6e-4391-b78f-bpfdfee1e6f5";
* metricsAdvisorAdminAsyncClient.listAlertConfigs&
* .subscribe&
* System.out.printf&
* System.out.printf&
* anomalyAlertConfiguration.getDescription&
* System.out.printf&
* anomalyAlertConfiguration.getHookIdsToAlert&
* System.out.printf&
* anomalyAlertConfiguration.getCrossMetricsOperator&
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listAlertConfigs
*
* @param detectionConfigurationId The id of the detection configuration.
* @param listAnomalyAlertConfigsOptions th e additional configurable options to specify when querying the result.
*
* @return A {@link PagedFlux} containing information of all the
* {@link AnomalyAlertConfiguration anomaly alert configurations} for the specified detection configuration.
* @throws NullPointerException thrown if the {@code detectionConfigurationId} is null.
* @throws IllegalArgumentException If {@code detectionConfigurationId} does not conform to the
* UUID format specification.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AnomalyAlertConfiguration> listAlertConfigs(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions listAnomalyAlertConfigsOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listAnomalyAlertConfigsSinglePageAsync(detectionConfigurationId,
listAnomalyAlertConfigsOptions,
context)),
continuationToken ->
withContext(context -> listAnomalyAlertConfigsNextPageAsync(continuationToken,
context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> FluxUtil.monoError(logger, ex));
}
}
PagedFlux<AnomalyAlertConfiguration> listAlertConfigs(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions options, Context context) {
return new PagedFlux<>(() ->
listAnomalyAlertConfigsSinglePageAsync(detectionConfigurationId,
options,
context),
continuationToken ->
listAnomalyAlertConfigsNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<AnomalyAlertConfiguration>> listAnomalyAlertConfigsSinglePageAsync(
String detectionConfigurationId, ListAnomalyAlertConfigsOptions options, Context context) {
Objects.requireNonNull(detectionConfigurationId, "'detectionConfigurationId' is required.");
if (options == null) {
options = new ListAnomalyAlertConfigsOptions();
}
return service.getAnomalyAlertingConfigurationsByAnomalyDetectionConfigurationSinglePageAsync(
UUID.fromString(detectionConfigurationId), options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing AnomalyAlertConfigs"))
.doOnSuccess(response -> logger.info("Listed AnomalyAlertConfigs {}", response))
.doOnError(error -> logger.warning("Failed to list the AnomalyAlertConfigs", error))
.map(AlertConfigurationTransforms::fromInnerPagedResponse);
}
private Mono<PagedResponse<AnomalyAlertConfiguration>> listAnomalyAlertConfigsNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.getAnomalyAlertingConfigurationsByAnomalyDetectionConfigurationNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {} {}",
nextPageLink,
response))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(AlertConfigurationTransforms::fromInnerPagedResponse);
}
/**
* Create a data source credential entity.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredential
* <pre>
* DataSourceCredentialEntity datasourceCredential;
* final String name = "sample_name" + UUID.randomUUID&
* final String cId = "f45668b2-bffa-11eb-8529-0246ac130003";
* final String tId = "67890ded-5e07-4e52-b225-4ae8f905afb5";
* final String mockSecret = "890hy69-5e07-4e52-b225-4ae8f905afb5";
*
* datasourceCredential = new DataSourceServicePrincipalInKeyVault&
* .setName&
* .setKeyVaultForDataSourceSecrets&
* .setTenantId&
* .setSecretNameForDataSourceClientId&
* .setSecretNameForDataSourceClientSecret&
*
* metricsAdvisorAdminAsyncClient.createDataSourceCredential&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredential
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the created {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> createDataSourceCredential(
DataSourceCredentialEntity dataSourceCredential) {
return createDataSourceCredentialWithResponse(dataSourceCredential)
.map(Response::getValue);
}
/**
* Create a data source credential entity with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredentialWithResponse
* <pre>
* DataSourceCredentialEntity datasourceCredential;
* final String name = "sample_name" + UUID.randomUUID&
* final String cId = "f45668b2-bffa-11eb-8529-0246ac130003";
* final String tId = "67890ded-5e07-4e52-b225-4ae8f905afb5";
* final String mockSecret = "890hy69-5e07-4e52-b225-4ae8f905afb5";
*
* datasourceCredential = new DataSourceServicePrincipalInKeyVault&
* .setName&
* .setKeyVaultForDataSourceSecrets&
* .setTenantId&
* .setSecretNameForDataSourceClientId&
* .setSecretNameForDataSourceClientSecret&
*
* metricsAdvisorAdminAsyncClient.createDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.createDataSourceCredentialWithResponse
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the created {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> createDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential) {
try {
return withContext(context -> createDataSourceCredentialWithResponse(dataSourceCredential,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataSourceCredentialEntity>> createDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential,
Context context) {
Objects.requireNonNull(dataSourceCredential, "dataSourceCredential is required");
final DataSourceCredential
innerDataSourceCredential = DataSourceCredentialEntityTransforms.toInnerForCreate(dataSourceCredential);
return service.createCredentialWithResponseAsync(innerDataSourceCredential, context)
.doOnSubscribe(ignoredValue -> logger.info("Creating DataSourceCredentialEntity"))
.doOnSuccess(response -> logger.info("Created DataSourceCredentialEntity"))
.doOnError(error -> logger.warning("Failed to create DataSourceCredentialEntity", error))
.flatMap(response -> {
final String credentialId
= Utility.parseOperationId(response.getDeserializedHeaders().getLocation());
return this.getDataSourceCredentialWithResponse(credentialId, context)
.map(configurationResponse -> new ResponseBase<Void, DataSourceCredentialEntity>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Update a data source credential entity.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredential
* <pre>
* String credentialId = "";
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .flatMap&
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV = null;
* if &
* actualCredentialSPInKV = &
* &
* return metricsAdvisorAdminAsyncClient.updateDataSourceCredential&
* actualCredentialSPInKV.setDescription&
* &
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getDescription&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredential
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the updated {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> updateDataSourceCredential(
DataSourceCredentialEntity dataSourceCredential) {
return updateDataSourceCredentialWithResponse(dataSourceCredential)
.map(Response::getValue);
}
/**
* Update a data source credential entity with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredentialWithResponse
* <pre>
* String credentialId = "";
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .flatMap&
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV = null;
* if &
* actualCredentialSPInKV = &
* &
* return metricsAdvisorAdminAsyncClient.updateDataSourceCredentialWithResponse&
* actualCredentialSPInKV.setDescription&
* &
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getDescription&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.updateDataSourceCredentialWithResponse
*
* @param dataSourceCredential The credential entity.
* @return A {@link Mono} containing the updated {@link DataSourceCredentialEntity}.
* @throws NullPointerException thrown if the {@code credentialEntity} is null
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> updateDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential) {
try {
return withContext(context -> updateDataSourceCredentialWithResponse(dataSourceCredential,
context));
} catch (RuntimeException e) {
return FluxUtil.monoError(logger, e);
}
}
Mono<Response<DataSourceCredentialEntity>> updateDataSourceCredentialWithResponse(
DataSourceCredentialEntity dataSourceCredential,
Context context) {
Objects.requireNonNull(dataSourceCredential, "dataSourceCredential is required");
final DataSourceCredentialPatch
innerDataSourceCredential = DataSourceCredentialEntityTransforms.toInnerForUpdate(dataSourceCredential);
return service.updateCredentialWithResponseAsync(UUID.fromString(dataSourceCredential.getId()),
innerDataSourceCredential,
context)
.doOnSubscribe(ignoredValue -> logger.info("Updating DataSourceCredentialEntity"))
.doOnSuccess(response -> logger.info("Updated DataSourceCredentialEntity"))
.doOnError(error -> logger.warning("Failed to update DataSourceCredentialEntity", error))
.flatMap(response -> {
return this.getDataSourceCredentialWithResponse(dataSourceCredential.getId(), context)
.map(configurationResponse -> new ResponseBase<Void, DataSourceCredentialEntity>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
configurationResponse.getValue(),
null));
});
}
/**
* Get a data source credential entity by its id.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredential
* <pre>
* final String datasourceCredentialId = "f45668b2-bffa-11eb-8529-0246ac130003";
*
* metricsAdvisorAdminAsyncClient.getDataSourceCredential&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredential
*
* @param credentialId The data source credential entity unique id.
*
* @return The data source credential entity for the provided id.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DataSourceCredentialEntity> getDataSourceCredential(String credentialId) {
return getDataSourceCredentialWithResponse(credentialId).flatMap(FluxUtil::toMono);
}
/**
* Get a data source credential entity by its id with REST response.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredentialWithResponse
* <pre>
* final String datasourceCredentialId = "f45668b2-bffa-11eb-8529-0246ac130003";
*
* metricsAdvisorAdminAsyncClient.getDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* credentialEntityWithResponse.getStatusCode&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.getDataSourceCredentialWithResponse
*
* @param credentialId The data source credential entity unique id.
*
* @return The data source credential entity for the provided id.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DataSourceCredentialEntity>> getDataSourceCredentialWithResponse(
String credentialId) {
try {
return withContext(context -> getDataSourceCredentialWithResponse(credentialId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DataSourceCredentialEntity>> getDataSourceCredentialWithResponse(String credentialId,
Context context) {
Objects.requireNonNull(credentialId, "'credentialId' cannot be null.");
return service.getCredentialWithResponseAsync(UUID.fromString(credentialId), context)
.map(response -> new SimpleResponse<>(response,
DataSourceCredentialEntityTransforms.fromInner(response.getValue())));
}
/**
* Deletes the data source credential entity identified by {@code credentialId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredential
* <pre>
* final String datasourceCredentialId = "t00853f1-9080-447f-bacf-8dccf2e86f";
* metricsAdvisorAdminAsyncClient.deleteDataFeed&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredential
*
* @param credentialId The data source credential entity id.
*
* @return An empty Mono.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteDataSourceCredential(String credentialId) {
return deleteDataSourceCredentialWithResponse(credentialId).flatMap(FluxUtil::toMono);
}
/**
* Deletes the data source credential entity identified by {@code credentialId}.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredentialWithResponse
* <pre>
* final String datasourceCredentialId = "eh0854f1-8927-447f-bacf-8dccf2e86fwe";
* metricsAdvisorAdminAsyncClient.deleteDataSourceCredentialWithResponse&
* .subscribe&
* System.out.printf&
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.deleteDataSourceCredentialWithResponse
*
* @param credentialId The data source credential entity id.
*
* @return A response containing status code and headers returned after the operation.
* @throws IllegalArgumentException If {@code credentialId} does not conform to the
* UUID format specification.
* @throws NullPointerException thrown if the {@code credentialId} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteDataSourceCredentialWithResponse(String credentialId) {
try {
return withContext(context -> deleteDataSourceCredentialWithResponse(credentialId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<Void>> deleteDataSourceCredentialWithResponse(String credentialId, Context context) {
Objects.requireNonNull(credentialId, "'credentialId' is required.");
return service.deleteCredentialWithResponseAsync(UUID.fromString(credentialId),
context)
.doOnSubscribe(ignoredValue -> logger.info("Deleting deleteDataSourceCredentialEntity - {}",
credentialId))
.doOnSuccess(response -> logger.info("Deleted deleteDataSourceCredentialEntity - {}", response))
.doOnError(error -> logger.warning("Failed to delete deleteDataSourceCredentialEntity - {}",
credentialId, error));
}
/**
* List information of all data source credential entities on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials -->
* <pre>
* metricsAdvisorAdminAsyncClient.listDataSourceCredentials&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials -->
*
* @return A {@link PagedFlux} containing information of all the {@link DataSourceCredentialEntity data feeds}
* in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials() {
return listDataSourceCredentials(new ListCredentialEntityOptions());
}
/**
* List information of all data source credential entities on the metrics advisor account.
*
* <p><strong>Code sample</strong></p>
* <!-- src_embed com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials
* <pre>
* metricsAdvisorAdminAsyncClient.listDataSourceCredentials&
* new ListCredentialEntityOptions&
* .setMaxPageSize&
* .subscribe&
* if &
* DataSourceServicePrincipalInKeyVault actualCredentialSPInKV
* = &
* System.out
* .printf&
* actualCredentialSPInKV.getKeyVaultEndpoint&
* System.out.printf&
* actualCredentialSPInKV.getKeyVaultClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientId&
* System.out.printf&
* actualCredentialSPInKV.getSecretNameForDataSourceClientSecret&
* &
* &
* </pre>
* <!-- end com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.listDataSourceCredentials
*
* @param listCredentialEntityOptions The configurable {@link ListCredentialEntityOptions options} to pass for filtering
* the output result.
*
* @return A {@link PagedFlux} containing information of all the {@link DataSourceCredentialEntity data feeds}
* in the account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials(ListCredentialEntityOptions listCredentialEntityOptions) {
try {
return new PagedFlux<>(() ->
withContext(context ->
listCredentialEntitiesSinglePageAsync(listCredentialEntityOptions, context)),
continuationToken ->
withContext(context -> listCredentialEntitiesSNextPageAsync(continuationToken, context)));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
PagedFlux<DataSourceCredentialEntity> listDataSourceCredentials(ListCredentialEntityOptions options,
Context context) {
return new PagedFlux<>(() ->
listCredentialEntitiesSinglePageAsync(options, context),
continuationToken ->
listCredentialEntitiesSNextPageAsync(continuationToken, context));
}
private Mono<PagedResponse<DataSourceCredentialEntity>> listCredentialEntitiesSinglePageAsync(
ListCredentialEntityOptions options, Context context) {
options = options != null ? options : new ListCredentialEntityOptions();
return service.listCredentialsSinglePageAsync(options.getSkip(), options.getMaxPageSize(), context)
.doOnRequest(ignoredValue -> logger.info("Listing information for all data source credentials"))
.doOnSuccess(response -> logger.info("Listed data source credentials {}", response))
.doOnError(error -> logger.warning("Failed to list all data source credential information - {}", error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream()
.map(DataSourceCredentialEntityTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
private Mono<PagedResponse<DataSourceCredentialEntity>> listCredentialEntitiesSNextPageAsync(
String nextPageLink, Context context) {
if (CoreUtils.isNullOrEmpty(nextPageLink)) {
return Mono.empty();
}
return service.listCredentialsNextSinglePageAsync(nextPageLink, context)
.doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink))
.doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink))
.doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink,
error))
.map(res -> new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().stream()
.map(DataSourceCredentialEntityTransforms::fromInner).collect(Collectors.toList()),
res.getContinuationToken(),
null));
}
} |
I would put `sharetokenIntent()` immediately after `credential()` since they are grouped together conceptually and this sample is about that exact grouping. | public void createShareServiceClientWithTokenCredential() {
String shareName = "testshare";
String shareURL = String.format("https:
ShareClient serviceClient = new ShareClientBuilder()
.endpoint(shareURL)
.credential(tokenCredential)
.shareName(shareName)
.shareTokenIntent(ShareTokenIntent.BACKUP)
.buildClient();
} | .buildClient(); | public void createShareServiceClientWithTokenCredential() {
String shareName = "testshare";
String shareURL = String.format("https:
ShareClient serviceClient = new ShareClientBuilder()
.endpoint(shareURL)
.credential(tokenCredential)
.shareTokenIntent(ShareTokenIntent.BACKUP)
.shareName(shareName)
.buildClient();
} | class ReadmeSamples {
private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME");
private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN");
private static final String CONNECTION_STRING = System.getenv("AZURE_CONNECTION_STRING");
private TokenCredential tokenCredential;
ShareServiceClient shareServiceClient = new ShareServiceClientBuilder().buildClient();
ShareClient shareClient = new ShareClientBuilder().buildClient();
ShareDirectoryClient directoryClient = new ShareFileClientBuilder().buildDirectoryClient();
ShareFileClient fileClient = new ShareFileClientBuilder().buildFileClient();
private Logger logger = LoggerFactory.getLogger(ReadmeSamples.class);
public void handleException() {
try {
shareServiceClient.createShare("myShare");
} catch (ShareStorageException e) {
logger.error("Failed to create a share with error code: " + e.getErrorCode());
}
}
public void createShareServiceClient() {
String shareServiceURL = String.format("https:
ShareServiceClient shareServiceClient = new ShareServiceClientBuilder().endpoint(shareServiceURL)
.sasToken(SAS_TOKEN).buildClient();
}
public void createShareClient() {
String shareName = "testshare";
String shareURL = String.format("https:
ShareClient shareClient = new ShareClientBuilder().endpoint(shareURL)
.sasToken(SAS_TOKEN).shareName(shareName).buildClient();
}
public void createShareClientWithConnectionString() {
String shareName = "testshare";
String shareURL = String.format("https:
ShareClient shareClient = new ShareClientBuilder().endpoint(shareURL)
.connectionString(CONNECTION_STRING).shareName(shareName).buildClient();
}
public void createDirectoryClient() {
String shareName = "testshare";
String directoryPath = "directoryPath";
String directoryURL = String.format("https:
ShareDirectoryClient directoryClient = new ShareFileClientBuilder().endpoint(directoryURL)
.sasToken(SAS_TOKEN).shareName(shareName).resourcePath(directoryPath).buildDirectoryClient();
}
public void createFileClient() {
String shareName = "testshare";
String directoryPath = "directoryPath";
String fileName = "fileName";
String fileURL = String.format("https:
ShareFileClient fileClient = new ShareFileClientBuilder().connectionString(CONNECTION_STRING)
.endpoint(fileURL).shareName(shareName).resourcePath(directoryPath + "/" + fileName).buildFileClient();
}
public void createShare() {
String shareName = "testshare";
shareServiceClient.createShare(shareName);
}
public void createSnapshotOnShare() {
String shareName = "testshare";
ShareClient shareClient = shareServiceClient.getShareClient(shareName);
shareClient.createSnapshot();
}
public void createDirectory() {
String dirName = "testdir";
shareClient.createDirectory(dirName);
}
public void createSubDirectory() {
String subDirName = "testsubdir";
directoryClient.createSubdirectory(subDirName);
}
public void createFile() {
String fileName = "testfile";
long maxSize = 1024;
directoryClient.createFile(fileName, maxSize);
}
public void getShareList() {
shareServiceClient.listShares();
}
public void getSubDirectoryAndFileList() {
directoryClient.listFilesAndDirectories();
}
public void getRangeList() {
fileClient.listRanges();
}
public void deleteShare() {
shareClient.delete();
}
public void deleteDirectory() {
String dirName = "testdir";
shareClient.deleteDirectory(dirName);
}
public void deleteSubDirectory() {
String subDirName = "testsubdir";
directoryClient.deleteSubdirectory(subDirName);
}
public void deleteFile() {
String fileName = "testfile";
directoryClient.deleteFile(fileName);
}
public void copyFile() {
String sourceURL = "https:
Duration pollInterval = Duration.ofSeconds(2);
SyncPoller<ShareFileCopyInfo, Void> poller = fileClient.beginCopy(sourceURL, (Map<String, String>) null, pollInterval);
}
public void abortCopyFile() {
fileClient.abortCopy("copyId");
}
public void uploadDataToStorage() {
String uploadText = "default";
InputStream data = new ByteArrayInputStream(uploadText.getBytes(StandardCharsets.UTF_8));
fileClient.upload(data, uploadText.length());
}
public void uploadDataToStorageBiggerThan4MB() {
byte[] data = "Hello, data sample!".getBytes(StandardCharsets.UTF_8);
long chunkSize = ShareFileAsyncClient.FILE_DEFAULT_BLOCK_SIZE;
if (data.length > chunkSize) {
for (int offset = 0; offset < data.length; offset += chunkSize) {
try {
chunkSize = Math.min(data.length - offset, chunkSize);
byte[] subArray = Arrays.copyOfRange(data, offset, (int) (offset + chunkSize));
fileClient.uploadWithResponse(new ByteArrayInputStream(subArray), chunkSize, (long) offset, null, Context.NONE);
} catch (RuntimeException e) {
logger.error("Failed to upload the file", e);
if (Boolean.TRUE.equals(fileClient.exists())) {
fileClient.delete();
}
throw e;
}
}
} else {
fileClient.upload(new ByteArrayInputStream(data), data.length);
}
}
public void uploadFileToStorage() {
String filePath = "${myLocalFilePath}";
fileClient.uploadFromFile(filePath);
}
public void downloadDataFromFileRange() {
ShareFileRange fileRange = new ShareFileRange(0L, 2048L);
OutputStream stream = new ByteArrayOutputStream();
fileClient.downloadWithResponse(stream, fileRange, false, null, Context.NONE);
}
public void downloadFileFromFileRange() {
String filePath = "${myLocalFilePath}";
fileClient.downloadToFile(filePath);
}
public void getShareServiceProperties() {
shareServiceClient.getProperties();
}
public void setShareServiceProperties() {
ShareServiceProperties properties = shareServiceClient.getProperties();
properties.getMinuteMetrics().setEnabled(true).setIncludeApis(true);
properties.getHourMetrics().setEnabled(true).setIncludeApis(true);
shareServiceClient.setProperties(properties);
}
public void setShareMetadata() {
Map<String, String> metadata = Collections.singletonMap("directory", "metadata");
shareClient.setMetadata(metadata);
}
public void getAccessPolicy() {
shareClient.getAccessPolicy();
}
public void setAccessPolicy() {
ShareAccessPolicy accessPolicy = new ShareAccessPolicy().setPermissions("r")
.setStartsOn(OffsetDateTime.now(ZoneOffset.UTC))
.setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10));
ShareSignedIdentifier permission = new ShareSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy);
shareClient.setAccessPolicy(Collections.singletonList(permission));
}
public void getHandleList() {
PagedIterable<HandleItem> handleItems = directoryClient.listHandles(null, true, Duration.ofSeconds(30), Context.NONE);
}
public void forceCloseHandleWithResponse() {
PagedIterable<HandleItem> handleItems = directoryClient.listHandles(null, true, Duration.ofSeconds(30), Context.NONE);
String handleId = handleItems.iterator().next().getHandleId();
directoryClient.forceCloseHandleWithResponse(handleId, Duration.ofSeconds(30), Context.NONE);
}
public void setQuotaOnShare() {
int quotaOnGB = 1;
shareClient.setPropertiesWithResponse(new ShareSetPropertiesOptions().setQuotaInGb(quotaOnGB), null, Context.NONE);
}
public void setFileHttpHeaders() {
ShareFileHttpHeaders httpHeaders = new ShareFileHttpHeaders().setContentType("text/plain");
fileClient.setProperties(1024, httpHeaders, null, null);
}
} | class ReadmeSamples {
private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME");
private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN");
private static final String CONNECTION_STRING = System.getenv("AZURE_CONNECTION_STRING");
private TokenCredential tokenCredential;
ShareServiceClient shareServiceClient = new ShareServiceClientBuilder().buildClient();
ShareClient shareClient = new ShareClientBuilder().buildClient();
ShareDirectoryClient directoryClient = new ShareFileClientBuilder().buildDirectoryClient();
ShareFileClient fileClient = new ShareFileClientBuilder().buildFileClient();
private Logger logger = LoggerFactory.getLogger(ReadmeSamples.class);
public void handleException() {
try {
shareServiceClient.createShare("myShare");
} catch (ShareStorageException e) {
logger.error("Failed to create a share with error code: " + e.getErrorCode());
}
}
public void createShareServiceClient() {
String shareServiceURL = String.format("https:
ShareServiceClient shareServiceClient = new ShareServiceClientBuilder().endpoint(shareServiceURL)
.sasToken(SAS_TOKEN).buildClient();
}
public void createShareClient() {
String shareName = "testshare";
String shareURL = String.format("https:
ShareClient shareClient = new ShareClientBuilder().endpoint(shareURL)
.sasToken(SAS_TOKEN).shareName(shareName).buildClient();
}
public void createShareClientWithConnectionString() {
String shareName = "testshare";
String shareURL = String.format("https:
ShareClient shareClient = new ShareClientBuilder().endpoint(shareURL)
.connectionString(CONNECTION_STRING).shareName(shareName).buildClient();
}
public void createDirectoryClient() {
String shareName = "testshare";
String directoryPath = "directoryPath";
String directoryURL = String.format("https:
ShareDirectoryClient directoryClient = new ShareFileClientBuilder().endpoint(directoryURL)
.sasToken(SAS_TOKEN).shareName(shareName).resourcePath(directoryPath).buildDirectoryClient();
}
public void createFileClient() {
String shareName = "testshare";
String directoryPath = "directoryPath";
String fileName = "fileName";
String fileURL = String.format("https:
ShareFileClient fileClient = new ShareFileClientBuilder().connectionString(CONNECTION_STRING)
.endpoint(fileURL).shareName(shareName).resourcePath(directoryPath + "/" + fileName).buildFileClient();
}
public void createShare() {
String shareName = "testshare";
shareServiceClient.createShare(shareName);
}
public void createSnapshotOnShare() {
String shareName = "testshare";
ShareClient shareClient = shareServiceClient.getShareClient(shareName);
shareClient.createSnapshot();
}
public void createDirectory() {
String dirName = "testdir";
shareClient.createDirectory(dirName);
}
public void createSubDirectory() {
String subDirName = "testsubdir";
directoryClient.createSubdirectory(subDirName);
}
public void createFile() {
String fileName = "testfile";
long maxSize = 1024;
directoryClient.createFile(fileName, maxSize);
}
public void getShareList() {
shareServiceClient.listShares();
}
public void getSubDirectoryAndFileList() {
directoryClient.listFilesAndDirectories();
}
public void getRangeList() {
fileClient.listRanges();
}
public void deleteShare() {
shareClient.delete();
}
public void deleteDirectory() {
String dirName = "testdir";
shareClient.deleteDirectory(dirName);
}
public void deleteSubDirectory() {
String subDirName = "testsubdir";
directoryClient.deleteSubdirectory(subDirName);
}
public void deleteFile() {
String fileName = "testfile";
directoryClient.deleteFile(fileName);
}
public void copyFile() {
String sourceURL = "https:
Duration pollInterval = Duration.ofSeconds(2);
SyncPoller<ShareFileCopyInfo, Void> poller = fileClient.beginCopy(sourceURL, (Map<String, String>) null, pollInterval);
}
public void abortCopyFile() {
fileClient.abortCopy("copyId");
}
public void uploadDataToStorage() {
String uploadText = "default";
InputStream data = new ByteArrayInputStream(uploadText.getBytes(StandardCharsets.UTF_8));
fileClient.upload(data, uploadText.length());
}
public void uploadDataToStorageBiggerThan4MB() {
byte[] data = "Hello, data sample!".getBytes(StandardCharsets.UTF_8);
long chunkSize = ShareFileAsyncClient.FILE_DEFAULT_BLOCK_SIZE;
if (data.length > chunkSize) {
for (int offset = 0; offset < data.length; offset += chunkSize) {
try {
chunkSize = Math.min(data.length - offset, chunkSize);
byte[] subArray = Arrays.copyOfRange(data, offset, (int) (offset + chunkSize));
fileClient.uploadWithResponse(new ByteArrayInputStream(subArray), chunkSize, (long) offset, null, Context.NONE);
} catch (RuntimeException e) {
logger.error("Failed to upload the file", e);
if (Boolean.TRUE.equals(fileClient.exists())) {
fileClient.delete();
}
throw e;
}
}
} else {
fileClient.upload(new ByteArrayInputStream(data), data.length);
}
}
public void uploadFileToStorage() {
String filePath = "${myLocalFilePath}";
fileClient.uploadFromFile(filePath);
}
public void downloadDataFromFileRange() {
ShareFileRange fileRange = new ShareFileRange(0L, 2048L);
OutputStream stream = new ByteArrayOutputStream();
fileClient.downloadWithResponse(stream, fileRange, false, null, Context.NONE);
}
public void downloadFileFromFileRange() {
String filePath = "${myLocalFilePath}";
fileClient.downloadToFile(filePath);
}
public void getShareServiceProperties() {
shareServiceClient.getProperties();
}
public void setShareServiceProperties() {
ShareServiceProperties properties = shareServiceClient.getProperties();
properties.getMinuteMetrics().setEnabled(true).setIncludeApis(true);
properties.getHourMetrics().setEnabled(true).setIncludeApis(true);
shareServiceClient.setProperties(properties);
}
public void setShareMetadata() {
Map<String, String> metadata = Collections.singletonMap("directory", "metadata");
shareClient.setMetadata(metadata);
}
public void getAccessPolicy() {
shareClient.getAccessPolicy();
}
public void setAccessPolicy() {
ShareAccessPolicy accessPolicy = new ShareAccessPolicy().setPermissions("r")
.setStartsOn(OffsetDateTime.now(ZoneOffset.UTC))
.setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10));
ShareSignedIdentifier permission = new ShareSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy);
shareClient.setAccessPolicy(Collections.singletonList(permission));
}
public void getHandleList() {
PagedIterable<HandleItem> handleItems = directoryClient.listHandles(null, true, Duration.ofSeconds(30), Context.NONE);
}
public void forceCloseHandleWithResponse() {
PagedIterable<HandleItem> handleItems = directoryClient.listHandles(null, true, Duration.ofSeconds(30), Context.NONE);
String handleId = handleItems.iterator().next().getHandleId();
directoryClient.forceCloseHandleWithResponse(handleId, Duration.ofSeconds(30), Context.NONE);
}
public void setQuotaOnShare() {
int quotaOnGB = 1;
shareClient.setPropertiesWithResponse(new ShareSetPropertiesOptions().setQuotaInGb(quotaOnGB), null, Context.NONE);
}
public void setFileHttpHeaders() {
ShareFileHttpHeaders httpHeaders = new ShareFileHttpHeaders().setContentType("text/plain");
fileClient.setProperties(1024, httpHeaders, null, null);
}
} |
Why are we overriding the javadoc in the first place? | public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization implementationModels = customization.getPackage("com.azure.storage.file.share.implementation.models");
implementationModels.getClass("FilesAndDirectoriesListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.file.share.implementation.util.FilesAndDirectoriesListSegmentDeserializer.class)");
PackageCustomization models = customization.getPackage("com.azure.storage.file.share.models");
models.getClass("ShareFileRangeList").addAnnotation("@JsonDeserialize(using = ShareFileRangeListDeserializer.class)");
changeJacksonXmlRootElementName(models.getClass("ShareMetrics"), "Metrics");
changeJacksonXmlRootElementName(models.getClass("ShareRetentionPolicy"), "RetentionPolicy");
changeJacksonXmlRootElementName(models.getClass("ShareSignedIdentifier"), "SignedIdentifier");
changeJacksonXmlRootElementName(models.getClass("ShareAccessPolicy"), "AccessPolicy");
changeJacksonXmlRootElementName(models.getClass("ShareFileHttpHeaders"), "share-file-http-headers");
changeJacksonXmlRootElementName(models.getClass("SourceModifiedAccessConditions"), "source-modified-access-conditions");
ClassCustomization shareTokenIntent = models.getClass("ShareTokenIntent");
shareTokenIntent.getJavadoc().setDescription("The request intent for whether the file should be backed up. " +
"Possible values are: {@link ShareTokenIntent
" meaning that all file/directory ACLs are bypassed and full permissions are granted. User must also have required RBAC permission.");
} | " meaning that all file/directory ACLs are bypassed and full permissions are granted. User must also have required RBAC permission."); | public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization implementationModels = customization.getPackage("com.azure.storage.file.share.implementation.models");
implementationModels.getClass("FilesAndDirectoriesListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.file.share.implementation.util.FilesAndDirectoriesListSegmentDeserializer.class)");
PackageCustomization models = customization.getPackage("com.azure.storage.file.share.models");
models.getClass("ShareFileRangeList").addAnnotation("@JsonDeserialize(using = ShareFileRangeListDeserializer.class)");
changeJacksonXmlRootElementName(models.getClass("ShareMetrics"), "Metrics");
changeJacksonXmlRootElementName(models.getClass("ShareRetentionPolicy"), "RetentionPolicy");
changeJacksonXmlRootElementName(models.getClass("ShareSignedIdentifier"), "SignedIdentifier");
changeJacksonXmlRootElementName(models.getClass("ShareAccessPolicy"), "AccessPolicy");
changeJacksonXmlRootElementName(models.getClass("ShareFileHttpHeaders"), "share-file-http-headers");
changeJacksonXmlRootElementName(models.getClass("SourceModifiedAccessConditions"), "source-modified-access-conditions");
ClassCustomization shareTokenIntent = models.getClass("ShareTokenIntent");
shareTokenIntent.getJavadoc().setDescription("The request intent specifies requests that are intended for " +
"backup/admin type operations, meaning that all file/directory ACLs are bypassed and full permissions are " +
"granted. User must also have required RBAC permission.");
} | class ShareStorageCustomization extends Customization {
@Override
/*
* Uses ClassCustomization.customizeAst to replace the 'localName' value of the JacksonXmlRootElement instead of
* the previous implementation which removed the JacksonXmlRootElement then added it back with the updated
* 'localName'. The previous implementation would occasionally run into an issue where the JacksonXmlRootElement
* import wouldn't be added back, causing a failure in CI when validating that code generation was up-to-date.
*/
@SuppressWarnings("OptionalGetWithoutIsPresent")
private void changeJacksonXmlRootElementName(ClassCustomization classCustomization, String rootElementName) {
classCustomization.customizeAst(ast -> ast.getClassByName(classCustomization.getClassName()).get()
.getAnnotationByName("JacksonXmlRootElement").get()
.asNormalAnnotationExpr()
.setPairs(new NodeList<>(new MemberValuePair("localName", new StringLiteralExpr(rootElementName)))));
}
} | class ShareStorageCustomization extends Customization {
@Override
/*
* Uses ClassCustomization.customizeAst to replace the 'localName' value of the JacksonXmlRootElement instead of
* the previous implementation which removed the JacksonXmlRootElement then added it back with the updated
* 'localName'. The previous implementation would occasionally run into an issue where the JacksonXmlRootElement
* import wouldn't be added back, causing a failure in CI when validating that code generation was up-to-date.
*/
@SuppressWarnings("OptionalGetWithoutIsPresent")
private void changeJacksonXmlRootElementName(ClassCustomization classCustomization, String rootElementName) {
classCustomization.customizeAst(ast -> ast.getClassByName(classCustomization.getClassName()).get()
.getAnnotationByName("JacksonXmlRootElement").get()
.asNormalAnnotationExpr()
.setPairs(new NodeList<>(new MemberValuePair("localName", new StringLiteralExpr(rootElementName)))));
}
} |
I added more description since before it was just "Defines values for ShareTokenIntent." I thought this wasn't descriptive enough for the user to understand what ShareTokenIntent is for. Do you think it would be better to remove the description from the ShareTokenIntent class and have the description describing the behavior in the client builders? | public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization implementationModels = customization.getPackage("com.azure.storage.file.share.implementation.models");
implementationModels.getClass("FilesAndDirectoriesListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.file.share.implementation.util.FilesAndDirectoriesListSegmentDeserializer.class)");
PackageCustomization models = customization.getPackage("com.azure.storage.file.share.models");
models.getClass("ShareFileRangeList").addAnnotation("@JsonDeserialize(using = ShareFileRangeListDeserializer.class)");
changeJacksonXmlRootElementName(models.getClass("ShareMetrics"), "Metrics");
changeJacksonXmlRootElementName(models.getClass("ShareRetentionPolicy"), "RetentionPolicy");
changeJacksonXmlRootElementName(models.getClass("ShareSignedIdentifier"), "SignedIdentifier");
changeJacksonXmlRootElementName(models.getClass("ShareAccessPolicy"), "AccessPolicy");
changeJacksonXmlRootElementName(models.getClass("ShareFileHttpHeaders"), "share-file-http-headers");
changeJacksonXmlRootElementName(models.getClass("SourceModifiedAccessConditions"), "source-modified-access-conditions");
ClassCustomization shareTokenIntent = models.getClass("ShareTokenIntent");
shareTokenIntent.getJavadoc().setDescription("The request intent for whether the file should be backed up. " +
"Possible values are: {@link ShareTokenIntent
" meaning that all file/directory ACLs are bypassed and full permissions are granted. User must also have required RBAC permission.");
} | " meaning that all file/directory ACLs are bypassed and full permissions are granted. User must also have required RBAC permission."); | public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization implementationModels = customization.getPackage("com.azure.storage.file.share.implementation.models");
implementationModels.getClass("FilesAndDirectoriesListSegment").addAnnotation("@JsonDeserialize(using = com.azure.storage.file.share.implementation.util.FilesAndDirectoriesListSegmentDeserializer.class)");
PackageCustomization models = customization.getPackage("com.azure.storage.file.share.models");
models.getClass("ShareFileRangeList").addAnnotation("@JsonDeserialize(using = ShareFileRangeListDeserializer.class)");
changeJacksonXmlRootElementName(models.getClass("ShareMetrics"), "Metrics");
changeJacksonXmlRootElementName(models.getClass("ShareRetentionPolicy"), "RetentionPolicy");
changeJacksonXmlRootElementName(models.getClass("ShareSignedIdentifier"), "SignedIdentifier");
changeJacksonXmlRootElementName(models.getClass("ShareAccessPolicy"), "AccessPolicy");
changeJacksonXmlRootElementName(models.getClass("ShareFileHttpHeaders"), "share-file-http-headers");
changeJacksonXmlRootElementName(models.getClass("SourceModifiedAccessConditions"), "source-modified-access-conditions");
ClassCustomization shareTokenIntent = models.getClass("ShareTokenIntent");
shareTokenIntent.getJavadoc().setDescription("The request intent specifies requests that are intended for " +
"backup/admin type operations, meaning that all file/directory ACLs are bypassed and full permissions are " +
"granted. User must also have required RBAC permission.");
} | class ShareStorageCustomization extends Customization {
@Override
/*
* Uses ClassCustomization.customizeAst to replace the 'localName' value of the JacksonXmlRootElement instead of
* the previous implementation which removed the JacksonXmlRootElement then added it back with the updated
* 'localName'. The previous implementation would occasionally run into an issue where the JacksonXmlRootElement
* import wouldn't be added back, causing a failure in CI when validating that code generation was up-to-date.
*/
@SuppressWarnings("OptionalGetWithoutIsPresent")
private void changeJacksonXmlRootElementName(ClassCustomization classCustomization, String rootElementName) {
classCustomization.customizeAst(ast -> ast.getClassByName(classCustomization.getClassName()).get()
.getAnnotationByName("JacksonXmlRootElement").get()
.asNormalAnnotationExpr()
.setPairs(new NodeList<>(new MemberValuePair("localName", new StringLiteralExpr(rootElementName)))));
}
} | class ShareStorageCustomization extends Customization {
@Override
/*
* Uses ClassCustomization.customizeAst to replace the 'localName' value of the JacksonXmlRootElement instead of
* the previous implementation which removed the JacksonXmlRootElement then added it back with the updated
* 'localName'. The previous implementation would occasionally run into an issue where the JacksonXmlRootElement
* import wouldn't be added back, causing a failure in CI when validating that code generation was up-to-date.
*/
@SuppressWarnings("OptionalGetWithoutIsPresent")
private void changeJacksonXmlRootElementName(ClassCustomization classCustomization, String rootElementName) {
classCustomization.customizeAst(ast -> ast.getClassByName(classCustomization.getClassName()).get()
.getAnnotationByName("JacksonXmlRootElement").get()
.asNormalAnnotationExpr()
.setPairs(new NodeList<>(new MemberValuePair("localName", new StringLiteralExpr(rootElementName)))));
}
} |
Any reason to reduce the number? 50 would definitely will have second page of response, I remember the number around 28 ish | public void listConfigurationSettingsWithPagination(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 13;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
settings.add(new ConfigurationSetting().setKey(keyPrefix + "-" + value).setValue("myValue").setLabel(labelPrefix));
}
for (ConfigurationSetting setting : settings) {
StepVerifier.create(client.setConfigurationSetting(setting)).expectNextCount(1).verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix + "-*").setLabelFilter(labelPrefix);
StepVerifier.create(client.listConfigurationSettings(filter))
.expectNextCount(numberExpected)
.verifyComplete();
} | final int numberExpected = 13; | public void listConfigurationSettingsWithPagination(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
settings.add(new ConfigurationSetting().setKey(keyPrefix + "-" + value).setValue("myValue").setLabel(labelPrefix));
}
for (ConfigurationSetting setting : settings) {
StepVerifier.create(client.setConfigurationSetting(setting)).expectNextCount(1).verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix + "-*").setLabelFilter(labelPrefix);
StepVerifier.create(client.listConfigurationSettings(filter))
.expectNextCount(numberExpected)
.verifyComplete();
} | class ConfigurationAsyncClientTest extends ConfigurationClientTestBase {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class);
private static final String NO_LABEL = null;
private ConfigurationAsyncClient client;
@Override
protected String getTestName() {
return "";
}
@Override
protected void beforeTest() {
beforeTestSetup();
}
@Override
protected void afterTest() {
logger.info("Cleaning up created key values.");
client.listConfigurationSettings(new SettingSelector().setKeyFilter(keyPrefix + "*"))
.flatMap(configurationSetting -> {
logger.info("Deleting key:label [{}:{}]. isReadOnly? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isReadOnly());
Mono<Response<ConfigurationSetting>> unlock = configurationSetting.isReadOnly() ? client.setReadOnlyWithResponse(configurationSetting, false) : Mono.empty();
return unlock.then(client.deleteConfigurationSettingWithResponse(configurationSetting, false));
})
.blockLast();
logger.info("Finished cleaning up values.");
}
private ConfigurationAsyncClient getConfigurationAsyncClient(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
return clientSetup(credentials -> {
ConfigurationClientBuilder builder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.httpClient(buildAsyncAssertingClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient))
.serviceVersion(serviceVersion)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
if (interceptorManager.isRecordMode()) {
builder
.addPolicy(interceptorManager.getRecordPolicy())
.addPolicy(new RetryPolicy());
} else if (interceptorManager.isPlaybackMode()) {
interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("Sync-Token"))));
}
return builder.buildAsyncClient();
});
}
private HttpClient buildAsyncAssertingClient(HttpClient httpClient) {
BiFunction<HttpRequest, com.azure.core.util.Context, Boolean> skipRequestFunction = (request, context) -> {
String callerMethod = (String) context.getData("caller-method").orElse("");
return callerMethod.contains("list");
};
return new AssertingHttpClientBuilder(httpClient)
.skipRequest(skipRequestFunction)
.assertAsync()
.build();
}
/**
* Tests that a configuration is able to be added, these are differentiate from each other using a key or key-label
* identifier.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingRunner((expected) ->
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingConvenience(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addFeatureFlagConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addSecretReferenceConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that we cannot add a configuration setting when the key is an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingEmptyKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.addConfigurationSetting("", null, "A value"))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD));
}
/**
* Tests that we can add configuration settings when value is not null or an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingEmptyValue(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingEmptyValueRunner((setting) -> {
StepVerifier.create(client.addConfigurationSetting(setting.getKey(), setting.getLabel(), setting.getValue()))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(setting.getKey(), setting.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
});
}
/**
* Verifies that an exception is thrown when null key is passed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.addConfigurationSetting(null, null, "A Value"))
.expectError(IllegalArgumentException.class)
.verify();
StepVerifier.create(client.addConfigurationSettingWithResponse(null))
.expectError(NullPointerException.class)
.verify();
}
/**
* Tests that a configuration cannot be added twice with the same key. This should return a 412 error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addExistingSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addExistingSettingRunner((expected) ->
StepVerifier.create(
client.addConfigurationSettingWithResponse(expected)
.then(
client.addConfigurationSettingWithResponse(expected)))
.verifyErrorSatisfies(ex -> assertRestException(ex,
HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED)));
}
/**
* Tests that a configuration is able to be added or updated with set.
* When the configuration is read-only updates cannot happen, this will result in a 409.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingRunner((expected, update) ->
StepVerifier.create(client.setConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setFeatureFlagConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(
expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setSecretReferenceConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(
expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that when an ETag is passed to set it will only set if the current representation of the setting has the
* ETag. If the set ETag doesn't match anything the update won't happen, this will result in a 412. This will
* prevent set from doing an add as well.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingIfETag(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingIfETagRunner((initial, update) -> {
StepVerifier.create(client.setConfigurationSettingWithResponse(initial.setETag("badEtag"), true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
final String etag = client.addConfigurationSettingWithResponse(initial).block().getValue().getETag();
StepVerifier.create(client.setConfigurationSettingWithResponse(update.setETag(etag), true))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(initial, true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
StepVerifier.create(client.getConfigurationSettingWithResponse(update, null, false))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
});
}
/**
* Tests that we cannot set a configuration setting when the key is an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingEmptyKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.setConfigurationSetting("", NO_LABEL, "A value"))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD));
}
/**
* Tests that we can set configuration settings when value is not null or an empty string.
* Value is not a required property.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingEmptyValue(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingEmptyValueRunner((setting) -> {
StepVerifier.create(client.setConfigurationSetting(setting.getKey(), NO_LABEL, setting.getValue()))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(setting.getKey(), setting.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
});
}
/**
* Verifies that an exception is thrown when null key is passed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.setConfigurationSetting(null, NO_LABEL, "A Value"))
.verifyError(IllegalArgumentException.class);
StepVerifier.create(client.setConfigurationSettingWithResponse(null, false))
.verifyError(NullPointerException.class);
}
/**
* Tests that a configuration is able to be retrieved when it exists, whether or not it is read-only.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getConfigurationSettingRunner((expected) ->
StepVerifier.create(
client.addConfigurationSettingWithResponse(expected)
.then(client.getConfigurationSettingWithResponse(expected, null, false)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingConvenience(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getFeatureFlagConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getSecretReferenceConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that attempting to retrieve a non-existent configuration doesn't work, this will result in a 404.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingNotFound(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting neverRetrievedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverRetreivedValue");
final ConfigurationSetting nonExistentLabel = new ConfigurationSetting().setKey(key).setLabel("myNonExistentLabel");
StepVerifier.create(client.addConfigurationSettingWithResponse(neverRetrievedConfiguration))
.assertNext(response -> assertConfigurationEquals(neverRetrievedConfiguration, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting("myNonExistentKey", null, null))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
StepVerifier.create(client.getConfigurationSettingWithResponse(nonExistentLabel, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that configurations are able to be deleted when they exist.
* After the configuration has been deleted attempting to get it will result in a 404, the same as if the
* configuration never existed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected).then(client.getConfigurationSettingWithResponse(expected, null, false)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(expected, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteFeatureFlagConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteSecretReferenceConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
/**
* Tests that attempting to delete a non-existent configuration will return a 204.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingNotFound(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting neverDeletedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverDeletedValue");
StepVerifier.create(client.addConfigurationSettingWithResponse(neverDeletedConfiguration))
.assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(new ConfigurationSetting().setKey("myNonExistentKey"), false))
.assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(new ConfigurationSetting().setKey(neverDeletedConfiguration.getKey()).setLabel("myNonExistentLabel"), false))
.assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(neverDeletedConfiguration.getKey(), neverDeletedConfiguration.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response))
.verifyComplete();
}
/**
* Tests that when an ETag is passed to delete it will only delete if the current representation of the setting has the ETag.
* If the delete ETag doesn't match anything the delete won't happen, this will result in a 412.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingWithETag(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingWithETagRunner((initial, update) -> {
final ConfigurationSetting initiallyAddedConfig = client.addConfigurationSettingWithResponse(initial).block().getValue();
final ConfigurationSetting updatedConfig = client.setConfigurationSettingWithResponse(update, true).block().getValue();
StepVerifier.create(client.getConfigurationSettingWithResponse(initial, null, false))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(initiallyAddedConfig, true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
StepVerifier.create(client.deleteConfigurationSettingWithResponse(updatedConfig, true))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(initial, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
/**
* Test the API will not make a delete call without having a key passed, an IllegalArgumentException should be thrown.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.deleteConfigurationSetting(null, null))
.verifyError(IllegalArgumentException.class);
StepVerifier.create(client.deleteConfigurationSettingWithResponse(null, false))
.verifyError(NullPointerException.class);
}
/**
* Tests assert that the setting can be deleted after clear read-only of the setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnly(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
/**
* Tests assert that the setting can be deleted after clear read-only of the setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnlyWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockFeatureFlagRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockSecretReferenceRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
});
}
/**
* Verifies that a ConfigurationSetting can be added with a label, and that we can fetch that ConfigurationSetting
* from the service when filtering by either its label or just its key.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithKeyAndLabel(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String value = "myValue";
final String key = testResourceNamer.randomName(keyPrefix, 16);
final String label = testResourceNamer.randomName("lbl", 8);
final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue(value).setLabel(label);
StepVerifier.create(client.setConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key).setLabelFilter(label)))
.assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key)))
.assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting))
.verifyComplete();
}
/**
* Verifies that ConfigurationSettings can be added and that we can fetch those ConfigurationSettings from the
* service when filtering by their keys.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithMultipleKeys(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String key2 = getKey();
listWithMultipleKeysRunner(key, key2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key + "," + key2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
@Disabled("This was failing even before re-record with Test Proxy")
public void listConfigurationSettingsWithNullSelector(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final String key2 = getKey();
StepVerifier.create(
client.listConfigurationSettings(null)
.flatMap(setting -> client.deleteConfigurationSettingWithResponse(setting, false))
.then())
.verifyComplete();
listWithMultipleKeysRunner(key, key2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(null))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
assertEquals(2, selected.size());
return selected;
});
}
/**
* Verifies that ConfigurationSettings can be added with different labels and that we can fetch those ConfigurationSettings
* from the service when filtering by their labels.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithMultipleLabels(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String label = getLabel();
String label2 = getLabel();
listWithMultipleLabelsRunner(key, label, label2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key).setLabelFilter(label + "," + label2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can select filter results by key, label, and select fields using SettingSelector.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFields(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
listConfigurationSettingsSelectFieldsRunner((settings, selector) -> {
final List<Mono<Response<ConfigurationSetting>>> settingsBeingAdded = new ArrayList<>();
for (ConfigurationSetting setting : settings) {
settingsBeingAdded.add(client.setConfigurationSettingWithResponse(setting, false));
}
Flux.merge(settingsBeingAdded).blockLast();
List<ConfigurationSetting> settingsReturned = new ArrayList<>();
StepVerifier.create(client.listConfigurationSettings(selector))
.assertNext(settingsReturned::add)
.assertNext(settingsReturned::add)
.verifyComplete();
return settingsReturned;
});
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a key filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithPrefixStarKeyFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest("*" + getKey(), getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a* key filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithSubstringKeyFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest("*" + getKey() + "*", getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a label filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithPrefixStarLabelFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest(getKey(), "*" + getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a* label filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithSubstringLabelFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest(getKey(), "*" + getLabel() + "*");
}
/**
* Verifies that we can get a ConfigurationSetting at the provided accept datetime
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsAcceptDateTime(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2)))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
List<ConfigurationSetting> revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).collectList().block();
assertNotNull(revisions);
assertEquals(3, revisions.size());
SettingSelector options = new SettingSelector().setKeyFilter(keyName).setAcceptDatetime(revisions.get(1).getLastModified());
StepVerifier.create(client.listConfigurationSettings(options))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
}
/**
* Verifies that we can get all of the revisions for this ConfigurationSetting. Then verifies that we can select
* specific fields.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisions(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(keyName)))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.assertNext(response -> assertConfigurationEquals(updated, response))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(keyName).setFields(SettingFields.KEY, SettingFields.ETAG)))
.assertNext(response -> validateListRevisions(updated2, response))
.assertNext(response -> validateListRevisions(updated, response))
.assertNext(response -> validateListRevisions(original, response))
.verifyComplete();
assertTrue(client.listRevisions(null).toStream().collect(Collectors.toList()).size() > 0);
}
/**
* Verifies that we can get all the revisions for all settings with the specified keys.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithMultipleKeys(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String key2 = getKey();
listRevisionsWithMultipleKeysRunner(key, key2, (testInput) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(0)))
.assertNext(response -> assertConfigurationEquals(testInput.get(0), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(1), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(1), response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(2)))
.assertNext(response -> assertConfigurationEquals(testInput.get(2), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(3), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(3), response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(key + "," + key2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can get all revisions for all settings with the specified labels.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithMultipleLabels(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String label = getLabel();
String label2 = getLabel();
listRevisionsWithMultipleLabelsRunner(key, label, label2, (testInput) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(0)))
.assertNext(response -> assertConfigurationEquals(testInput.get(0), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(1), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(1), response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(2)))
.assertNext(response -> assertConfigurationEquals(testInput.get(2), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(3), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(3), response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(key).setLabelFilter(label + "," + label2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can get a subset of revisions based on the "acceptDateTime"
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsAcceptDateTime(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2)))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
List<ConfigurationSetting> revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).collectList().block();
assertNotNull(revisions);
assertEquals(3, revisions.size());
SettingSelector options = new SettingSelector().setKeyFilter(keyName)
.setAcceptDatetime(revisions.get(1).getLastModified());
StepVerifier.create(client.listRevisions(options))
.assertNext(response -> assertConfigurationEquals(updated, response))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPagination(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
settings.add(new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix));
}
for (ConfigurationSetting setting : settings) {
StepVerifier.create(client.setConfigurationSetting(setting))
.expectNextCount(1)
.verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
StepVerifier.create(client.listRevisions(filter))
.expectNextCount(numberExpected)
.verifyComplete();
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times.
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPaginationAndRepeatStream(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix);
settings.add(setting);
StepVerifier.create(client.setConfigurationSetting(setting))
.expectNextCount(1)
.verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>();
List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>();
PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listRevisions(filter);
configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList1.size());
configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList2.size());
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times.
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPaginationAndRepeatIterator(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix);
settings.add(setting);
StepVerifier.create(client.setConfigurationSetting(setting)).expectNextCount(1).verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>();
List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>();
PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listRevisions(filter);
configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList1.size());
configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList2.size());
}
/**
* Verifies that, given a ton of existing settings, we can list the ConfigurationSettings using pagination
* (ie. where 'nextLink' has a URL pointing to the next page of results.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
/**
* Verifies the conditional "GET" scenario where the setting has yet to be updated, resulting in a 304. This GET
* scenario will return a setting when the ETag provided does not match the one of the current setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingWhenValueNotUpdated(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue("myValue");
final ConfigurationSetting newExpected = new ConfigurationSetting().setKey(key).setValue("myNewValue");
final ConfigurationSetting block = client.addConfigurationSettingWithResponse(expected).block().getValue();
assertNotNull(block);
assertConfigurationEquals(expected, block);
StepVerifier.create(client.getConfigurationSettingWithResponse(block, null, true))
.assertNext(response -> assertConfigurationEquals(null, response, 304))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(newExpected, false))
.assertNext(response -> assertConfigurationEquals(newExpected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(block, null, true))
.assertNext(response -> assertConfigurationEquals(newExpected, response))
.verifyComplete();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
@Disabled
public void deleteAllSettings(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
client.listConfigurationSettings(new SettingSelector().setKeyFilter("*"))
.flatMap(configurationSetting -> {
logger.info("Deleting key:label [{}:{}]. isReadOnly? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isReadOnly());
return client.deleteConfigurationSettingWithResponse(configurationSetting, false);
}).blockLast();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addHeadersFromContextPolicyTest(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final HttpHeaders headers = getCustomizedHeaders();
addHeadersFromContextPolicyRunner(expected ->
StepVerifier.create(client.addConfigurationSettingWithResponse(expected)
.contextWrite(Context.of(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers)))
.assertNext(response -> {
final HttpHeaders requestHeaders = response.getRequest().getHeaders();
assertContainsHeaders(headers, requestHeaders);
})
.verifyComplete());
}
/**
* Test helper that calling list configuration setting with given key and label input
*
* @param keyFilter key filter expression
* @param labelFilter label filter expression
*/
private void filterValueTest(String keyFilter, String labelFilter) {
listConfigurationSettingsSelectFieldsWithNotSupportedFilterRunner(keyFilter, labelFilter, selector ->
StepVerifier.create(client.listConfigurationSettings(selector))
.verifyError(HttpResponseException.class));
}
} | class ConfigurationAsyncClientTest extends ConfigurationClientTestBase {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class);
private static final String NO_LABEL = null;
private ConfigurationAsyncClient client;
@Override
protected String getTestName() {
return "";
}
@Override
protected void beforeTest() {
beforeTestSetup();
}
@Override
protected void afterTest() {
logger.info("Cleaning up created key values.");
client.listConfigurationSettings(new SettingSelector().setKeyFilter(keyPrefix + "*"))
.flatMap(configurationSetting -> {
logger.info("Deleting key:label [{}:{}]. isReadOnly? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isReadOnly());
Mono<Response<ConfigurationSetting>> unlock = configurationSetting.isReadOnly() ? client.setReadOnlyWithResponse(configurationSetting, false) : Mono.empty();
return unlock.then(client.deleteConfigurationSettingWithResponse(configurationSetting, false));
})
.blockLast();
logger.info("Finished cleaning up values.");
}
private ConfigurationAsyncClient getConfigurationAsyncClient(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
return clientSetup(credentials -> {
ConfigurationClientBuilder builder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.serviceVersion(serviceVersion)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
setHttpClient(httpClient, builder);
if (interceptorManager.isRecordMode()) {
builder
.addPolicy(interceptorManager.getRecordPolicy())
.addPolicy(new RetryPolicy());
} else if (interceptorManager.isPlaybackMode()) {
interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("Sync-Token"))));
}
return builder.buildAsyncClient();
});
}
private ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) {
if (interceptorManager.isRecordMode()) {
return builder
.httpClient(buildAsyncAssertingClient(httpClient));
} else if (interceptorManager.isPlaybackMode()) {
return builder
.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient()));
}
return builder;
}
private HttpClient buildAsyncAssertingClient(HttpClient httpClient) {
BiFunction<HttpRequest, com.azure.core.util.Context, Boolean> skipRequestFunction = (request, context) -> {
String callerMethod = (String) context.getData("caller-method").orElse("");
return callerMethod.contains("list");
};
return new AssertingHttpClientBuilder(httpClient)
.skipRequest(skipRequestFunction)
.assertAsync()
.build();
}
/**
* Tests that a configuration is able to be added, these are differentiate from each other using a key or key-label
* identifier.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingRunner((expected) ->
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingConvenience(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addFeatureFlagConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addSecretReferenceConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that we cannot add a configuration setting when the key is an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingEmptyKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.addConfigurationSetting("", null, "A value"))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD));
}
/**
* Tests that we can add configuration settings when value is not null or an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingEmptyValue(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingEmptyValueRunner((setting) -> {
StepVerifier.create(client.addConfigurationSetting(setting.getKey(), setting.getLabel(), setting.getValue()))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(setting.getKey(), setting.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
});
}
/**
* Verifies that an exception is thrown when null key is passed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.addConfigurationSetting(null, null, "A Value"))
.expectError(IllegalArgumentException.class)
.verify();
StepVerifier.create(client.addConfigurationSettingWithResponse(null))
.expectError(NullPointerException.class)
.verify();
}
/**
* Tests that a configuration cannot be added twice with the same key. This should return a 412 error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addExistingSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addExistingSettingRunner((expected) ->
StepVerifier.create(
client.addConfigurationSettingWithResponse(expected)
.then(
client.addConfigurationSettingWithResponse(expected)))
.verifyErrorSatisfies(ex -> assertRestException(ex,
HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED)));
}
/**
* Tests that a configuration is able to be added or updated with set.
* When the configuration is read-only updates cannot happen, this will result in a 409.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingRunner((expected, update) ->
StepVerifier.create(client.setConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setFeatureFlagConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(
expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setSecretReferenceConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(
expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that when an ETag is passed to set it will only set if the current representation of the setting has the
* ETag. If the set ETag doesn't match anything the update won't happen, this will result in a 412. This will
* prevent set from doing an add as well.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingIfETag(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingIfETagRunner((initial, update) -> {
StepVerifier.create(client.setConfigurationSettingWithResponse(initial.setETag("badEtag"), true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
final String etag = client.addConfigurationSettingWithResponse(initial).block().getValue().getETag();
StepVerifier.create(client.setConfigurationSettingWithResponse(update.setETag(etag), true))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(initial, true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
StepVerifier.create(client.getConfigurationSettingWithResponse(update, null, false))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
});
}
/**
* Tests that we cannot set a configuration setting when the key is an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingEmptyKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.setConfigurationSetting("", NO_LABEL, "A value"))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD));
}
/**
* Tests that we can set configuration settings when value is not null or an empty string.
* Value is not a required property.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingEmptyValue(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingEmptyValueRunner((setting) -> {
StepVerifier.create(client.setConfigurationSetting(setting.getKey(), NO_LABEL, setting.getValue()))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(setting.getKey(), setting.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
});
}
/**
* Verifies that an exception is thrown when null key is passed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.setConfigurationSetting(null, NO_LABEL, "A Value"))
.verifyError(IllegalArgumentException.class);
StepVerifier.create(client.setConfigurationSettingWithResponse(null, false))
.verifyError(NullPointerException.class);
}
/**
* Tests that a configuration is able to be retrieved when it exists, whether or not it is read-only.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getConfigurationSettingRunner((expected) ->
StepVerifier.create(
client.addConfigurationSettingWithResponse(expected)
.then(client.getConfigurationSettingWithResponse(expected, null, false)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingConvenience(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getFeatureFlagConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getSecretReferenceConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that attempting to retrieve a non-existent configuration doesn't work, this will result in a 404.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingNotFound(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting neverRetrievedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverRetreivedValue");
final ConfigurationSetting nonExistentLabel = new ConfigurationSetting().setKey(key).setLabel("myNonExistentLabel");
StepVerifier.create(client.addConfigurationSettingWithResponse(neverRetrievedConfiguration))
.assertNext(response -> assertConfigurationEquals(neverRetrievedConfiguration, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting("myNonExistentKey", null, null))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
StepVerifier.create(client.getConfigurationSettingWithResponse(nonExistentLabel, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that configurations are able to be deleted when they exist.
* After the configuration has been deleted attempting to get it will result in a 404, the same as if the
* configuration never existed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected).then(client.getConfigurationSettingWithResponse(expected, null, false)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(expected, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteFeatureFlagConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteSecretReferenceConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
/**
* Tests that attempting to delete a non-existent configuration will return a 204.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingNotFound(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting neverDeletedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverDeletedValue");
StepVerifier.create(client.addConfigurationSettingWithResponse(neverDeletedConfiguration))
.assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(new ConfigurationSetting().setKey("myNonExistentKey"), false))
.assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(new ConfigurationSetting().setKey(neverDeletedConfiguration.getKey()).setLabel("myNonExistentLabel"), false))
.assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(neverDeletedConfiguration.getKey(), neverDeletedConfiguration.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response))
.verifyComplete();
}
/**
* Tests that when an ETag is passed to delete it will only delete if the current representation of the setting has the ETag.
* If the delete ETag doesn't match anything the delete won't happen, this will result in a 412.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingWithETag(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingWithETagRunner((initial, update) -> {
final ConfigurationSetting initiallyAddedConfig = client.addConfigurationSettingWithResponse(initial).block().getValue();
final ConfigurationSetting updatedConfig = client.setConfigurationSettingWithResponse(update, true).block().getValue();
StepVerifier.create(client.getConfigurationSettingWithResponse(initial, null, false))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(initiallyAddedConfig, true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
StepVerifier.create(client.deleteConfigurationSettingWithResponse(updatedConfig, true))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(initial, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
/**
* Test the API will not make a delete call without having a key passed, an IllegalArgumentException should be thrown.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.deleteConfigurationSetting(null, null))
.verifyError(IllegalArgumentException.class);
StepVerifier.create(client.deleteConfigurationSettingWithResponse(null, false))
.verifyError(NullPointerException.class);
}
/**
* Tests assert that the setting can be deleted after clear read-only of the setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnly(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
/**
* Tests assert that the setting can be deleted after clear read-only of the setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnlyWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockFeatureFlagRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockSecretReferenceRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
});
}
/**
* Verifies that a ConfigurationSetting can be added with a label, and that we can fetch that ConfigurationSetting
* from the service when filtering by either its label or just its key.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithKeyAndLabel(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String value = "myValue";
final String key = testResourceNamer.randomName(keyPrefix, 16);
final String label = testResourceNamer.randomName("lbl", 8);
final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue(value).setLabel(label);
StepVerifier.create(client.setConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key).setLabelFilter(label)))
.assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key)))
.assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting))
.verifyComplete();
}
/**
* Verifies that ConfigurationSettings can be added and that we can fetch those ConfigurationSettings from the
* service when filtering by their keys.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithMultipleKeys(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String key2 = getKey();
listWithMultipleKeysRunner(key, key2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key + "," + key2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsWithNullSelector(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final String key2 = getKey();
StepVerifier.create(
client.listConfigurationSettings(null)
.flatMap(setting -> client.deleteConfigurationSettingWithResponse(setting, false))
.then())
.verifyComplete();
listWithMultipleKeysRunner(key, key2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(null))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
assertEquals(2, selected.size());
return selected;
});
}
/**
* Verifies that ConfigurationSettings can be added with different labels and that we can fetch those ConfigurationSettings
* from the service when filtering by their labels.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithMultipleLabels(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String label = getLabel();
String label2 = getLabel();
listWithMultipleLabelsRunner(key, label, label2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key).setLabelFilter(label + "," + label2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can select filter results by key, label, and select fields using SettingSelector.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFields(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
listConfigurationSettingsSelectFieldsRunner((settings, selector) -> {
final List<Mono<Response<ConfigurationSetting>>> settingsBeingAdded = new ArrayList<>();
for (ConfigurationSetting setting : settings) {
settingsBeingAdded.add(client.setConfigurationSettingWithResponse(setting, false));
}
Flux.merge(settingsBeingAdded).blockLast();
List<ConfigurationSetting> settingsReturned = new ArrayList<>();
StepVerifier.create(client.listConfigurationSettings(selector))
.assertNext(settingsReturned::add)
.assertNext(settingsReturned::add)
.verifyComplete();
return settingsReturned;
});
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a key filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithPrefixStarKeyFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest("*" + getKey(), getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a* key filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithSubstringKeyFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest("*" + getKey() + "*", getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a label filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithPrefixStarLabelFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest(getKey(), "*" + getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a* label filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithSubstringLabelFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest(getKey(), "*" + getLabel() + "*");
}
/**
* Verifies that we can get a ConfigurationSetting at the provided accept datetime
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsAcceptDateTime(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2)))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
List<ConfigurationSetting> revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).collectList().block();
assertNotNull(revisions);
assertEquals(3, revisions.size());
SettingSelector options = new SettingSelector().setKeyFilter(keyName).setAcceptDatetime(revisions.get(1).getLastModified());
StepVerifier.create(client.listConfigurationSettings(options))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
}
/**
* Verifies that we can get all of the revisions for this ConfigurationSetting. Then verifies that we can select
* specific fields.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisions(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(keyName)))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.assertNext(response -> assertConfigurationEquals(updated, response))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(keyName).setFields(SettingFields.KEY, SettingFields.ETAG)))
.assertNext(response -> validateListRevisions(updated2, response))
.assertNext(response -> validateListRevisions(updated, response))
.assertNext(response -> validateListRevisions(original, response))
.verifyComplete();
assertTrue(client.listRevisions(null).toStream().collect(Collectors.toList()).size() > 0);
}
/**
* Verifies that we can get all the revisions for all settings with the specified keys.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithMultipleKeys(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String key2 = getKey();
listRevisionsWithMultipleKeysRunner(key, key2, (testInput) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(0)))
.assertNext(response -> assertConfigurationEquals(testInput.get(0), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(1), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(1), response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(2)))
.assertNext(response -> assertConfigurationEquals(testInput.get(2), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(3), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(3), response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(key + "," + key2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can get all revisions for all settings with the specified labels.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithMultipleLabels(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String label = getLabel();
String label2 = getLabel();
listRevisionsWithMultipleLabelsRunner(key, label, label2, (testInput) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(0)))
.assertNext(response -> assertConfigurationEquals(testInput.get(0), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(1), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(1), response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(2)))
.assertNext(response -> assertConfigurationEquals(testInput.get(2), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(3), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(3), response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(key).setLabelFilter(label + "," + label2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can get a subset of revisions based on the "acceptDateTime"
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsAcceptDateTime(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2)))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
List<ConfigurationSetting> revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).collectList().block();
assertNotNull(revisions);
assertEquals(3, revisions.size());
SettingSelector options = new SettingSelector().setKeyFilter(keyName)
.setAcceptDatetime(revisions.get(1).getLastModified());
StepVerifier.create(client.listRevisions(options))
.assertNext(response -> assertConfigurationEquals(updated, response))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPagination(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
settings.add(new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix));
}
for (ConfigurationSetting setting : settings) {
StepVerifier.create(client.setConfigurationSetting(setting))
.expectNextCount(1)
.verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
StepVerifier.create(client.listRevisions(filter))
.expectNextCount(numberExpected)
.verifyComplete();
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times.
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPaginationAndRepeatStream(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix);
settings.add(setting);
StepVerifier.create(client.setConfigurationSetting(setting))
.expectNextCount(1)
.verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>();
List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>();
PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listRevisions(filter);
configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList1.size());
configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList2.size());
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times.
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPaginationAndRepeatIterator(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix);
settings.add(setting);
StepVerifier.create(client.setConfigurationSetting(setting)).expectNextCount(1).verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>();
List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>();
PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listRevisions(filter);
configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList1.size());
configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList2.size());
}
/**
* Verifies that, given a ton of existing settings, we can list the ConfigurationSettings using pagination
* (ie. where 'nextLink' has a URL pointing to the next page of results.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
/**
* Verifies the conditional "GET" scenario where the setting has yet to be updated, resulting in a 304. This GET
* scenario will return a setting when the ETag provided does not match the one of the current setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingWhenValueNotUpdated(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue("myValue");
final ConfigurationSetting newExpected = new ConfigurationSetting().setKey(key).setValue("myNewValue");
final ConfigurationSetting block = client.addConfigurationSettingWithResponse(expected).block().getValue();
assertNotNull(block);
assertConfigurationEquals(expected, block);
StepVerifier.create(client.getConfigurationSettingWithResponse(block, null, true))
.assertNext(response -> assertConfigurationEquals(null, response, 304))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(newExpected, false))
.assertNext(response -> assertConfigurationEquals(newExpected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(block, null, true))
.assertNext(response -> assertConfigurationEquals(newExpected, response))
.verifyComplete();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
@Disabled
public void deleteAllSettings(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
client.listConfigurationSettings(new SettingSelector().setKeyFilter("*"))
.flatMap(configurationSetting -> {
logger.info("Deleting key:label [{}:{}]. isReadOnly? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isReadOnly());
return client.deleteConfigurationSettingWithResponse(configurationSetting, false);
}).blockLast();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addHeadersFromContextPolicyTest(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final HttpHeaders headers = getCustomizedHeaders();
addHeadersFromContextPolicyRunner(expected ->
StepVerifier.create(client.addConfigurationSettingWithResponse(expected)
.contextWrite(Context.of(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers)))
.assertNext(response -> {
final HttpHeaders requestHeaders = response.getRequest().getHeaders();
assertContainsHeaders(headers, requestHeaders);
})
.verifyComplete());
}
/**
* Test helper that calling list configuration setting with given key and label input
*
* @param keyFilter key filter expression
* @param labelFilter label filter expression
*/
private void filterValueTest(String keyFilter, String labelFilter) {
listConfigurationSettingsSelectFieldsWithNotSupportedFilterRunner(keyFilter, labelFilter, selector ->
StepVerifier.create(client.listConfigurationSettings(selector))
.verifyError(HttpResponseException.class));
}
} |
That is what the updated record returned and it passes for this number. Any reason not to update this or is it always supposed to be 50? | public void listConfigurationSettingsWithPagination(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 13;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
settings.add(new ConfigurationSetting().setKey(keyPrefix + "-" + value).setValue("myValue").setLabel(labelPrefix));
}
for (ConfigurationSetting setting : settings) {
StepVerifier.create(client.setConfigurationSetting(setting)).expectNextCount(1).verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix + "-*").setLabelFilter(labelPrefix);
StepVerifier.create(client.listConfigurationSettings(filter))
.expectNextCount(numberExpected)
.verifyComplete();
} | final int numberExpected = 13; | public void listConfigurationSettingsWithPagination(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
settings.add(new ConfigurationSetting().setKey(keyPrefix + "-" + value).setValue("myValue").setLabel(labelPrefix));
}
for (ConfigurationSetting setting : settings) {
StepVerifier.create(client.setConfigurationSetting(setting)).expectNextCount(1).verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix + "-*").setLabelFilter(labelPrefix);
StepVerifier.create(client.listConfigurationSettings(filter))
.expectNextCount(numberExpected)
.verifyComplete();
} | class ConfigurationAsyncClientTest extends ConfigurationClientTestBase {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class);
private static final String NO_LABEL = null;
private ConfigurationAsyncClient client;
@Override
protected String getTestName() {
return "";
}
@Override
protected void beforeTest() {
beforeTestSetup();
}
@Override
protected void afterTest() {
logger.info("Cleaning up created key values.");
client.listConfigurationSettings(new SettingSelector().setKeyFilter(keyPrefix + "*"))
.flatMap(configurationSetting -> {
logger.info("Deleting key:label [{}:{}]. isReadOnly? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isReadOnly());
Mono<Response<ConfigurationSetting>> unlock = configurationSetting.isReadOnly() ? client.setReadOnlyWithResponse(configurationSetting, false) : Mono.empty();
return unlock.then(client.deleteConfigurationSettingWithResponse(configurationSetting, false));
})
.blockLast();
logger.info("Finished cleaning up values.");
}
private ConfigurationAsyncClient getConfigurationAsyncClient(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
return clientSetup(credentials -> {
ConfigurationClientBuilder builder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.httpClient(buildAsyncAssertingClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient))
.serviceVersion(serviceVersion)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
if (interceptorManager.isRecordMode()) {
builder
.addPolicy(interceptorManager.getRecordPolicy())
.addPolicy(new RetryPolicy());
} else if (interceptorManager.isPlaybackMode()) {
interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("Sync-Token"))));
}
return builder.buildAsyncClient();
});
}
private HttpClient buildAsyncAssertingClient(HttpClient httpClient) {
BiFunction<HttpRequest, com.azure.core.util.Context, Boolean> skipRequestFunction = (request, context) -> {
String callerMethod = (String) context.getData("caller-method").orElse("");
return callerMethod.contains("list");
};
return new AssertingHttpClientBuilder(httpClient)
.skipRequest(skipRequestFunction)
.assertAsync()
.build();
}
/**
* Tests that a configuration is able to be added, these are differentiate from each other using a key or key-label
* identifier.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingRunner((expected) ->
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingConvenience(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addFeatureFlagConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addSecretReferenceConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that we cannot add a configuration setting when the key is an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingEmptyKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.addConfigurationSetting("", null, "A value"))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD));
}
/**
* Tests that we can add configuration settings when value is not null or an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingEmptyValue(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingEmptyValueRunner((setting) -> {
StepVerifier.create(client.addConfigurationSetting(setting.getKey(), setting.getLabel(), setting.getValue()))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(setting.getKey(), setting.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
});
}
/**
* Verifies that an exception is thrown when null key is passed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.addConfigurationSetting(null, null, "A Value"))
.expectError(IllegalArgumentException.class)
.verify();
StepVerifier.create(client.addConfigurationSettingWithResponse(null))
.expectError(NullPointerException.class)
.verify();
}
/**
* Tests that a configuration cannot be added twice with the same key. This should return a 412 error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addExistingSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addExistingSettingRunner((expected) ->
StepVerifier.create(
client.addConfigurationSettingWithResponse(expected)
.then(
client.addConfigurationSettingWithResponse(expected)))
.verifyErrorSatisfies(ex -> assertRestException(ex,
HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED)));
}
/**
* Tests that a configuration is able to be added or updated with set.
* When the configuration is read-only updates cannot happen, this will result in a 409.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingRunner((expected, update) ->
StepVerifier.create(client.setConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setFeatureFlagConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(
expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setSecretReferenceConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(
expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that when an ETag is passed to set it will only set if the current representation of the setting has the
* ETag. If the set ETag doesn't match anything the update won't happen, this will result in a 412. This will
* prevent set from doing an add as well.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingIfETag(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingIfETagRunner((initial, update) -> {
StepVerifier.create(client.setConfigurationSettingWithResponse(initial.setETag("badEtag"), true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
final String etag = client.addConfigurationSettingWithResponse(initial).block().getValue().getETag();
StepVerifier.create(client.setConfigurationSettingWithResponse(update.setETag(etag), true))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(initial, true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
StepVerifier.create(client.getConfigurationSettingWithResponse(update, null, false))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
});
}
/**
* Tests that we cannot set a configuration setting when the key is an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingEmptyKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.setConfigurationSetting("", NO_LABEL, "A value"))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD));
}
/**
* Tests that we can set configuration settings when value is not null or an empty string.
* Value is not a required property.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingEmptyValue(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingEmptyValueRunner((setting) -> {
StepVerifier.create(client.setConfigurationSetting(setting.getKey(), NO_LABEL, setting.getValue()))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(setting.getKey(), setting.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
});
}
/**
* Verifies that an exception is thrown when null key is passed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.setConfigurationSetting(null, NO_LABEL, "A Value"))
.verifyError(IllegalArgumentException.class);
StepVerifier.create(client.setConfigurationSettingWithResponse(null, false))
.verifyError(NullPointerException.class);
}
/**
* Tests that a configuration is able to be retrieved when it exists, whether or not it is read-only.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getConfigurationSettingRunner((expected) ->
StepVerifier.create(
client.addConfigurationSettingWithResponse(expected)
.then(client.getConfigurationSettingWithResponse(expected, null, false)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingConvenience(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getFeatureFlagConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getSecretReferenceConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that attempting to retrieve a non-existent configuration doesn't work, this will result in a 404.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingNotFound(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting neverRetrievedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverRetreivedValue");
final ConfigurationSetting nonExistentLabel = new ConfigurationSetting().setKey(key).setLabel("myNonExistentLabel");
StepVerifier.create(client.addConfigurationSettingWithResponse(neverRetrievedConfiguration))
.assertNext(response -> assertConfigurationEquals(neverRetrievedConfiguration, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting("myNonExistentKey", null, null))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
StepVerifier.create(client.getConfigurationSettingWithResponse(nonExistentLabel, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that configurations are able to be deleted when they exist.
* After the configuration has been deleted attempting to get it will result in a 404, the same as if the
* configuration never existed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected).then(client.getConfigurationSettingWithResponse(expected, null, false)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(expected, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteFeatureFlagConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteSecretReferenceConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
/**
* Tests that attempting to delete a non-existent configuration will return a 204.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingNotFound(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting neverDeletedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverDeletedValue");
StepVerifier.create(client.addConfigurationSettingWithResponse(neverDeletedConfiguration))
.assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(new ConfigurationSetting().setKey("myNonExistentKey"), false))
.assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(new ConfigurationSetting().setKey(neverDeletedConfiguration.getKey()).setLabel("myNonExistentLabel"), false))
.assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(neverDeletedConfiguration.getKey(), neverDeletedConfiguration.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response))
.verifyComplete();
}
/**
* Tests that when an ETag is passed to delete it will only delete if the current representation of the setting has the ETag.
* If the delete ETag doesn't match anything the delete won't happen, this will result in a 412.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingWithETag(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingWithETagRunner((initial, update) -> {
final ConfigurationSetting initiallyAddedConfig = client.addConfigurationSettingWithResponse(initial).block().getValue();
final ConfigurationSetting updatedConfig = client.setConfigurationSettingWithResponse(update, true).block().getValue();
StepVerifier.create(client.getConfigurationSettingWithResponse(initial, null, false))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(initiallyAddedConfig, true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
StepVerifier.create(client.deleteConfigurationSettingWithResponse(updatedConfig, true))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(initial, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
/**
* Test the API will not make a delete call without having a key passed, an IllegalArgumentException should be thrown.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.deleteConfigurationSetting(null, null))
.verifyError(IllegalArgumentException.class);
StepVerifier.create(client.deleteConfigurationSettingWithResponse(null, false))
.verifyError(NullPointerException.class);
}
/**
* Tests assert that the setting can be deleted after clear read-only of the setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnly(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
/**
* Tests assert that the setting can be deleted after clear read-only of the setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnlyWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockFeatureFlagRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockSecretReferenceRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
});
}
/**
* Verifies that a ConfigurationSetting can be added with a label, and that we can fetch that ConfigurationSetting
* from the service when filtering by either its label or just its key.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithKeyAndLabel(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String value = "myValue";
final String key = testResourceNamer.randomName(keyPrefix, 16);
final String label = testResourceNamer.randomName("lbl", 8);
final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue(value).setLabel(label);
StepVerifier.create(client.setConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key).setLabelFilter(label)))
.assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key)))
.assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting))
.verifyComplete();
}
/**
* Verifies that ConfigurationSettings can be added and that we can fetch those ConfigurationSettings from the
* service when filtering by their keys.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithMultipleKeys(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String key2 = getKey();
listWithMultipleKeysRunner(key, key2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key + "," + key2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
@Disabled("This was failing even before re-record with Test Proxy")
public void listConfigurationSettingsWithNullSelector(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final String key2 = getKey();
StepVerifier.create(
client.listConfigurationSettings(null)
.flatMap(setting -> client.deleteConfigurationSettingWithResponse(setting, false))
.then())
.verifyComplete();
listWithMultipleKeysRunner(key, key2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(null))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
assertEquals(2, selected.size());
return selected;
});
}
/**
* Verifies that ConfigurationSettings can be added with different labels and that we can fetch those ConfigurationSettings
* from the service when filtering by their labels.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithMultipleLabels(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String label = getLabel();
String label2 = getLabel();
listWithMultipleLabelsRunner(key, label, label2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key).setLabelFilter(label + "," + label2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can select filter results by key, label, and select fields using SettingSelector.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFields(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
listConfigurationSettingsSelectFieldsRunner((settings, selector) -> {
final List<Mono<Response<ConfigurationSetting>>> settingsBeingAdded = new ArrayList<>();
for (ConfigurationSetting setting : settings) {
settingsBeingAdded.add(client.setConfigurationSettingWithResponse(setting, false));
}
Flux.merge(settingsBeingAdded).blockLast();
List<ConfigurationSetting> settingsReturned = new ArrayList<>();
StepVerifier.create(client.listConfigurationSettings(selector))
.assertNext(settingsReturned::add)
.assertNext(settingsReturned::add)
.verifyComplete();
return settingsReturned;
});
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a key filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithPrefixStarKeyFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest("*" + getKey(), getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a* key filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithSubstringKeyFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest("*" + getKey() + "*", getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a label filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithPrefixStarLabelFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest(getKey(), "*" + getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a* label filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithSubstringLabelFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest(getKey(), "*" + getLabel() + "*");
}
/**
* Verifies that we can get a ConfigurationSetting at the provided accept datetime
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsAcceptDateTime(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2)))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
List<ConfigurationSetting> revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).collectList().block();
assertNotNull(revisions);
assertEquals(3, revisions.size());
SettingSelector options = new SettingSelector().setKeyFilter(keyName).setAcceptDatetime(revisions.get(1).getLastModified());
StepVerifier.create(client.listConfigurationSettings(options))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
}
/**
* Verifies that we can get all of the revisions for this ConfigurationSetting. Then verifies that we can select
* specific fields.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisions(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(keyName)))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.assertNext(response -> assertConfigurationEquals(updated, response))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(keyName).setFields(SettingFields.KEY, SettingFields.ETAG)))
.assertNext(response -> validateListRevisions(updated2, response))
.assertNext(response -> validateListRevisions(updated, response))
.assertNext(response -> validateListRevisions(original, response))
.verifyComplete();
assertTrue(client.listRevisions(null).toStream().collect(Collectors.toList()).size() > 0);
}
/**
* Verifies that we can get all the revisions for all settings with the specified keys.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithMultipleKeys(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String key2 = getKey();
listRevisionsWithMultipleKeysRunner(key, key2, (testInput) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(0)))
.assertNext(response -> assertConfigurationEquals(testInput.get(0), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(1), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(1), response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(2)))
.assertNext(response -> assertConfigurationEquals(testInput.get(2), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(3), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(3), response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(key + "," + key2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can get all revisions for all settings with the specified labels.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithMultipleLabels(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String label = getLabel();
String label2 = getLabel();
listRevisionsWithMultipleLabelsRunner(key, label, label2, (testInput) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(0)))
.assertNext(response -> assertConfigurationEquals(testInput.get(0), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(1), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(1), response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(2)))
.assertNext(response -> assertConfigurationEquals(testInput.get(2), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(3), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(3), response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(key).setLabelFilter(label + "," + label2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can get a subset of revisions based on the "acceptDateTime"
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsAcceptDateTime(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2)))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
List<ConfigurationSetting> revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).collectList().block();
assertNotNull(revisions);
assertEquals(3, revisions.size());
SettingSelector options = new SettingSelector().setKeyFilter(keyName)
.setAcceptDatetime(revisions.get(1).getLastModified());
StepVerifier.create(client.listRevisions(options))
.assertNext(response -> assertConfigurationEquals(updated, response))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPagination(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
settings.add(new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix));
}
for (ConfigurationSetting setting : settings) {
StepVerifier.create(client.setConfigurationSetting(setting))
.expectNextCount(1)
.verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
StepVerifier.create(client.listRevisions(filter))
.expectNextCount(numberExpected)
.verifyComplete();
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times.
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPaginationAndRepeatStream(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix);
settings.add(setting);
StepVerifier.create(client.setConfigurationSetting(setting))
.expectNextCount(1)
.verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>();
List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>();
PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listRevisions(filter);
configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList1.size());
configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList2.size());
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times.
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPaginationAndRepeatIterator(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix);
settings.add(setting);
StepVerifier.create(client.setConfigurationSetting(setting)).expectNextCount(1).verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>();
List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>();
PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listRevisions(filter);
configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList1.size());
configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList2.size());
}
/**
* Verifies that, given a ton of existing settings, we can list the ConfigurationSettings using pagination
* (ie. where 'nextLink' has a URL pointing to the next page of results.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
/**
* Verifies the conditional "GET" scenario where the setting has yet to be updated, resulting in a 304. This GET
* scenario will return a setting when the ETag provided does not match the one of the current setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingWhenValueNotUpdated(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue("myValue");
final ConfigurationSetting newExpected = new ConfigurationSetting().setKey(key).setValue("myNewValue");
final ConfigurationSetting block = client.addConfigurationSettingWithResponse(expected).block().getValue();
assertNotNull(block);
assertConfigurationEquals(expected, block);
StepVerifier.create(client.getConfigurationSettingWithResponse(block, null, true))
.assertNext(response -> assertConfigurationEquals(null, response, 304))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(newExpected, false))
.assertNext(response -> assertConfigurationEquals(newExpected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(block, null, true))
.assertNext(response -> assertConfigurationEquals(newExpected, response))
.verifyComplete();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
@Disabled
public void deleteAllSettings(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
client.listConfigurationSettings(new SettingSelector().setKeyFilter("*"))
.flatMap(configurationSetting -> {
logger.info("Deleting key:label [{}:{}]. isReadOnly? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isReadOnly());
return client.deleteConfigurationSettingWithResponse(configurationSetting, false);
}).blockLast();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addHeadersFromContextPolicyTest(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final HttpHeaders headers = getCustomizedHeaders();
addHeadersFromContextPolicyRunner(expected ->
StepVerifier.create(client.addConfigurationSettingWithResponse(expected)
.contextWrite(Context.of(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers)))
.assertNext(response -> {
final HttpHeaders requestHeaders = response.getRequest().getHeaders();
assertContainsHeaders(headers, requestHeaders);
})
.verifyComplete());
}
/**
* Test helper that calling list configuration setting with given key and label input
*
* @param keyFilter key filter expression
* @param labelFilter label filter expression
*/
private void filterValueTest(String keyFilter, String labelFilter) {
listConfigurationSettingsSelectFieldsWithNotSupportedFilterRunner(keyFilter, labelFilter, selector ->
StepVerifier.create(client.listConfigurationSettings(selector))
.verifyError(HttpResponseException.class));
}
} | class ConfigurationAsyncClientTest extends ConfigurationClientTestBase {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class);
private static final String NO_LABEL = null;
private ConfigurationAsyncClient client;
@Override
protected String getTestName() {
return "";
}
@Override
protected void beforeTest() {
beforeTestSetup();
}
@Override
protected void afterTest() {
logger.info("Cleaning up created key values.");
client.listConfigurationSettings(new SettingSelector().setKeyFilter(keyPrefix + "*"))
.flatMap(configurationSetting -> {
logger.info("Deleting key:label [{}:{}]. isReadOnly? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isReadOnly());
Mono<Response<ConfigurationSetting>> unlock = configurationSetting.isReadOnly() ? client.setReadOnlyWithResponse(configurationSetting, false) : Mono.empty();
return unlock.then(client.deleteConfigurationSettingWithResponse(configurationSetting, false));
})
.blockLast();
logger.info("Finished cleaning up values.");
}
private ConfigurationAsyncClient getConfigurationAsyncClient(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
return clientSetup(credentials -> {
ConfigurationClientBuilder builder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.serviceVersion(serviceVersion)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
setHttpClient(httpClient, builder);
if (interceptorManager.isRecordMode()) {
builder
.addPolicy(interceptorManager.getRecordPolicy())
.addPolicy(new RetryPolicy());
} else if (interceptorManager.isPlaybackMode()) {
interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("Sync-Token"))));
}
return builder.buildAsyncClient();
});
}
private ConfigurationClientBuilder setHttpClient(HttpClient httpClient, ConfigurationClientBuilder builder) {
if (interceptorManager.isRecordMode()) {
return builder
.httpClient(buildAsyncAssertingClient(httpClient));
} else if (interceptorManager.isPlaybackMode()) {
return builder
.httpClient(buildAsyncAssertingClient(interceptorManager.getPlaybackClient()));
}
return builder;
}
private HttpClient buildAsyncAssertingClient(HttpClient httpClient) {
BiFunction<HttpRequest, com.azure.core.util.Context, Boolean> skipRequestFunction = (request, context) -> {
String callerMethod = (String) context.getData("caller-method").orElse("");
return callerMethod.contains("list");
};
return new AssertingHttpClientBuilder(httpClient)
.skipRequest(skipRequestFunction)
.assertAsync()
.build();
}
/**
* Tests that a configuration is able to be added, these are differentiate from each other using a key or key-label
* identifier.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingRunner((expected) ->
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingConvenience(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addFeatureFlagConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addSecretReferenceConfigurationSettingRunner(
(expected) ->
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that we cannot add a configuration setting when the key is an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingEmptyKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.addConfigurationSetting("", null, "A value"))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD));
}
/**
* Tests that we can add configuration settings when value is not null or an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingEmptyValue(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addConfigurationSettingEmptyValueRunner((setting) -> {
StepVerifier.create(client.addConfigurationSetting(setting.getKey(), setting.getLabel(), setting.getValue()))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(setting.getKey(), setting.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
});
}
/**
* Verifies that an exception is thrown when null key is passed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.addConfigurationSetting(null, null, "A Value"))
.expectError(IllegalArgumentException.class)
.verify();
StepVerifier.create(client.addConfigurationSettingWithResponse(null))
.expectError(NullPointerException.class)
.verify();
}
/**
* Tests that a configuration cannot be added twice with the same key. This should return a 412 error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addExistingSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
addExistingSettingRunner((expected) ->
StepVerifier.create(
client.addConfigurationSettingWithResponse(expected)
.then(
client.addConfigurationSettingWithResponse(expected)))
.verifyErrorSatisfies(ex -> assertRestException(ex,
HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED)));
}
/**
* Tests that a configuration is able to be added or updated with set.
* When the configuration is read-only updates cannot happen, this will result in a 409.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingRunner((expected, update) ->
StepVerifier.create(client.setConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setFeatureFlagConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(
expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setSecretReferenceConfigurationSettingRunner(
(expected, update) -> StepVerifier.create(client.setConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(
expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that when an ETag is passed to set it will only set if the current representation of the setting has the
* ETag. If the set ETag doesn't match anything the update won't happen, this will result in a 412. This will
* prevent set from doing an add as well.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingIfETag(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingIfETagRunner((initial, update) -> {
StepVerifier.create(client.setConfigurationSettingWithResponse(initial.setETag("badEtag"), true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
final String etag = client.addConfigurationSettingWithResponse(initial).block().getValue().getETag();
StepVerifier.create(client.setConfigurationSettingWithResponse(update.setETag(etag), true))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(initial, true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
StepVerifier.create(client.getConfigurationSettingWithResponse(update, null, false))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
});
}
/**
* Tests that we cannot set a configuration setting when the key is an empty string.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingEmptyKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.setConfigurationSetting("", NO_LABEL, "A value"))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD));
}
/**
* Tests that we can set configuration settings when value is not null or an empty string.
* Value is not a required property.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingEmptyValue(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
setConfigurationSettingEmptyValueRunner((setting) -> {
StepVerifier.create(client.setConfigurationSetting(setting.getKey(), NO_LABEL, setting.getValue()))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(setting.getKey(), setting.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
});
}
/**
* Verifies that an exception is thrown when null key is passed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void setConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.setConfigurationSetting(null, NO_LABEL, "A Value"))
.verifyError(IllegalArgumentException.class);
StepVerifier.create(client.setConfigurationSettingWithResponse(null, false))
.verifyError(NullPointerException.class);
}
/**
* Tests that a configuration is able to be retrieved when it exists, whether or not it is read-only.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getConfigurationSettingRunner((expected) ->
StepVerifier.create(
client.addConfigurationSettingWithResponse(expected)
.then(client.getConfigurationSettingWithResponse(expected, null, false)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingConvenience(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getFeatureFlagConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete());
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
getSecretReferenceConfigurationSettingRunner(
(expected) -> StepVerifier.create(
client.addConfigurationSetting(expected).then(
client.getConfigurationSetting(expected)))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete());
}
/**
* Tests that attempting to retrieve a non-existent configuration doesn't work, this will result in a 404.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingNotFound(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting neverRetrievedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverRetreivedValue");
final ConfigurationSetting nonExistentLabel = new ConfigurationSetting().setKey(key).setLabel("myNonExistentLabel");
StepVerifier.create(client.addConfigurationSettingWithResponse(neverRetrievedConfiguration))
.assertNext(response -> assertConfigurationEquals(neverRetrievedConfiguration, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting("myNonExistentKey", null, null))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
StepVerifier.create(client.getConfigurationSettingWithResponse(nonExistentLabel, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
}
/**
* Tests that configurations are able to be deleted when they exist.
* After the configuration has been deleted attempting to get it will result in a 404, the same as if the
* configuration never existed.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected).then(client.getConfigurationSettingWithResponse(expected, null, false)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(expected, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteFeatureFlagConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteSecretReferenceConfigurationSettingRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected).then(client.getConfigurationSetting(expected)))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(expected))
.verifyErrorSatisfies(
ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
/**
* Tests that attempting to delete a non-existent configuration will return a 204.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingNotFound(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting neverDeletedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverDeletedValue");
StepVerifier.create(client.addConfigurationSettingWithResponse(neverDeletedConfiguration))
.assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(new ConfigurationSetting().setKey("myNonExistentKey"), false))
.assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(new ConfigurationSetting().setKey(neverDeletedConfiguration.getKey()).setLabel("myNonExistentLabel"), false))
.assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT))
.verifyComplete();
StepVerifier.create(client.getConfigurationSetting(neverDeletedConfiguration.getKey(), neverDeletedConfiguration.getLabel(), null))
.assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response))
.verifyComplete();
}
/**
* Tests that when an ETag is passed to delete it will only delete if the current representation of the setting has the ETag.
* If the delete ETag doesn't match anything the delete won't happen, this will result in a 412.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingWithETag(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
deleteConfigurationSettingWithETagRunner((initial, update) -> {
final ConfigurationSetting initiallyAddedConfig = client.addConfigurationSettingWithResponse(initial).block().getValue();
final ConfigurationSetting updatedConfig = client.setConfigurationSettingWithResponse(update, true).block().getValue();
StepVerifier.create(client.getConfigurationSettingWithResponse(initial, null, false))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(initiallyAddedConfig, true))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_PRECON_FAILED));
StepVerifier.create(client.deleteConfigurationSettingWithResponse(updatedConfig, true))
.assertNext(response -> assertConfigurationEquals(update, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(initial, null, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND));
});
}
/**
* Test the API will not make a delete call without having a key passed, an IllegalArgumentException should be thrown.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void deleteConfigurationSettingNullKey(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.deleteConfigurationSetting(null, null))
.verifyError(IllegalArgumentException.class);
StepVerifier.create(client.deleteConfigurationSettingWithResponse(null, false))
.verifyError(NullPointerException.class);
}
/**
* Tests assert that the setting can be deleted after clear read-only of the setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnly(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
/**
* Tests assert that the setting can be deleted after clear read-only of the setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithConfigurationSetting(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSettingWithResponse(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel(), true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnlyWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithFeatureFlagConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockFeatureFlagRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertFeatureFlagConfigurationSettingEquals(expected,
(FeatureFlagConfigurationSetting) response))
.verifyComplete();
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void clearReadOnlyWithSecretReferenceConfigurationSettingConvenience(HttpClient httpClient,
ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
lockUnlockSecretReferenceRunner((expected) -> {
StepVerifier.create(client.addConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.setReadOnly(expected, true))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 409));
StepVerifier.create(client.setReadOnly(expected, false))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
StepVerifier.create(client.deleteConfigurationSetting(expected))
.assertNext(response -> assertSecretReferenceConfigurationSettingEquals(expected,
(SecretReferenceConfigurationSetting) response))
.verifyComplete();
});
}
/**
* Verifies that a ConfigurationSetting can be added with a label, and that we can fetch that ConfigurationSetting
* from the service when filtering by either its label or just its key.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithKeyAndLabel(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String value = "myValue";
final String key = testResourceNamer.randomName(keyPrefix, 16);
final String label = testResourceNamer.randomName("lbl", 8);
final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue(value).setLabel(label);
StepVerifier.create(client.setConfigurationSettingWithResponse(expected, false))
.assertNext(response -> assertConfigurationEquals(expected, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key).setLabelFilter(label)))
.assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key)))
.assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting))
.verifyComplete();
}
/**
* Verifies that ConfigurationSettings can be added and that we can fetch those ConfigurationSettings from the
* service when filtering by their keys.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithMultipleKeys(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String key2 = getKey();
listWithMultipleKeysRunner(key, key2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key + "," + key2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsWithNullSelector(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final String key2 = getKey();
StepVerifier.create(
client.listConfigurationSettings(null)
.flatMap(setting -> client.deleteConfigurationSettingWithResponse(setting, false))
.then())
.verifyComplete();
listWithMultipleKeysRunner(key, key2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(null))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
assertEquals(2, selected.size());
return selected;
});
}
/**
* Verifies that ConfigurationSettings can be added with different labels and that we can fetch those ConfigurationSettings
* from the service when filtering by their labels.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listWithMultipleLabels(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String label = getLabel();
String label2 = getLabel();
listWithMultipleLabelsRunner(key, label, label2, (setting, setting2) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting))
.assertNext(response -> assertConfigurationEquals(setting, response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(setting2))
.assertNext(response -> assertConfigurationEquals(setting2, response))
.verifyComplete();
StepVerifier.create(client.listConfigurationSettings(new SettingSelector().setKeyFilter(key).setLabelFilter(label + "," + label2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can select filter results by key, label, and select fields using SettingSelector.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFields(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
listConfigurationSettingsSelectFieldsRunner((settings, selector) -> {
final List<Mono<Response<ConfigurationSetting>>> settingsBeingAdded = new ArrayList<>();
for (ConfigurationSetting setting : settings) {
settingsBeingAdded.add(client.setConfigurationSettingWithResponse(setting, false));
}
Flux.merge(settingsBeingAdded).blockLast();
List<ConfigurationSetting> settingsReturned = new ArrayList<>();
StepVerifier.create(client.listConfigurationSettings(selector))
.assertNext(settingsReturned::add)
.assertNext(settingsReturned::add)
.verifyComplete();
return settingsReturned;
});
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a key filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithPrefixStarKeyFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest("*" + getKey(), getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a* key filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithSubstringKeyFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest("*" + getKey() + "*", getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a label filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithPrefixStarLabelFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest(getKey(), "*" + getLabel());
}
/**
* Verifies that throws exception when using SettingSelector with not supported *a* label filter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsSelectFieldsWithSubstringLabelFilter(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
filterValueTest(getKey(), "*" + getLabel() + "*");
}
/**
* Verifies that we can get a ConfigurationSetting at the provided accept datetime
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listConfigurationSettingsAcceptDateTime(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2)))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
List<ConfigurationSetting> revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).collectList().block();
assertNotNull(revisions);
assertEquals(3, revisions.size());
SettingSelector options = new SettingSelector().setKeyFilter(keyName).setAcceptDatetime(revisions.get(1).getLastModified());
StepVerifier.create(client.listConfigurationSettings(options))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
}
/**
* Verifies that we can get all of the revisions for this ConfigurationSetting. Then verifies that we can select
* specific fields.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisions(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(keyName)))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.assertNext(response -> assertConfigurationEquals(updated, response))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(keyName).setFields(SettingFields.KEY, SettingFields.ETAG)))
.assertNext(response -> validateListRevisions(updated2, response))
.assertNext(response -> validateListRevisions(updated, response))
.assertNext(response -> validateListRevisions(original, response))
.verifyComplete();
assertTrue(client.listRevisions(null).toStream().collect(Collectors.toList()).size() > 0);
}
/**
* Verifies that we can get all the revisions for all settings with the specified keys.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithMultipleKeys(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String key2 = getKey();
listRevisionsWithMultipleKeysRunner(key, key2, (testInput) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(0)))
.assertNext(response -> assertConfigurationEquals(testInput.get(0), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(1), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(1), response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(2)))
.assertNext(response -> assertConfigurationEquals(testInput.get(2), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(3), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(3), response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(key + "," + key2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can get all revisions for all settings with the specified labels.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithMultipleLabels(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
String key = getKey();
String label = getLabel();
String label2 = getLabel();
listRevisionsWithMultipleLabelsRunner(key, label, label2, (testInput) -> {
List<ConfigurationSetting> selected = new ArrayList<>();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(0)))
.assertNext(response -> assertConfigurationEquals(testInput.get(0), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(1), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(1), response))
.verifyComplete();
StepVerifier.create(client.addConfigurationSettingWithResponse(testInput.get(2)))
.assertNext(response -> assertConfigurationEquals(testInput.get(2), response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(testInput.get(3), false))
.assertNext(response -> assertConfigurationEquals(testInput.get(3), response))
.verifyComplete();
StepVerifier.create(client.listRevisions(new SettingSelector().setKeyFilter(key).setLabelFilter(label + "," + label2)))
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.consumeNextWith(selected::add)
.verifyComplete();
return selected;
});
}
/**
* Verifies that we can get a subset of revisions based on the "acceptDateTime"
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsAcceptDateTime(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String keyName = testResourceNamer.randomName(keyPrefix, 16);
final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue");
final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue");
final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2");
StepVerifier.create(client.setConfigurationSettingWithResponse(original, false))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2)))
.assertNext(response -> assertConfigurationEquals(updated, response))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(updated2, false))
.assertNext(response -> assertConfigurationEquals(updated2, response))
.verifyComplete();
List<ConfigurationSetting> revisions = client.listRevisions(new SettingSelector().setKeyFilter(keyName)).collectList().block();
assertNotNull(revisions);
assertEquals(3, revisions.size());
SettingSelector options = new SettingSelector().setKeyFilter(keyName)
.setAcceptDatetime(revisions.get(1).getLastModified());
StepVerifier.create(client.listRevisions(options))
.assertNext(response -> assertConfigurationEquals(updated, response))
.assertNext(response -> assertConfigurationEquals(original, response))
.verifyComplete();
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPagination(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
settings.add(new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix));
}
for (ConfigurationSetting setting : settings) {
StepVerifier.create(client.setConfigurationSetting(setting))
.expectNextCount(1)
.verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
StepVerifier.create(client.listRevisions(filter))
.expectNextCount(numberExpected)
.verifyComplete();
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times.
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPaginationAndRepeatStream(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix);
settings.add(setting);
StepVerifier.create(client.setConfigurationSetting(setting))
.expectNextCount(1)
.verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>();
List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>();
PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listRevisions(filter);
configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList1.size());
configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList2.size());
}
/**
* Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times.
* (ie. where 'nextLink' has a URL pointing to the next page of results.)
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void listRevisionsWithPaginationAndRepeatIterator(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final int numberExpected = 50;
List<ConfigurationSetting> settings = new ArrayList<>(numberExpected);
for (int value = 0; value < numberExpected; value++) {
ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix);
settings.add(setting);
StepVerifier.create(client.setConfigurationSetting(setting)).expectNextCount(1).verifyComplete();
}
SettingSelector filter = new SettingSelector().setKeyFilter(keyPrefix).setLabelFilter(labelPrefix);
List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>();
List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>();
PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listRevisions(filter);
configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList1.size());
configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting));
assertEquals(numberExpected, configurationSettingList2.size());
}
/**
* Verifies that, given a ton of existing settings, we can list the ConfigurationSettings using pagination
* (ie. where 'nextLink' has a URL pointing to the next page of results.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
/**
* Verifies the conditional "GET" scenario where the setting has yet to be updated, resulting in a 304. This GET
* scenario will return a setting when the ETag provided does not match the one of the current setting.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void getConfigurationSettingWhenValueNotUpdated(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final String key = getKey();
final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue("myValue");
final ConfigurationSetting newExpected = new ConfigurationSetting().setKey(key).setValue("myNewValue");
final ConfigurationSetting block = client.addConfigurationSettingWithResponse(expected).block().getValue();
assertNotNull(block);
assertConfigurationEquals(expected, block);
StepVerifier.create(client.getConfigurationSettingWithResponse(block, null, true))
.assertNext(response -> assertConfigurationEquals(null, response, 304))
.verifyComplete();
StepVerifier.create(client.setConfigurationSettingWithResponse(newExpected, false))
.assertNext(response -> assertConfigurationEquals(newExpected, response))
.verifyComplete();
StepVerifier.create(client.getConfigurationSettingWithResponse(block, null, true))
.assertNext(response -> assertConfigurationEquals(newExpected, response))
.verifyComplete();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
@Disabled
public void deleteAllSettings(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
client.listConfigurationSettings(new SettingSelector().setKeyFilter("*"))
.flatMap(configurationSetting -> {
logger.info("Deleting key:label [{}:{}]. isReadOnly? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isReadOnly());
return client.deleteConfigurationSettingWithResponse(configurationSetting, false);
}).blockLast();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void addHeadersFromContextPolicyTest(HttpClient httpClient, ConfigurationServiceVersion serviceVersion) {
client = getConfigurationAsyncClient(httpClient, serviceVersion);
final HttpHeaders headers = getCustomizedHeaders();
addHeadersFromContextPolicyRunner(expected ->
StepVerifier.create(client.addConfigurationSettingWithResponse(expected)
.contextWrite(Context.of(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers)))
.assertNext(response -> {
final HttpHeaders requestHeaders = response.getRequest().getHeaders();
assertContainsHeaders(headers, requestHeaders);
})
.verifyComplete());
}
/**
* Test helper that calling list configuration setting with given key and label input
*
* @param keyFilter key filter expression
* @param labelFilter label filter expression
*/
private void filterValueTest(String keyFilter, String labelFilter) {
listConfigurationSettingsSelectFieldsWithNotSupportedFilterRunner(keyFilter, labelFilter, selector ->
StepVerifier.create(client.listConfigurationSettings(selector))
.verifyError(HttpResponseException.class));
}
} |
Should we throw for both LIVE and RECORD mode here? | public HttpClient getPlaybackClient() {
if (testProxyEnabled) {
if (isLiveMode()) {
throw new RuntimeException("A playback client cannot be requested in LIVE mode.");
}
if (testProxyPlaybackClient == null) {
testProxyPlaybackClient = new TestProxyPlaybackClient(httpClient);
proxyVariableQueue.addAll(testProxyPlaybackClient.startPlayback(playbackRecordName));
}
return testProxyPlaybackClient;
} else {
return new PlaybackClient(recordedData, textReplacementRules);
}
} | if (isLiveMode()) { | public HttpClient getPlaybackClient() {
if (testProxyEnabled) {
if (!isPlaybackMode()) {
throw new IllegalStateException("A playback client can only be requested in PLAYBACK mode.");
}
if (testProxyPlaybackClient == null) {
testProxyPlaybackClient = new TestProxyPlaybackClient(httpClient);
proxyVariableQueue.addAll(testProxyPlaybackClient.startPlayback(playbackRecordName));
}
return testProxyPlaybackClient;
} else {
return new PlaybackClient(recordedData, textReplacementRules);
}
} | class InterceptorManager implements AutoCloseable {
private static final ObjectMapper RECORD_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private static final ClientLogger LOGGER = new ClientLogger(InterceptorManager.class);
private final Map<String, String> textReplacementRules;
private final String testName;
private final String playbackRecordName;
private final TestMode testMode;
private final boolean allowedToReadRecordedValues;
private final boolean allowedToRecordValues;
private final RecordedData recordedData;
private final boolean testProxyEnabled;
private TestProxyRecordPolicy testProxyRecordPolicy;
private TestProxyPlaybackClient testProxyPlaybackClient;
private final Queue<String> proxyVariableQueue = new LinkedList<>();
private HttpClient httpClient;
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param testMode The {@link TestMode} for this interceptor.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, TestMode testMode) {
this(testName, testName, testMode, false, false);
}
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* <li>If {@code testMode} is {@link TestMode
* record.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode},
* and others.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
*/
public InterceptorManager(TestContextManager testContextManager) {
this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(),
testContextManager.getTestMode(), testContextManager.doNotRecordTest(), testContextManager.isTestProxyEnabled());
}
private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord, boolean enableTestProxy) {
this.testProxyEnabled = enableTestProxy;
Objects.requireNonNull(testName, "'testName' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = testMode;
this.textReplacementRules = new HashMap<>();
this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord);
this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord);
if (!enableTestProxy && allowedToReadRecordedValues) {
this.recordedData = readDataFromFile();
} else if (!enableTestProxy && allowedToRecordValues) {
this.recordedData = new RecordedData();
} else {
this.recordedData = null;
}
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules) {
this(testName, textReplacementRules, false, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord) {
this(testName, textReplacementRules, doNotRecord, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @param playbackRecordName Full name of the test including its iteration, used as the playback record name.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
*/
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord,
String playbackRecordName) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
Objects.requireNonNull(textReplacementRules, "'textReplacementRules' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = TestMode.PLAYBACK;
this.allowedToReadRecordedValues = !doNotRecord;
this.allowedToRecordValues = false;
this.testProxyEnabled = false;
this.recordedData = allowedToReadRecordedValues ? readDataFromFile() : null;
this.textReplacementRules = textReplacementRules;
}
/**
* Gets whether this InterceptorManager is in playback mode.
*
* @return true if the InterceptorManager is in playback mode and false otherwise.
*/
public boolean isPlaybackMode() {
return testMode == TestMode.PLAYBACK;
}
/**
* Gets whether this InterceptorManager is in live mode.
*
* @return true if the InterceptorManager is in live mode and false otherwise.
*/
public boolean isLiveMode() {
return testMode == TestMode.LIVE;
}
/**
* Gets the recorded data InterceptorManager is keeping track of.
*
* @return The recorded data managed by InterceptorManager.
*/
public RecordedData getRecordedData() {
return recordedData;
}
/**
* A {@link Supplier} for retrieving a variable from a test proxy recording.
* @return The supplier for retrieving a variable.
*/
public Supplier<String> getProxyVariableSupplier() {
return () -> {
Objects.requireNonNull(this.testProxyPlaybackClient, "Playback must be started to retrieve values");
if (!CoreUtils.isNullOrEmpty(proxyVariableQueue)) {
return proxyVariableQueue.remove();
} else {
throw LOGGER.logExceptionAsError(new RuntimeException("'proxyVariableQueue' cannot be null or empty."));
}
};
}
/**
* Get a {@link Consumer} for adding variables used in test proxy tests.
* @return The consumer for adding a variable.
*/
public Consumer<String> getProxyVariableConsumer() {
return proxyVariableQueue::add;
}
/**
* Gets a new HTTP pipeline policy that records network calls and its data is managed by
* {@link InterceptorManager}.
*
* @return HttpPipelinePolicy to record network calls.
*
* @throws RuntimeException A playback client was requested when the test proxy is enabled and test mode is LIVE.
*/
public HttpPipelinePolicy getRecordPolicy() {
if (testProxyEnabled) {
return getProxyRecordingPolicy();
}
return getRecordPolicy(Collections.emptyList());
}
/**
* Gets a new HTTP pipeline policy that records network calls. The recorded content is redacted by the given list of
* redactor functions to hide sensitive information.
*
* @param recordingRedactors The custom redactor functions that are applied in addition to the default redactor
* functions defined in {@link RecordingRedactor}.
* @return {@link HttpPipelinePolicy} to record network calls.
*/
public HttpPipelinePolicy getRecordPolicy(List<Function<String, String>> recordingRedactors) {
if (testProxyEnabled) {
return getProxyRecordingPolicy();
}
return new RecordNetworkCallPolicy(recordedData, recordingRedactors);
}
/**
* Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}.
*
* @return An HTTP client that plays back network calls from its recorded data.
*
* @throws RuntimeException A playback client was requested when the test proxy is enabled and test mode is LIVE.
*/
/**
* Disposes of resources used by this InterceptorManager.
*
* If {@code testMode} is {@link TestMode
* "<i>session-records/{@code testName}.json</i>"
*/
@Override
public void close() {
if (allowedToRecordValues) {
if (testProxyEnabled) {
testProxyRecordPolicy.stopRecording(proxyVariableQueue);
} else {
try (BufferedWriter writer = Files.newBufferedWriter(createRecordFile(playbackRecordName).toPath())) {
RECORD_MAPPER.writeValue(writer, recordedData);
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(
new UncheckedIOException("Unable to write data to playback file.", ex));
}
}
} else if (isPlaybackMode() && testProxyEnabled && allowedToReadRecordedValues) {
testProxyPlaybackClient.stopPlayback();
}
}
private RecordedData readDataFromFile() {
File recordFile = getRecordFile();
try (BufferedReader reader = Files.newBufferedReader(recordFile.toPath())) {
return RECORD_MAPPER.readValue(reader, RecordedData.class);
} catch (IOException ex) {
throw LOGGER.logExceptionAsWarning(new UncheckedIOException(ex));
}
}
private HttpPipelinePolicy getProxyRecordingPolicy() {
if (testProxyRecordPolicy == null) {
if (isLiveMode()) {
throw new RuntimeException("A recording policy cannot be requested in LIVE mode.");
}
testProxyRecordPolicy = new TestProxyRecordPolicy(httpClient);
testProxyRecordPolicy.startRecording(playbackRecordName);
}
return testProxyRecordPolicy;
}
/*
* Attempts to retrieve the playback file, if it is not found an exception is thrown as playback can't continue.
*/
private File getRecordFile() {
File recordFolder = TestUtils.getRecordFolder();
File playbackFile = new File(recordFolder, playbackRecordName + ".json");
File oldPlaybackFile = new File(recordFolder, testName + ".json");
if (!playbackFile.exists() && !oldPlaybackFile.exists()) {
throw LOGGER.logExceptionAsError(new RuntimeException(String.format(
"Missing both new and old playback files. Files are %s and %s.", playbackFile.getPath(),
oldPlaybackFile.getPath())));
}
if (playbackFile.exists()) {
LOGGER.info("==> Playback file path: {}", playbackFile.getPath());
return playbackFile;
} else {
LOGGER.info("==> Playback file path: {}", oldPlaybackFile.getPath());
return oldPlaybackFile;
}
}
/*
* Retrieves or creates the file that will be used to store the recorded test values.
*/
private File createRecordFile(String testName) throws IOException {
File recordFolder = TestUtils.getRecordFolder();
if (!recordFolder.exists()) {
if (recordFolder.mkdir()) {
LOGGER.verbose("Created directory: {}", recordFolder.getPath());
}
}
File recordFile = new File(recordFolder, testName + ".json");
if (recordFile.createNewFile()) {
LOGGER.verbose("Created record file: {}", recordFile.getPath());
}
LOGGER.info("==> Playback file path: " + recordFile);
return recordFile;
}
/**
* Add text replacement rule (regex as key, the replacement text as value) into
* {@link InterceptorManager
*
* @param regex the pattern to locate the position of replacement
* @param replacement the replacement text
*/
public void addTextReplacementRule(String regex, String replacement) {
textReplacementRules.put(regex, replacement);
}
/**
* Add sanitizer rule for sanitization during record or playback.
* @param testProxySanitizers the list of replacement regex and rules.
* @throws RuntimeException Neither playback or record has started.
*/
public void addSanitizers(List<TestProxySanitizer> testProxySanitizers) {
if (testProxyPlaybackClient != null) {
testProxyPlaybackClient.addProxySanitization(testProxySanitizers);
} else if (testProxyRecordPolicy != null) {
testProxyRecordPolicy.addProxySanitization(testProxySanitizers);
} else {
throw new RuntimeException("Playback or record must have been started before adding sanitizers.");
}
}
/**
* Add matcher rules to match recorded data in playback.
* @param testProxyMatchers the list of matcher rules when playing back recorded data.
* @throws RuntimeException Playback has not started.
*/
public void addMatchers(List<TestProxyRequestMatcher> testProxyMatchers) {
if (testProxyPlaybackClient != null) {
testProxyPlaybackClient.addMatcherRequests(testProxyMatchers);
} else {
throw new RuntimeException("Playback must have been started before adding matchers.");
}
}
/**
* Sets the httpClient to be used for this test.
* @param httpClient The {@link HttpClient} implementation to use.
*/
void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
} | class InterceptorManager implements AutoCloseable {
private static final ObjectMapper RECORD_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private static final ClientLogger LOGGER = new ClientLogger(InterceptorManager.class);
private final Map<String, String> textReplacementRules;
private final String testName;
private final String playbackRecordName;
private final TestMode testMode;
private final boolean allowedToReadRecordedValues;
private final boolean allowedToRecordValues;
private final RecordedData recordedData;
private final boolean testProxyEnabled;
private TestProxyRecordPolicy testProxyRecordPolicy;
private TestProxyPlaybackClient testProxyPlaybackClient;
private final Queue<String> proxyVariableQueue = new LinkedList<>();
private HttpClient httpClient;
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param testMode The {@link TestMode} for this interceptor.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, TestMode testMode) {
this(testName, testName, testMode, false, false);
}
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* <li>If {@code testMode} is {@link TestMode
* record.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode},
* and others.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
*/
public InterceptorManager(TestContextManager testContextManager) {
this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(),
testContextManager.getTestMode(), testContextManager.doNotRecordTest(), testContextManager.isTestProxyEnabled());
}
private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord, boolean enableTestProxy) {
this.testProxyEnabled = enableTestProxy;
Objects.requireNonNull(testName, "'testName' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = testMode;
this.textReplacementRules = new HashMap<>();
this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord);
this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord);
if (!enableTestProxy && allowedToReadRecordedValues) {
this.recordedData = readDataFromFile();
} else if (!enableTestProxy && allowedToRecordValues) {
this.recordedData = new RecordedData();
} else {
this.recordedData = null;
}
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules) {
this(testName, textReplacementRules, false, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord) {
this(testName, textReplacementRules, doNotRecord, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @param playbackRecordName Full name of the test including its iteration, used as the playback record name.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
*/
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord,
String playbackRecordName) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
Objects.requireNonNull(textReplacementRules, "'textReplacementRules' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = TestMode.PLAYBACK;
this.allowedToReadRecordedValues = !doNotRecord;
this.allowedToRecordValues = false;
this.testProxyEnabled = false;
this.recordedData = allowedToReadRecordedValues ? readDataFromFile() : null;
this.textReplacementRules = textReplacementRules;
}
/**
* Gets whether this InterceptorManager is in playback mode.
*
* @return true if the InterceptorManager is in playback mode and false otherwise.
*/
public boolean isPlaybackMode() {
return testMode == TestMode.PLAYBACK;
}
/**
* Gets whether this InterceptorManager is in live mode.
*
* @return true if the InterceptorManager is in live mode and false otherwise.
*/
public boolean isLiveMode() {
return testMode == TestMode.LIVE;
}
/**
* Gets whether this InterceptorManager is in record mode.
*
* @return true if the InterceptorManager is in record mode and false otherwise.
*/
public boolean isRecordMode() {
return testMode == TestMode.RECORD;
}
/**
* Gets the recorded data InterceptorManager is keeping track of.
*
* @return The recorded data managed by InterceptorManager.
*/
public RecordedData getRecordedData() {
return recordedData;
}
/**
* A {@link Supplier} for retrieving a variable from a test proxy recording.
* @return The supplier for retrieving a variable.
*/
public Supplier<String> getProxyVariableSupplier() {
return () -> {
Objects.requireNonNull(this.testProxyPlaybackClient, "Playback must be started to retrieve values");
if (!CoreUtils.isNullOrEmpty(proxyVariableQueue)) {
return proxyVariableQueue.remove();
} else {
throw LOGGER.logExceptionAsError(new RuntimeException("'proxyVariableQueue' cannot be null or empty."));
}
};
}
/**
* Get a {@link Consumer} for adding variables used in test proxy tests.
* @return The consumer for adding a variable.
*/
public Consumer<String> getProxyVariableConsumer() {
return proxyVariableQueue::add;
}
/**
* Gets a new HTTP pipeline policy that records network calls and its data is managed by
* {@link InterceptorManager}.
*
* @return HttpPipelinePolicy to record network calls.
*
* @throws IllegalStateException A recording policy was requested when the test proxy is enabled and test mode is not RECORD.
*/
public HttpPipelinePolicy getRecordPolicy() {
if (testProxyEnabled) {
return getProxyRecordingPolicy();
}
return getRecordPolicy(Collections.emptyList());
}
/**
* Gets a new HTTP pipeline policy that records network calls. The recorded content is redacted by the given list of
* redactor functions to hide sensitive information.
*
* @param recordingRedactors The custom redactor functions that are applied in addition to the default redactor
* functions defined in {@link RecordingRedactor}.
* @return {@link HttpPipelinePolicy} to record network calls.
*
* @throws IllegalStateException A recording policy was requested when the test proxy is enabled and test mode is not RECORD.
*/
public HttpPipelinePolicy getRecordPolicy(List<Function<String, String>> recordingRedactors) {
if (testProxyEnabled) {
return getProxyRecordingPolicy();
}
return new RecordNetworkCallPolicy(recordedData, recordingRedactors);
}
/**
* Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}.
*
* @return An HTTP client that plays back network calls from its recorded data.
*
* @throws IllegalStateException A playback client was requested when the test proxy is enabled and test mode is LIVE.
*/
/**
* Disposes of resources used by this InterceptorManager.
*
* If {@code testMode} is {@link TestMode
* "<i>session-records/{@code testName}.json</i>"
*/
@Override
public void close() {
if (allowedToRecordValues) {
if (testProxyEnabled) {
testProxyRecordPolicy.stopRecording(proxyVariableQueue);
} else {
try (BufferedWriter writer = Files.newBufferedWriter(createRecordFile(playbackRecordName).toPath())) {
RECORD_MAPPER.writeValue(writer, recordedData);
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(
new UncheckedIOException("Unable to write data to playback file.", ex));
}
}
} else if (isPlaybackMode() && testProxyEnabled && allowedToReadRecordedValues) {
testProxyPlaybackClient.stopPlayback();
}
}
private RecordedData readDataFromFile() {
File recordFile = getRecordFile();
try (BufferedReader reader = Files.newBufferedReader(recordFile.toPath())) {
return RECORD_MAPPER.readValue(reader, RecordedData.class);
} catch (IOException ex) {
throw LOGGER.logExceptionAsWarning(new UncheckedIOException(ex));
}
}
private HttpPipelinePolicy getProxyRecordingPolicy() {
if (testProxyRecordPolicy == null) {
if (!isRecordMode()) {
throw new IllegalStateException("A recording policy can only be requested in RECORD mode.");
}
testProxyRecordPolicy = new TestProxyRecordPolicy(httpClient);
testProxyRecordPolicy.startRecording(playbackRecordName);
}
return testProxyRecordPolicy;
}
/*
* Attempts to retrieve the playback file, if it is not found an exception is thrown as playback can't continue.
*/
private File getRecordFile() {
File recordFolder = TestUtils.getRecordFolder();
File playbackFile = new File(recordFolder, playbackRecordName + ".json");
File oldPlaybackFile = new File(recordFolder, testName + ".json");
if (!playbackFile.exists() && !oldPlaybackFile.exists()) {
throw LOGGER.logExceptionAsError(new RuntimeException(String.format(
"Missing both new and old playback files. Files are %s and %s.", playbackFile.getPath(),
oldPlaybackFile.getPath())));
}
if (playbackFile.exists()) {
LOGGER.info("==> Playback file path: {}", playbackFile.getPath());
return playbackFile;
} else {
LOGGER.info("==> Playback file path: {}", oldPlaybackFile.getPath());
return oldPlaybackFile;
}
}
/*
* Retrieves or creates the file that will be used to store the recorded test values.
*/
private File createRecordFile(String testName) throws IOException {
File recordFolder = TestUtils.getRecordFolder();
if (!recordFolder.exists()) {
if (recordFolder.mkdir()) {
LOGGER.verbose("Created directory: {}", recordFolder.getPath());
}
}
File recordFile = new File(recordFolder, testName + ".json");
if (recordFile.createNewFile()) {
LOGGER.verbose("Created record file: {}", recordFile.getPath());
}
LOGGER.info("==> Playback file path: " + recordFile);
return recordFile;
}
/**
* Add text replacement rule (regex as key, the replacement text as value) into
* {@link InterceptorManager
*
* @param regex the pattern to locate the position of replacement
* @param replacement the replacement text
*/
public void addTextReplacementRule(String regex, String replacement) {
textReplacementRules.put(regex, replacement);
}
/**
* Add sanitizer rule for sanitization during record or playback.
* @param testProxySanitizers the list of replacement regex and rules.
* @throws RuntimeException Neither playback or record has started.
*/
public void addSanitizers(List<TestProxySanitizer> testProxySanitizers) {
if (testProxyPlaybackClient != null) {
testProxyPlaybackClient.addProxySanitization(testProxySanitizers);
} else if (testProxyRecordPolicy != null) {
testProxyRecordPolicy.addProxySanitization(testProxySanitizers);
} else {
throw new RuntimeException("Playback or record must have been started before adding sanitizers.");
}
}
/**
* Add matcher rules to match recorded data in playback.
* @param testProxyMatchers the list of matcher rules when playing back recorded data.
* @throws RuntimeException Playback has not started.
*/
public void addMatchers(List<TestProxyRequestMatcher> testProxyMatchers) {
if (testProxyPlaybackClient != null) {
testProxyPlaybackClient.addMatcherRequests(testProxyMatchers);
} else {
throw new RuntimeException("Playback must have been started before adding matchers.");
}
}
/**
* Sets the httpClient to be used for this test.
* @param httpClient The {@link HttpClient} implementation to use.
*/
void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
} |
super nit: `IllegalStateException` (because guidelines) | public HttpClient getPlaybackClient() {
if (testProxyEnabled) {
if (isLiveMode()) {
throw new RuntimeException("A playback client cannot be requested in LIVE mode.");
}
if (testProxyPlaybackClient == null) {
testProxyPlaybackClient = new TestProxyPlaybackClient(httpClient);
proxyVariableQueue.addAll(testProxyPlaybackClient.startPlayback(playbackRecordName));
}
return testProxyPlaybackClient;
} else {
return new PlaybackClient(recordedData, textReplacementRules);
}
} | throw new RuntimeException("A playback client cannot be requested in LIVE mode."); | public HttpClient getPlaybackClient() {
if (testProxyEnabled) {
if (!isPlaybackMode()) {
throw new IllegalStateException("A playback client can only be requested in PLAYBACK mode.");
}
if (testProxyPlaybackClient == null) {
testProxyPlaybackClient = new TestProxyPlaybackClient(httpClient);
proxyVariableQueue.addAll(testProxyPlaybackClient.startPlayback(playbackRecordName));
}
return testProxyPlaybackClient;
} else {
return new PlaybackClient(recordedData, textReplacementRules);
}
} | class InterceptorManager implements AutoCloseable {
private static final ObjectMapper RECORD_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private static final ClientLogger LOGGER = new ClientLogger(InterceptorManager.class);
private final Map<String, String> textReplacementRules;
private final String testName;
private final String playbackRecordName;
private final TestMode testMode;
private final boolean allowedToReadRecordedValues;
private final boolean allowedToRecordValues;
private final RecordedData recordedData;
private final boolean testProxyEnabled;
private TestProxyRecordPolicy testProxyRecordPolicy;
private TestProxyPlaybackClient testProxyPlaybackClient;
private final Queue<String> proxyVariableQueue = new LinkedList<>();
private HttpClient httpClient;
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param testMode The {@link TestMode} for this interceptor.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, TestMode testMode) {
this(testName, testName, testMode, false, false);
}
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* <li>If {@code testMode} is {@link TestMode
* record.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode},
* and others.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
*/
public InterceptorManager(TestContextManager testContextManager) {
this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(),
testContextManager.getTestMode(), testContextManager.doNotRecordTest(), testContextManager.isTestProxyEnabled());
}
private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord, boolean enableTestProxy) {
this.testProxyEnabled = enableTestProxy;
Objects.requireNonNull(testName, "'testName' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = testMode;
this.textReplacementRules = new HashMap<>();
this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord);
this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord);
if (!enableTestProxy && allowedToReadRecordedValues) {
this.recordedData = readDataFromFile();
} else if (!enableTestProxy && allowedToRecordValues) {
this.recordedData = new RecordedData();
} else {
this.recordedData = null;
}
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules) {
this(testName, textReplacementRules, false, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord) {
this(testName, textReplacementRules, doNotRecord, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @param playbackRecordName Full name of the test including its iteration, used as the playback record name.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
*/
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord,
String playbackRecordName) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
Objects.requireNonNull(textReplacementRules, "'textReplacementRules' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = TestMode.PLAYBACK;
this.allowedToReadRecordedValues = !doNotRecord;
this.allowedToRecordValues = false;
this.testProxyEnabled = false;
this.recordedData = allowedToReadRecordedValues ? readDataFromFile() : null;
this.textReplacementRules = textReplacementRules;
}
/**
* Gets whether this InterceptorManager is in playback mode.
*
* @return true if the InterceptorManager is in playback mode and false otherwise.
*/
public boolean isPlaybackMode() {
return testMode == TestMode.PLAYBACK;
}
/**
* Gets whether this InterceptorManager is in live mode.
*
* @return true if the InterceptorManager is in live mode and false otherwise.
*/
public boolean isLiveMode() {
return testMode == TestMode.LIVE;
}
/**
* Gets the recorded data InterceptorManager is keeping track of.
*
* @return The recorded data managed by InterceptorManager.
*/
public RecordedData getRecordedData() {
return recordedData;
}
/**
* A {@link Supplier} for retrieving a variable from a test proxy recording.
* @return The supplier for retrieving a variable.
*/
public Supplier<String> getProxyVariableSupplier() {
return () -> {
Objects.requireNonNull(this.testProxyPlaybackClient, "Playback must be started to retrieve values");
if (!CoreUtils.isNullOrEmpty(proxyVariableQueue)) {
return proxyVariableQueue.remove();
} else {
throw LOGGER.logExceptionAsError(new RuntimeException("'proxyVariableQueue' cannot be null or empty."));
}
};
}
/**
* Get a {@link Consumer} for adding variables used in test proxy tests.
* @return The consumer for adding a variable.
*/
public Consumer<String> getProxyVariableConsumer() {
return proxyVariableQueue::add;
}
/**
* Gets a new HTTP pipeline policy that records network calls and its data is managed by
* {@link InterceptorManager}.
*
* @return HttpPipelinePolicy to record network calls.
*
* @throws RuntimeException A playback client was requested when the test proxy is enabled and test mode is LIVE.
*/
public HttpPipelinePolicy getRecordPolicy() {
if (testProxyEnabled) {
return getProxyRecordingPolicy();
}
return getRecordPolicy(Collections.emptyList());
}
/**
* Gets a new HTTP pipeline policy that records network calls. The recorded content is redacted by the given list of
* redactor functions to hide sensitive information.
*
* @param recordingRedactors The custom redactor functions that are applied in addition to the default redactor
* functions defined in {@link RecordingRedactor}.
* @return {@link HttpPipelinePolicy} to record network calls.
*/
public HttpPipelinePolicy getRecordPolicy(List<Function<String, String>> recordingRedactors) {
if (testProxyEnabled) {
return getProxyRecordingPolicy();
}
return new RecordNetworkCallPolicy(recordedData, recordingRedactors);
}
/**
* Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}.
*
* @return An HTTP client that plays back network calls from its recorded data.
*
* @throws RuntimeException A playback client was requested when the test proxy is enabled and test mode is LIVE.
*/
/**
* Disposes of resources used by this InterceptorManager.
*
* If {@code testMode} is {@link TestMode
* "<i>session-records/{@code testName}.json</i>"
*/
@Override
public void close() {
if (allowedToRecordValues) {
if (testProxyEnabled) {
testProxyRecordPolicy.stopRecording(proxyVariableQueue);
} else {
try (BufferedWriter writer = Files.newBufferedWriter(createRecordFile(playbackRecordName).toPath())) {
RECORD_MAPPER.writeValue(writer, recordedData);
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(
new UncheckedIOException("Unable to write data to playback file.", ex));
}
}
} else if (isPlaybackMode() && testProxyEnabled && allowedToReadRecordedValues) {
testProxyPlaybackClient.stopPlayback();
}
}
private RecordedData readDataFromFile() {
File recordFile = getRecordFile();
try (BufferedReader reader = Files.newBufferedReader(recordFile.toPath())) {
return RECORD_MAPPER.readValue(reader, RecordedData.class);
} catch (IOException ex) {
throw LOGGER.logExceptionAsWarning(new UncheckedIOException(ex));
}
}
private HttpPipelinePolicy getProxyRecordingPolicy() {
if (testProxyRecordPolicy == null) {
if (isLiveMode()) {
throw new RuntimeException("A recording policy cannot be requested in LIVE mode.");
}
testProxyRecordPolicy = new TestProxyRecordPolicy(httpClient);
testProxyRecordPolicy.startRecording(playbackRecordName);
}
return testProxyRecordPolicy;
}
/*
* Attempts to retrieve the playback file, if it is not found an exception is thrown as playback can't continue.
*/
private File getRecordFile() {
File recordFolder = TestUtils.getRecordFolder();
File playbackFile = new File(recordFolder, playbackRecordName + ".json");
File oldPlaybackFile = new File(recordFolder, testName + ".json");
if (!playbackFile.exists() && !oldPlaybackFile.exists()) {
throw LOGGER.logExceptionAsError(new RuntimeException(String.format(
"Missing both new and old playback files. Files are %s and %s.", playbackFile.getPath(),
oldPlaybackFile.getPath())));
}
if (playbackFile.exists()) {
LOGGER.info("==> Playback file path: {}", playbackFile.getPath());
return playbackFile;
} else {
LOGGER.info("==> Playback file path: {}", oldPlaybackFile.getPath());
return oldPlaybackFile;
}
}
/*
* Retrieves or creates the file that will be used to store the recorded test values.
*/
private File createRecordFile(String testName) throws IOException {
File recordFolder = TestUtils.getRecordFolder();
if (!recordFolder.exists()) {
if (recordFolder.mkdir()) {
LOGGER.verbose("Created directory: {}", recordFolder.getPath());
}
}
File recordFile = new File(recordFolder, testName + ".json");
if (recordFile.createNewFile()) {
LOGGER.verbose("Created record file: {}", recordFile.getPath());
}
LOGGER.info("==> Playback file path: " + recordFile);
return recordFile;
}
/**
* Add text replacement rule (regex as key, the replacement text as value) into
* {@link InterceptorManager
*
* @param regex the pattern to locate the position of replacement
* @param replacement the replacement text
*/
public void addTextReplacementRule(String regex, String replacement) {
textReplacementRules.put(regex, replacement);
}
/**
* Add sanitizer rule for sanitization during record or playback.
* @param testProxySanitizers the list of replacement regex and rules.
* @throws RuntimeException Neither playback or record has started.
*/
public void addSanitizers(List<TestProxySanitizer> testProxySanitizers) {
if (testProxyPlaybackClient != null) {
testProxyPlaybackClient.addProxySanitization(testProxySanitizers);
} else if (testProxyRecordPolicy != null) {
testProxyRecordPolicy.addProxySanitization(testProxySanitizers);
} else {
throw new RuntimeException("Playback or record must have been started before adding sanitizers.");
}
}
/**
* Add matcher rules to match recorded data in playback.
* @param testProxyMatchers the list of matcher rules when playing back recorded data.
* @throws RuntimeException Playback has not started.
*/
public void addMatchers(List<TestProxyRequestMatcher> testProxyMatchers) {
if (testProxyPlaybackClient != null) {
testProxyPlaybackClient.addMatcherRequests(testProxyMatchers);
} else {
throw new RuntimeException("Playback must have been started before adding matchers.");
}
}
/**
* Sets the httpClient to be used for this test.
* @param httpClient The {@link HttpClient} implementation to use.
*/
void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
} | class InterceptorManager implements AutoCloseable {
private static final ObjectMapper RECORD_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private static final ClientLogger LOGGER = new ClientLogger(InterceptorManager.class);
private final Map<String, String> textReplacementRules;
private final String testName;
private final String playbackRecordName;
private final TestMode testMode;
private final boolean allowedToReadRecordedValues;
private final boolean allowedToRecordValues;
private final RecordedData recordedData;
private final boolean testProxyEnabled;
private TestProxyRecordPolicy testProxyRecordPolicy;
private TestProxyPlaybackClient testProxyPlaybackClient;
private final Queue<String> proxyVariableQueue = new LinkedList<>();
private HttpClient httpClient;
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param testMode The {@link TestMode} for this interceptor.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, TestMode testMode) {
this(testName, testName, testMode, false, false);
}
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* <li>If {@code testMode} is {@link TestMode
* record.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode},
* and others.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
*/
public InterceptorManager(TestContextManager testContextManager) {
this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(),
testContextManager.getTestMode(), testContextManager.doNotRecordTest(), testContextManager.isTestProxyEnabled());
}
private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord, boolean enableTestProxy) {
this.testProxyEnabled = enableTestProxy;
Objects.requireNonNull(testName, "'testName' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = testMode;
this.textReplacementRules = new HashMap<>();
this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord);
this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord);
if (!enableTestProxy && allowedToReadRecordedValues) {
this.recordedData = readDataFromFile();
} else if (!enableTestProxy && allowedToRecordValues) {
this.recordedData = new RecordedData();
} else {
this.recordedData = null;
}
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules) {
this(testName, textReplacementRules, false, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord) {
this(testName, textReplacementRules, doNotRecord, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of
* {@code textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a
* {@link NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @param playbackRecordName Full name of the test including its iteration, used as the playback record name.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
*/
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord,
String playbackRecordName) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
Objects.requireNonNull(textReplacementRules, "'textReplacementRules' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = TestMode.PLAYBACK;
this.allowedToReadRecordedValues = !doNotRecord;
this.allowedToRecordValues = false;
this.testProxyEnabled = false;
this.recordedData = allowedToReadRecordedValues ? readDataFromFile() : null;
this.textReplacementRules = textReplacementRules;
}
/**
* Gets whether this InterceptorManager is in playback mode.
*
* @return true if the InterceptorManager is in playback mode and false otherwise.
*/
public boolean isPlaybackMode() {
return testMode == TestMode.PLAYBACK;
}
/**
* Gets whether this InterceptorManager is in live mode.
*
* @return true if the InterceptorManager is in live mode and false otherwise.
*/
public boolean isLiveMode() {
return testMode == TestMode.LIVE;
}
/**
* Gets whether this InterceptorManager is in record mode.
*
* @return true if the InterceptorManager is in record mode and false otherwise.
*/
public boolean isRecordMode() {
return testMode == TestMode.RECORD;
}
/**
* Gets the recorded data InterceptorManager is keeping track of.
*
* @return The recorded data managed by InterceptorManager.
*/
public RecordedData getRecordedData() {
return recordedData;
}
/**
* A {@link Supplier} for retrieving a variable from a test proxy recording.
* @return The supplier for retrieving a variable.
*/
public Supplier<String> getProxyVariableSupplier() {
return () -> {
Objects.requireNonNull(this.testProxyPlaybackClient, "Playback must be started to retrieve values");
if (!CoreUtils.isNullOrEmpty(proxyVariableQueue)) {
return proxyVariableQueue.remove();
} else {
throw LOGGER.logExceptionAsError(new RuntimeException("'proxyVariableQueue' cannot be null or empty."));
}
};
}
/**
* Get a {@link Consumer} for adding variables used in test proxy tests.
* @return The consumer for adding a variable.
*/
public Consumer<String> getProxyVariableConsumer() {
return proxyVariableQueue::add;
}
/**
* Gets a new HTTP pipeline policy that records network calls and its data is managed by
* {@link InterceptorManager}.
*
* @return HttpPipelinePolicy to record network calls.
*
* @throws IllegalStateException A recording policy was requested when the test proxy is enabled and test mode is not RECORD.
*/
public HttpPipelinePolicy getRecordPolicy() {
if (testProxyEnabled) {
return getProxyRecordingPolicy();
}
return getRecordPolicy(Collections.emptyList());
}
/**
* Gets a new HTTP pipeline policy that records network calls. The recorded content is redacted by the given list of
* redactor functions to hide sensitive information.
*
* @param recordingRedactors The custom redactor functions that are applied in addition to the default redactor
* functions defined in {@link RecordingRedactor}.
* @return {@link HttpPipelinePolicy} to record network calls.
*
* @throws IllegalStateException A recording policy was requested when the test proxy is enabled and test mode is not RECORD.
*/
public HttpPipelinePolicy getRecordPolicy(List<Function<String, String>> recordingRedactors) {
if (testProxyEnabled) {
return getProxyRecordingPolicy();
}
return new RecordNetworkCallPolicy(recordedData, recordingRedactors);
}
/**
* Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}.
*
* @return An HTTP client that plays back network calls from its recorded data.
*
* @throws IllegalStateException A playback client was requested when the test proxy is enabled and test mode is LIVE.
*/
/**
* Disposes of resources used by this InterceptorManager.
*
* If {@code testMode} is {@link TestMode
* "<i>session-records/{@code testName}.json</i>"
*/
@Override
public void close() {
if (allowedToRecordValues) {
if (testProxyEnabled) {
testProxyRecordPolicy.stopRecording(proxyVariableQueue);
} else {
try (BufferedWriter writer = Files.newBufferedWriter(createRecordFile(playbackRecordName).toPath())) {
RECORD_MAPPER.writeValue(writer, recordedData);
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(
new UncheckedIOException("Unable to write data to playback file.", ex));
}
}
} else if (isPlaybackMode() && testProxyEnabled && allowedToReadRecordedValues) {
testProxyPlaybackClient.stopPlayback();
}
}
private RecordedData readDataFromFile() {
File recordFile = getRecordFile();
try (BufferedReader reader = Files.newBufferedReader(recordFile.toPath())) {
return RECORD_MAPPER.readValue(reader, RecordedData.class);
} catch (IOException ex) {
throw LOGGER.logExceptionAsWarning(new UncheckedIOException(ex));
}
}
private HttpPipelinePolicy getProxyRecordingPolicy() {
if (testProxyRecordPolicy == null) {
if (!isRecordMode()) {
throw new IllegalStateException("A recording policy can only be requested in RECORD mode.");
}
testProxyRecordPolicy = new TestProxyRecordPolicy(httpClient);
testProxyRecordPolicy.startRecording(playbackRecordName);
}
return testProxyRecordPolicy;
}
/*
* Attempts to retrieve the playback file, if it is not found an exception is thrown as playback can't continue.
*/
private File getRecordFile() {
File recordFolder = TestUtils.getRecordFolder();
File playbackFile = new File(recordFolder, playbackRecordName + ".json");
File oldPlaybackFile = new File(recordFolder, testName + ".json");
if (!playbackFile.exists() && !oldPlaybackFile.exists()) {
throw LOGGER.logExceptionAsError(new RuntimeException(String.format(
"Missing both new and old playback files. Files are %s and %s.", playbackFile.getPath(),
oldPlaybackFile.getPath())));
}
if (playbackFile.exists()) {
LOGGER.info("==> Playback file path: {}", playbackFile.getPath());
return playbackFile;
} else {
LOGGER.info("==> Playback file path: {}", oldPlaybackFile.getPath());
return oldPlaybackFile;
}
}
/*
* Retrieves or creates the file that will be used to store the recorded test values.
*/
private File createRecordFile(String testName) throws IOException {
File recordFolder = TestUtils.getRecordFolder();
if (!recordFolder.exists()) {
if (recordFolder.mkdir()) {
LOGGER.verbose("Created directory: {}", recordFolder.getPath());
}
}
File recordFile = new File(recordFolder, testName + ".json");
if (recordFile.createNewFile()) {
LOGGER.verbose("Created record file: {}", recordFile.getPath());
}
LOGGER.info("==> Playback file path: " + recordFile);
return recordFile;
}
/**
* Add text replacement rule (regex as key, the replacement text as value) into
* {@link InterceptorManager
*
* @param regex the pattern to locate the position of replacement
* @param replacement the replacement text
*/
public void addTextReplacementRule(String regex, String replacement) {
textReplacementRules.put(regex, replacement);
}
/**
* Add sanitizer rule for sanitization during record or playback.
* @param testProxySanitizers the list of replacement regex and rules.
* @throws RuntimeException Neither playback or record has started.
*/
public void addSanitizers(List<TestProxySanitizer> testProxySanitizers) {
if (testProxyPlaybackClient != null) {
testProxyPlaybackClient.addProxySanitization(testProxySanitizers);
} else if (testProxyRecordPolicy != null) {
testProxyRecordPolicy.addProxySanitization(testProxySanitizers);
} else {
throw new RuntimeException("Playback or record must have been started before adding sanitizers.");
}
}
/**
* Add matcher rules to match recorded data in playback.
* @param testProxyMatchers the list of matcher rules when playing back recorded data.
* @throws RuntimeException Playback has not started.
*/
public void addMatchers(List<TestProxyRequestMatcher> testProxyMatchers) {
if (testProxyPlaybackClient != null) {
testProxyPlaybackClient.addMatcherRequests(testProxyMatchers);
} else {
throw new RuntimeException("Playback must have been started before adding matchers.");
}
}
/**
* Sets the httpClient to be used for this test.
* @param httpClient The {@link HttpClient} implementation to use.
*/
void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
} |
This will be a future enhancement, but long term we should support writes larger than 2 GB, likely through managing multiple `ByteBuffer`s internally. I don't believe this is something we should hold the feature back on before GAing it. | public SeekableByteChannel openSeekableByteChannelWrite(BlockBlobSeekableByteChannelWriteOptions options) {
Objects.requireNonNull(options);
StorageSeekableByteChannelBlockBlobWriteBehavior.WriteMode internalMode;
long startingPosition = 0L;
if (options.getWriteMode() == BlockBlobSeekableByteChannelWriteOptions.WriteMode.OVERWRITE) {
internalMode = StorageSeekableByteChannelBlockBlobWriteBehavior.WriteMode.OVERWRITE;
} else {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Unsupported value for `options.getWriteMode()`."));
}
return new StorageSeekableByteChannel(
options.getChunkSize() != null
? options.getChunkSize().intValue()
: BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE,
new StorageSeekableByteChannelBlockBlobWriteBehavior(this, options.getHeaders(), options.getMetadata(),
options.getTags(), options.getTier(), options.getRequestConditions(), internalMode, null),
startingPosition);
} | : BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE, | public SeekableByteChannel openSeekableByteChannelWrite(BlockBlobSeekableByteChannelWriteOptions options) {
Objects.requireNonNull(options);
StorageSeekableByteChannelBlockBlobWriteBehavior.WriteMode internalMode;
long startingPosition = 0L;
if (options.getWriteMode() == BlockBlobSeekableByteChannelWriteOptions.WriteMode.OVERWRITE) {
internalMode = StorageSeekableByteChannelBlockBlobWriteBehavior.WriteMode.OVERWRITE;
} else {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Unsupported value for `options.getWriteMode()`."));
}
return new StorageSeekableByteChannel(
options.getChunkSize() != null
? options.getChunkSize().intValue()
: BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE,
new StorageSeekableByteChannelBlockBlobWriteBehavior(this, options.getHeaders(), options.getMetadata(),
options.getTags(), options.getTier(), options.getRequestConditions(), internalMode, null),
startingPosition);
} | class BlockBlobClient extends BlobClientBase {
private static final ClientLogger LOGGER = new ClientLogger(BlockBlobClient.class);
private final BlockBlobAsyncClient client;
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
* @deprecated Use {@link
*/
@Deprecated
public static final int MAX_UPLOAD_BLOB_BYTES = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES;
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
*/
public static final long MAX_UPLOAD_BLOB_BYTES_LONG = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES_LONG;
/**
* Indicates the maximum number of bytes that can be sent in a call to stageBlock.
* @deprecated Use {@link
*/
@Deprecated
public static final int MAX_STAGE_BLOCK_BYTES = BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES;
/**
* Indicates the maximum number of bytes that can be sent in a call to stageBlock.
*/
public static final long MAX_STAGE_BLOCK_BYTES_LONG = BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES_LONG;
/**
* Indicates the maximum number of blocks allowed in a block blob.
*/
public static final int MAX_BLOCKS = BlockBlobAsyncClient.MAX_BLOCKS;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param client the async block blob client
*/
BlockBlobClient(BlockBlobAsyncClient client) {
super(client);
this.client = client;
}
/**
* Creates a new {@link BlockBlobClient} with the specified {@code encryptionScope}.
*
* @param encryptionScope the encryption scope for the blob, pass {@code null} to use no encryption scope.
* @return a {@link BlockBlobClient} with the specified {@code encryptionScope}.
*/
@Override
public BlockBlobClient getEncryptionScopeClient(String encryptionScope) {
return new BlockBlobClient(client.getEncryptionScopeAsyncClient(encryptionScope));
}
/**
* Creates a new {@link BlockBlobClient} with the specified {@code customerProvidedKey}.
*
* @param customerProvidedKey the {@link CustomerProvidedKey} for the blob,
* pass {@code null} to use no customer provided key.
* @return a {@link BlockBlobClient} with the specified {@code customerProvidedKey}.
*/
@Override
public BlockBlobClient getCustomerProvidedKeyClient(CustomerProvidedKey customerProvidedKey) {
return new BlockBlobClient(client.getCustomerProvidedKeyAsyncClient(customerProvidedKey));
}
/**
* Creates and opens an output stream to write data to the block blob.
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream() {
return getBlobOutputStream(false);
}
/**
* Creates and opens an output stream to write data to the block blob.
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(boolean overwrite) {
BlobRequestConditions requestConditions = null;
if (!overwrite) {
if (exists()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS));
}
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return getBlobOutputStream(requestConditions);
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param requestConditions A {@link BlobRequestConditions} object that represents the access conditions for the
* blob.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(BlobRequestConditions requestConditions) {
return getBlobOutputStream(null, null, null, null, requestConditions);
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(ParallelTransferOptions parallelTransferOptions,
BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier,
BlobRequestConditions requestConditions) {
return this.getBlobOutputStream(new BlockBlobOutputStreamOptions()
.setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata).setTier(tier)
.setRequestConditions(requestConditions));
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param options {@link BlockBlobOutputStreamOptions}
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(BlockBlobOutputStreamOptions options) {
BlobAsyncClient blobClient = prepareBuilder().buildAsyncClient();
return BlobOutputStream.blockBlobOutputStream(blobClient, options, null);
}
/**
* Opens a seekable byte channel in write-only mode to upload the blob.
*
* @param options {@link BlobSeekableByteChannelReadOptions}
* @return A <code>SeekableByteChannel</code> object that represents the channel to use for writing to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
private BlobClientBuilder prepareBuilder() {
BlobClientBuilder builder = new BlobClientBuilder()
.pipeline(getHttpPipeline())
.endpoint(getBlobUrl())
.snapshot(getSnapshotId())
.serviceVersion(getServiceVersion());
CpkInfo cpk = getCustomerProvidedKey();
if (cpk != null) {
builder.customerProvidedKey(new CustomerProvidedKey(cpk.getEncryptionKey()));
}
return builder;
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob. Updating an existing block
* blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content
* of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use
* PutBlock and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @return The information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(InputStream data, long length) {
return upload(data, length, false);
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob. Updating an existing block
* blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content
* of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use
* PutBlock and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* BinaryData binaryData = BinaryData.fromStream&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(BinaryData data) {
return upload(data, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* boolean overwrite = false;
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(InputStream data, long length, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadWithResponse(data, length, null, null, null, null, blobRequestConditions, null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* boolean overwrite = false;
* BinaryData binaryData = BinaryData.fromStream&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(BinaryData data, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadWithResponse(
new BlockBlobSimpleUploadOptions(data)
.setRequestConditions(blobRequestConditions),
null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* requestConditions, timeout, context&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param contentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block during
* transport. When this header is specified, the storage service compares the hash of the content that has arrived
* with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the
* operation will fail.
* @param requestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the uploaded block blob.
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadWithResponse(InputStream data, long length, BlobHttpHeaders headers,
Map<String, String> metadata, AccessTier tier, byte[] contentMd5, BlobRequestConditions requestConditions,
Duration timeout, Context context) {
return this.uploadWithResponse(new BlockBlobSimpleUploadOptions(data, length).setHeaders(headers)
.setMetadata(metadata).setTier(tier).setContentMd5(contentMd5).setRequestConditions(requestConditions),
timeout, context);
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* .setHeaders&
* .setRequestConditions&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
*
* @param options {@link BlockBlobSimpleUploadOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the uploaded block blob.
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadWithResponse(BlockBlobSimpleUploadOptions options, Duration timeout,
Context context) {
StorageImplUtils.assertNotNull("options", options);
Mono<Response<BlockBlobItem>> upload = client.uploadWithResponse(options, context);
try {
return blockWithOptionalTimeout(upload, timeout);
} catch (UncheckedIOException e) {
throw LOGGER.logExceptionAsError(e);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
* <pre>
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
*
* @param sourceUrl The source URL to upload from.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem uploadFromUrl(String sourceUrl) {
return uploadFromUrl(sourceUrl, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
* <pre>
* boolean overwrite = false;
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
*
* @param sourceUrl The source URL to upload from.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem uploadFromUrl(String sourceUrl, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadFromUrlWithResponse(
new BlobUploadFromUrlOptions(sourceUrl).setDestinationRequestConditions(blobRequestConditions),
null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* .setHeaders&
* .setDestinationRequestConditions&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse
*
* @param options {@link BlobUploadFromUrlOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadFromUrlWithResponse(BlobUploadFromUrlOptions options, Duration timeout,
Context context) {
StorageImplUtils.assertNotNull("options", options);
Mono<Response<BlockBlobItem>> upload = client.uploadFromUrlWithResponse(options, context);
try {
return blockWithOptionalTimeout(upload, timeout);
} catch (UncheckedIOException e) {
throw LOGGER.logExceptionAsError(e);
}
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
* <pre>
* client.stageBlock&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlock(String base64BlockId, InputStream data, long length) {
stageBlockWithResponse(base64BlockId, data, length, null, null, null, Context.NONE);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
* <pre>
* BinaryData binaryData = BinaryData.fromStream&
* client.stageBlock&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlock(String base64BlockId, BinaryData data) {
stageBlockWithResponse(new BlockBlobStageBlockOptions(base64BlockId, data), null, Context.NONE);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
* <pre>
* Context context = new Context&
* System.out.printf&
* client.stageBlockWithResponse&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param contentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block during
* transport. When this header is specified, the storage service compares the hash of the content that has arrived
* with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the
* operation will fail.
* @param leaseId The lease ID the active lease on the blob must match.
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockWithResponse(String base64BlockId, InputStream data, long length, byte[] contentMd5,
String leaseId, Duration timeout, Context context) {
StorageImplUtils.assertNotNull("data", data);
Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length,
BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE, true);
Mono<Response<Void>> response = client.stageBlockWithResponse(base64BlockId, fbb, length, contentMd5, leaseId,
context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
* <pre>
* Context context = new Context&
* BinaryData binaryData = BinaryData.fromStream&
* BlockBlobStageBlockOptions options = new BlockBlobStageBlockOptions&
* .setContentMd5&
* .setLeaseId&
* System.out.printf&
* client.stageBlockWithResponse&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
*
* @param options {@link BlockBlobStageBlockOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input options is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockWithResponse(BlockBlobStageBlockOptions options, Duration timeout, Context context) {
Objects.requireNonNull(options, "options must not be null");
Mono<Response<Void>> response = client.stageBlockWithResponse(
options.getBase64BlockId(), options.getData(), options.getContentMd5(), options.getLeaseId(), context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl
* <pre>
* client.stageBlockFromUrl&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param sourceUrl The url to the blob that will be the source of the copy. A source blob in the same storage
* account can be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is public, no
* authentication is required to perform the operation.
* @param sourceRange {@link BlobRange}
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlockFromUrl(String base64BlockId, String sourceUrl, BlobRange sourceRange) {
stageBlockFromUrlWithResponse(base64BlockId, sourceUrl, sourceRange, null, null, null, null, Context.NONE);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
* <pre>
* BlobRequestConditions sourceRequestConditions = new BlobRequestConditions&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.stageBlockFromUrlWithResponse&
* leaseId, sourceRequestConditions, timeout, context&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param sourceUrl The url to the blob that will be the source of the copy. A source blob in the same storage
* account can be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is public, no
* authentication is required to perform the operation.
* @param sourceRange {@link BlobRange}
* @param sourceContentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block
* during transport. When this header is specified, the storage service compares the hash of the content that has
* arrived with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not
* match, the operation will fail.
* @param leaseId The lease ID that the active lease on the blob must match.
* @param sourceRequestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockFromUrlWithResponse(String base64BlockId, String sourceUrl, BlobRange sourceRange,
byte[] sourceContentMd5, String leaseId, BlobRequestConditions sourceRequestConditions, Duration timeout,
Context context) {
return stageBlockFromUrlWithResponse(new BlockBlobStageBlockFromUrlOptions(base64BlockId, sourceUrl)
.setSourceRange(sourceRange).setSourceContentMd5(sourceContentMd5).setLeaseId(leaseId)
.setSourceRequestConditions(sourceRequestConditions), timeout, context);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
* <pre>
* BlobRequestConditions sourceRequestConditions = new BlobRequestConditions&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.stageBlockFromUrlWithResponse&
* .setSourceRange&
* .setSourceRequestConditions&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
*
* @param options Parameters for the operation
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockFromUrlWithResponse(BlockBlobStageBlockFromUrlOptions options, Duration timeout,
Context context) {
Mono<Response<Void>> response = client.stageBlockFromUrlWithResponse(options, context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list filter.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocks
* <pre>
* BlockList block = client.listBlocks&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocks
*
* @param listType Specifies which type of blocks to return.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockList listBlocks(BlockListType listType) {
return this.listBlocksWithResponse(listType, null, null, Context.NONE).getValue();
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list
* filter. For more information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
* <pre>
* Context context = new Context&
* BlockList block = client.listBlocksWithResponse&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
*
* @param listType Specifies which type of blocks to return.
* @param leaseId The lease ID the active lease on the blob must match.
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockList> listBlocksWithResponse(BlockListType listType, String leaseId, Duration timeout,
Context context) {
return listBlocksWithResponse(new BlockBlobListBlocksOptions(listType).setLeaseId(leaseId), timeout, context);
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list
* filter. For more information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
* <pre>
* Context context = new Context&
* BlockList block = client.listBlocksWithResponse&
* .setLeaseId&
* .setIfTagsMatch&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
*
* @param options {@link BlockBlobListBlocksOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockList> listBlocksWithResponse(BlockBlobListBlocksOptions options, Duration timeout,
Context context) {
return blockWithOptionalTimeout(client.listBlocksWithResponse(options, context), timeout);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can call
* commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new and
* existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
* <pre>
* System.out.printf&
* client.commitBlockList&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem commitBlockList(List<String> base64BlockIds) {
return commitBlockList(base64BlockIds, false);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can call
* commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new and
* existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
* <pre>
* boolean overwrite = false; &
* System.out.printf&
* client.commitBlockList&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem commitBlockList(List<String> base64BlockIds, boolean overwrite) {
BlobRequestConditions requestConditions = null;
if (!overwrite) {
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return commitBlockListWithResponse(base64BlockIds, null, null, null, requestConditions, null, Context.NONE)
.getValue();
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part
* of a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can
* call commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new
* and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.commitBlockListWithResponse&
* AccessTier.HOT, requestConditions, timeout, context&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> commitBlockListWithResponse(List<String> base64BlockIds, BlobHttpHeaders headers,
Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions, Duration timeout,
Context context) {
return this.commitBlockListWithResponse(new BlockBlobCommitBlockListOptions(base64BlockIds)
.setHeaders(headers).setMetadata(metadata).setTier(tier).setRequestConditions(requestConditions),
timeout, context);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part
* of a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can
* call commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new
* and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.commitBlockListWithResponse&
* new BlockBlobCommitBlockListOptions&
* .setMetadata&
* .setRequestConditions&
* .getStatusCode&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
*
* @param options {@link BlockBlobCommitBlockListOptions options}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> commitBlockListWithResponse(BlockBlobCommitBlockListOptions options,
Duration timeout, Context context) {
Mono<Response<BlockBlobItem>> response = client.commitBlockListWithResponse(
options, context);
return blockWithOptionalTimeout(response, timeout);
}
} | class BlockBlobClient extends BlobClientBase {
private static final ClientLogger LOGGER = new ClientLogger(BlockBlobClient.class);
private final BlockBlobAsyncClient client;
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
* @deprecated Use {@link
*/
@Deprecated
public static final int MAX_UPLOAD_BLOB_BYTES = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES;
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
*/
public static final long MAX_UPLOAD_BLOB_BYTES_LONG = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES_LONG;
/**
* Indicates the maximum number of bytes that can be sent in a call to stageBlock.
* @deprecated Use {@link
*/
@Deprecated
public static final int MAX_STAGE_BLOCK_BYTES = BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES;
/**
* Indicates the maximum number of bytes that can be sent in a call to stageBlock.
*/
public static final long MAX_STAGE_BLOCK_BYTES_LONG = BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES_LONG;
/**
* Indicates the maximum number of blocks allowed in a block blob.
*/
public static final int MAX_BLOCKS = BlockBlobAsyncClient.MAX_BLOCKS;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param client the async block blob client
*/
BlockBlobClient(BlockBlobAsyncClient client) {
super(client);
this.client = client;
}
/**
* Creates a new {@link BlockBlobClient} with the specified {@code encryptionScope}.
*
* @param encryptionScope the encryption scope for the blob, pass {@code null} to use no encryption scope.
* @return a {@link BlockBlobClient} with the specified {@code encryptionScope}.
*/
@Override
public BlockBlobClient getEncryptionScopeClient(String encryptionScope) {
return new BlockBlobClient(client.getEncryptionScopeAsyncClient(encryptionScope));
}
/**
* Creates a new {@link BlockBlobClient} with the specified {@code customerProvidedKey}.
*
* @param customerProvidedKey the {@link CustomerProvidedKey} for the blob,
* pass {@code null} to use no customer provided key.
* @return a {@link BlockBlobClient} with the specified {@code customerProvidedKey}.
*/
@Override
public BlockBlobClient getCustomerProvidedKeyClient(CustomerProvidedKey customerProvidedKey) {
return new BlockBlobClient(client.getCustomerProvidedKeyAsyncClient(customerProvidedKey));
}
/**
* Creates and opens an output stream to write data to the block blob.
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream() {
return getBlobOutputStream(false);
}
/**
* Creates and opens an output stream to write data to the block blob.
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(boolean overwrite) {
BlobRequestConditions requestConditions = null;
if (!overwrite) {
if (exists()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS));
}
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return getBlobOutputStream(requestConditions);
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param requestConditions A {@link BlobRequestConditions} object that represents the access conditions for the
* blob.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(BlobRequestConditions requestConditions) {
return getBlobOutputStream(null, null, null, null, requestConditions);
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(ParallelTransferOptions parallelTransferOptions,
BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier,
BlobRequestConditions requestConditions) {
return this.getBlobOutputStream(new BlockBlobOutputStreamOptions()
.setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata).setTier(tier)
.setRequestConditions(requestConditions));
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param options {@link BlockBlobOutputStreamOptions}
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(BlockBlobOutputStreamOptions options) {
BlobAsyncClient blobClient = prepareBuilder().buildAsyncClient();
return BlobOutputStream.blockBlobOutputStream(blobClient, options, null);
}
/**
* Opens a seekable byte channel in write-only mode to upload the blob.
*
* @param options {@link BlobSeekableByteChannelReadOptions}
* @return A <code>SeekableByteChannel</code> object that represents the channel to use for writing to the blob.
* @throws BlobStorageException If a storage service error occurred.
* @throws NullPointerException if 'options' is null.
*/
private BlobClientBuilder prepareBuilder() {
BlobClientBuilder builder = new BlobClientBuilder()
.pipeline(getHttpPipeline())
.endpoint(getBlobUrl())
.snapshot(getSnapshotId())
.serviceVersion(getServiceVersion());
CpkInfo cpk = getCustomerProvidedKey();
if (cpk != null) {
builder.customerProvidedKey(new CustomerProvidedKey(cpk.getEncryptionKey()));
}
return builder;
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob. Updating an existing block
* blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content
* of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use
* PutBlock and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @return The information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(InputStream data, long length) {
return upload(data, length, false);
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob. Updating an existing block
* blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content
* of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use
* PutBlock and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* BinaryData binaryData = BinaryData.fromStream&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(BinaryData data) {
return upload(data, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* boolean overwrite = false;
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(InputStream data, long length, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadWithResponse(data, length, null, null, null, null, blobRequestConditions, null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* boolean overwrite = false;
* BinaryData binaryData = BinaryData.fromStream&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(BinaryData data, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadWithResponse(
new BlockBlobSimpleUploadOptions(data)
.setRequestConditions(blobRequestConditions),
null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* requestConditions, timeout, context&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param contentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block during
* transport. When this header is specified, the storage service compares the hash of the content that has arrived
* with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the
* operation will fail.
* @param requestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the uploaded block blob.
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadWithResponse(InputStream data, long length, BlobHttpHeaders headers,
Map<String, String> metadata, AccessTier tier, byte[] contentMd5, BlobRequestConditions requestConditions,
Duration timeout, Context context) {
return this.uploadWithResponse(new BlockBlobSimpleUploadOptions(data, length).setHeaders(headers)
.setMetadata(metadata).setTier(tier).setContentMd5(contentMd5).setRequestConditions(requestConditions),
timeout, context);
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* .setHeaders&
* .setRequestConditions&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
*
* @param options {@link BlockBlobSimpleUploadOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the uploaded block blob.
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadWithResponse(BlockBlobSimpleUploadOptions options, Duration timeout,
Context context) {
StorageImplUtils.assertNotNull("options", options);
Mono<Response<BlockBlobItem>> upload = client.uploadWithResponse(options, context);
try {
return blockWithOptionalTimeout(upload, timeout);
} catch (UncheckedIOException e) {
throw LOGGER.logExceptionAsError(e);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
* <pre>
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
*
* @param sourceUrl The source URL to upload from.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem uploadFromUrl(String sourceUrl) {
return uploadFromUrl(sourceUrl, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
* <pre>
* boolean overwrite = false;
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
*
* @param sourceUrl The source URL to upload from.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem uploadFromUrl(String sourceUrl, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadFromUrlWithResponse(
new BlobUploadFromUrlOptions(sourceUrl).setDestinationRequestConditions(blobRequestConditions),
null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* .setHeaders&
* .setDestinationRequestConditions&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse
*
* @param options {@link BlobUploadFromUrlOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadFromUrlWithResponse(BlobUploadFromUrlOptions options, Duration timeout,
Context context) {
StorageImplUtils.assertNotNull("options", options);
Mono<Response<BlockBlobItem>> upload = client.uploadFromUrlWithResponse(options, context);
try {
return blockWithOptionalTimeout(upload, timeout);
} catch (UncheckedIOException e) {
throw LOGGER.logExceptionAsError(e);
}
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
* <pre>
* client.stageBlock&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlock(String base64BlockId, InputStream data, long length) {
stageBlockWithResponse(base64BlockId, data, length, null, null, null, Context.NONE);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
* <pre>
* BinaryData binaryData = BinaryData.fromStream&
* client.stageBlock&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlock(String base64BlockId, BinaryData data) {
stageBlockWithResponse(new BlockBlobStageBlockOptions(base64BlockId, data), null, Context.NONE);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
* <pre>
* Context context = new Context&
* System.out.printf&
* client.stageBlockWithResponse&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param contentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block during
* transport. When this header is specified, the storage service compares the hash of the content that has arrived
* with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the
* operation will fail.
* @param leaseId The lease ID the active lease on the blob must match.
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockWithResponse(String base64BlockId, InputStream data, long length, byte[] contentMd5,
String leaseId, Duration timeout, Context context) {
StorageImplUtils.assertNotNull("data", data);
Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length,
BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE, true);
Mono<Response<Void>> response = client.stageBlockWithResponse(base64BlockId, fbb, length, contentMd5, leaseId,
context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
* <pre>
* Context context = new Context&
* BinaryData binaryData = BinaryData.fromStream&
* BlockBlobStageBlockOptions options = new BlockBlobStageBlockOptions&
* .setContentMd5&
* .setLeaseId&
* System.out.printf&
* client.stageBlockWithResponse&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
*
* @param options {@link BlockBlobStageBlockOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input options is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockWithResponse(BlockBlobStageBlockOptions options, Duration timeout, Context context) {
Objects.requireNonNull(options, "options must not be null");
Mono<Response<Void>> response = client.stageBlockWithResponse(
options.getBase64BlockId(), options.getData(), options.getContentMd5(), options.getLeaseId(), context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl
* <pre>
* client.stageBlockFromUrl&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param sourceUrl The url to the blob that will be the source of the copy. A source blob in the same storage
* account can be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is public, no
* authentication is required to perform the operation.
* @param sourceRange {@link BlobRange}
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlockFromUrl(String base64BlockId, String sourceUrl, BlobRange sourceRange) {
stageBlockFromUrlWithResponse(base64BlockId, sourceUrl, sourceRange, null, null, null, null, Context.NONE);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
* <pre>
* BlobRequestConditions sourceRequestConditions = new BlobRequestConditions&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.stageBlockFromUrlWithResponse&
* leaseId, sourceRequestConditions, timeout, context&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param sourceUrl The url to the blob that will be the source of the copy. A source blob in the same storage
* account can be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is public, no
* authentication is required to perform the operation.
* @param sourceRange {@link BlobRange}
* @param sourceContentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block
* during transport. When this header is specified, the storage service compares the hash of the content that has
* arrived with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not
* match, the operation will fail.
* @param leaseId The lease ID that the active lease on the blob must match.
* @param sourceRequestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockFromUrlWithResponse(String base64BlockId, String sourceUrl, BlobRange sourceRange,
byte[] sourceContentMd5, String leaseId, BlobRequestConditions sourceRequestConditions, Duration timeout,
Context context) {
return stageBlockFromUrlWithResponse(new BlockBlobStageBlockFromUrlOptions(base64BlockId, sourceUrl)
.setSourceRange(sourceRange).setSourceContentMd5(sourceContentMd5).setLeaseId(leaseId)
.setSourceRequestConditions(sourceRequestConditions), timeout, context);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
* <pre>
* BlobRequestConditions sourceRequestConditions = new BlobRequestConditions&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.stageBlockFromUrlWithResponse&
* .setSourceRange&
* .setSourceRequestConditions&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
*
* @param options Parameters for the operation
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockFromUrlWithResponse(BlockBlobStageBlockFromUrlOptions options, Duration timeout,
Context context) {
Mono<Response<Void>> response = client.stageBlockFromUrlWithResponse(options, context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list filter.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocks
* <pre>
* BlockList block = client.listBlocks&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocks
*
* @param listType Specifies which type of blocks to return.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockList listBlocks(BlockListType listType) {
return this.listBlocksWithResponse(listType, null, null, Context.NONE).getValue();
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list
* filter. For more information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
* <pre>
* Context context = new Context&
* BlockList block = client.listBlocksWithResponse&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
*
* @param listType Specifies which type of blocks to return.
* @param leaseId The lease ID the active lease on the blob must match.
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockList> listBlocksWithResponse(BlockListType listType, String leaseId, Duration timeout,
Context context) {
return listBlocksWithResponse(new BlockBlobListBlocksOptions(listType).setLeaseId(leaseId), timeout, context);
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list
* filter. For more information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
* <pre>
* Context context = new Context&
* BlockList block = client.listBlocksWithResponse&
* .setLeaseId&
* .setIfTagsMatch&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
*
* @param options {@link BlockBlobListBlocksOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockList> listBlocksWithResponse(BlockBlobListBlocksOptions options, Duration timeout,
Context context) {
return blockWithOptionalTimeout(client.listBlocksWithResponse(options, context), timeout);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can call
* commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new and
* existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
* <pre>
* System.out.printf&
* client.commitBlockList&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem commitBlockList(List<String> base64BlockIds) {
return commitBlockList(base64BlockIds, false);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can call
* commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new and
* existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
* <pre>
* boolean overwrite = false; &
* System.out.printf&
* client.commitBlockList&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem commitBlockList(List<String> base64BlockIds, boolean overwrite) {
BlobRequestConditions requestConditions = null;
if (!overwrite) {
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return commitBlockListWithResponse(base64BlockIds, null, null, null, requestConditions, null, Context.NONE)
.getValue();
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part
* of a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can
* call commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new
* and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.commitBlockListWithResponse&
* AccessTier.HOT, requestConditions, timeout, context&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> commitBlockListWithResponse(List<String> base64BlockIds, BlobHttpHeaders headers,
Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions, Duration timeout,
Context context) {
return this.commitBlockListWithResponse(new BlockBlobCommitBlockListOptions(base64BlockIds)
.setHeaders(headers).setMetadata(metadata).setTier(tier).setRequestConditions(requestConditions),
timeout, context);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part
* of a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can
* call commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new
* and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.commitBlockListWithResponse&
* new BlockBlobCommitBlockListOptions&
* .setMetadata&
* .setRequestConditions&
* .getStatusCode&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
*
* @param options {@link BlockBlobCommitBlockListOptions options}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> commitBlockListWithResponse(BlockBlobCommitBlockListOptions options,
Duration timeout, Context context) {
Mono<Response<BlockBlobItem>> response = client.commitBlockListWithResponse(
options, context);
return blockWithOptionalTimeout(response, timeout);
}
} |
Agreed. API uses a Long for this purpose. | public SeekableByteChannel openSeekableByteChannelWrite(BlockBlobSeekableByteChannelWriteOptions options) {
Objects.requireNonNull(options);
StorageSeekableByteChannelBlockBlobWriteBehavior.WriteMode internalMode;
long startingPosition = 0L;
if (options.getWriteMode() == BlockBlobSeekableByteChannelWriteOptions.WriteMode.OVERWRITE) {
internalMode = StorageSeekableByteChannelBlockBlobWriteBehavior.WriteMode.OVERWRITE;
} else {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Unsupported value for `options.getWriteMode()`."));
}
return new StorageSeekableByteChannel(
options.getChunkSize() != null
? options.getChunkSize().intValue()
: BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE,
new StorageSeekableByteChannelBlockBlobWriteBehavior(this, options.getHeaders(), options.getMetadata(),
options.getTags(), options.getTier(), options.getRequestConditions(), internalMode, null),
startingPosition);
} | : BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE, | public SeekableByteChannel openSeekableByteChannelWrite(BlockBlobSeekableByteChannelWriteOptions options) {
Objects.requireNonNull(options);
StorageSeekableByteChannelBlockBlobWriteBehavior.WriteMode internalMode;
long startingPosition = 0L;
if (options.getWriteMode() == BlockBlobSeekableByteChannelWriteOptions.WriteMode.OVERWRITE) {
internalMode = StorageSeekableByteChannelBlockBlobWriteBehavior.WriteMode.OVERWRITE;
} else {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Unsupported value for `options.getWriteMode()`."));
}
return new StorageSeekableByteChannel(
options.getChunkSize() != null
? options.getChunkSize().intValue()
: BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE,
new StorageSeekableByteChannelBlockBlobWriteBehavior(this, options.getHeaders(), options.getMetadata(),
options.getTags(), options.getTier(), options.getRequestConditions(), internalMode, null),
startingPosition);
} | class BlockBlobClient extends BlobClientBase {
private static final ClientLogger LOGGER = new ClientLogger(BlockBlobClient.class);
private final BlockBlobAsyncClient client;
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
* @deprecated Use {@link
*/
@Deprecated
public static final int MAX_UPLOAD_BLOB_BYTES = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES;
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
*/
public static final long MAX_UPLOAD_BLOB_BYTES_LONG = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES_LONG;
/**
* Indicates the maximum number of bytes that can be sent in a call to stageBlock.
* @deprecated Use {@link
*/
@Deprecated
public static final int MAX_STAGE_BLOCK_BYTES = BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES;
/**
* Indicates the maximum number of bytes that can be sent in a call to stageBlock.
*/
public static final long MAX_STAGE_BLOCK_BYTES_LONG = BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES_LONG;
/**
* Indicates the maximum number of blocks allowed in a block blob.
*/
public static final int MAX_BLOCKS = BlockBlobAsyncClient.MAX_BLOCKS;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param client the async block blob client
*/
BlockBlobClient(BlockBlobAsyncClient client) {
super(client);
this.client = client;
}
/**
* Creates a new {@link BlockBlobClient} with the specified {@code encryptionScope}.
*
* @param encryptionScope the encryption scope for the blob, pass {@code null} to use no encryption scope.
* @return a {@link BlockBlobClient} with the specified {@code encryptionScope}.
*/
@Override
public BlockBlobClient getEncryptionScopeClient(String encryptionScope) {
return new BlockBlobClient(client.getEncryptionScopeAsyncClient(encryptionScope));
}
/**
* Creates a new {@link BlockBlobClient} with the specified {@code customerProvidedKey}.
*
* @param customerProvidedKey the {@link CustomerProvidedKey} for the blob,
* pass {@code null} to use no customer provided key.
* @return a {@link BlockBlobClient} with the specified {@code customerProvidedKey}.
*/
@Override
public BlockBlobClient getCustomerProvidedKeyClient(CustomerProvidedKey customerProvidedKey) {
return new BlockBlobClient(client.getCustomerProvidedKeyAsyncClient(customerProvidedKey));
}
/**
* Creates and opens an output stream to write data to the block blob.
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream() {
return getBlobOutputStream(false);
}
/**
* Creates and opens an output stream to write data to the block blob.
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(boolean overwrite) {
BlobRequestConditions requestConditions = null;
if (!overwrite) {
if (exists()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS));
}
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return getBlobOutputStream(requestConditions);
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param requestConditions A {@link BlobRequestConditions} object that represents the access conditions for the
* blob.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(BlobRequestConditions requestConditions) {
return getBlobOutputStream(null, null, null, null, requestConditions);
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(ParallelTransferOptions parallelTransferOptions,
BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier,
BlobRequestConditions requestConditions) {
return this.getBlobOutputStream(new BlockBlobOutputStreamOptions()
.setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata).setTier(tier)
.setRequestConditions(requestConditions));
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param options {@link BlockBlobOutputStreamOptions}
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(BlockBlobOutputStreamOptions options) {
BlobAsyncClient blobClient = prepareBuilder().buildAsyncClient();
return BlobOutputStream.blockBlobOutputStream(blobClient, options, null);
}
/**
* Opens a seekable byte channel in write-only mode to upload the blob.
*
* @param options {@link BlobSeekableByteChannelReadOptions}
* @return A <code>SeekableByteChannel</code> object that represents the channel to use for writing to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
private BlobClientBuilder prepareBuilder() {
BlobClientBuilder builder = new BlobClientBuilder()
.pipeline(getHttpPipeline())
.endpoint(getBlobUrl())
.snapshot(getSnapshotId())
.serviceVersion(getServiceVersion());
CpkInfo cpk = getCustomerProvidedKey();
if (cpk != null) {
builder.customerProvidedKey(new CustomerProvidedKey(cpk.getEncryptionKey()));
}
return builder;
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob. Updating an existing block
* blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content
* of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use
* PutBlock and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @return The information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(InputStream data, long length) {
return upload(data, length, false);
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob. Updating an existing block
* blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content
* of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use
* PutBlock and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* BinaryData binaryData = BinaryData.fromStream&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(BinaryData data) {
return upload(data, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* boolean overwrite = false;
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(InputStream data, long length, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadWithResponse(data, length, null, null, null, null, blobRequestConditions, null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* boolean overwrite = false;
* BinaryData binaryData = BinaryData.fromStream&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(BinaryData data, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadWithResponse(
new BlockBlobSimpleUploadOptions(data)
.setRequestConditions(blobRequestConditions),
null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* requestConditions, timeout, context&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param contentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block during
* transport. When this header is specified, the storage service compares the hash of the content that has arrived
* with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the
* operation will fail.
* @param requestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the uploaded block blob.
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadWithResponse(InputStream data, long length, BlobHttpHeaders headers,
Map<String, String> metadata, AccessTier tier, byte[] contentMd5, BlobRequestConditions requestConditions,
Duration timeout, Context context) {
return this.uploadWithResponse(new BlockBlobSimpleUploadOptions(data, length).setHeaders(headers)
.setMetadata(metadata).setTier(tier).setContentMd5(contentMd5).setRequestConditions(requestConditions),
timeout, context);
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* .setHeaders&
* .setRequestConditions&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
*
* @param options {@link BlockBlobSimpleUploadOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the uploaded block blob.
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadWithResponse(BlockBlobSimpleUploadOptions options, Duration timeout,
Context context) {
StorageImplUtils.assertNotNull("options", options);
Mono<Response<BlockBlobItem>> upload = client.uploadWithResponse(options, context);
try {
return blockWithOptionalTimeout(upload, timeout);
} catch (UncheckedIOException e) {
throw LOGGER.logExceptionAsError(e);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
* <pre>
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
*
* @param sourceUrl The source URL to upload from.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem uploadFromUrl(String sourceUrl) {
return uploadFromUrl(sourceUrl, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
* <pre>
* boolean overwrite = false;
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
*
* @param sourceUrl The source URL to upload from.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem uploadFromUrl(String sourceUrl, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadFromUrlWithResponse(
new BlobUploadFromUrlOptions(sourceUrl).setDestinationRequestConditions(blobRequestConditions),
null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* .setHeaders&
* .setDestinationRequestConditions&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse
*
* @param options {@link BlobUploadFromUrlOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadFromUrlWithResponse(BlobUploadFromUrlOptions options, Duration timeout,
Context context) {
StorageImplUtils.assertNotNull("options", options);
Mono<Response<BlockBlobItem>> upload = client.uploadFromUrlWithResponse(options, context);
try {
return blockWithOptionalTimeout(upload, timeout);
} catch (UncheckedIOException e) {
throw LOGGER.logExceptionAsError(e);
}
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
* <pre>
* client.stageBlock&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlock(String base64BlockId, InputStream data, long length) {
stageBlockWithResponse(base64BlockId, data, length, null, null, null, Context.NONE);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
* <pre>
* BinaryData binaryData = BinaryData.fromStream&
* client.stageBlock&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlock(String base64BlockId, BinaryData data) {
stageBlockWithResponse(new BlockBlobStageBlockOptions(base64BlockId, data), null, Context.NONE);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
* <pre>
* Context context = new Context&
* System.out.printf&
* client.stageBlockWithResponse&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param contentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block during
* transport. When this header is specified, the storage service compares the hash of the content that has arrived
* with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the
* operation will fail.
* @param leaseId The lease ID the active lease on the blob must match.
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockWithResponse(String base64BlockId, InputStream data, long length, byte[] contentMd5,
String leaseId, Duration timeout, Context context) {
StorageImplUtils.assertNotNull("data", data);
Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length,
BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE, true);
Mono<Response<Void>> response = client.stageBlockWithResponse(base64BlockId, fbb, length, contentMd5, leaseId,
context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
* <pre>
* Context context = new Context&
* BinaryData binaryData = BinaryData.fromStream&
* BlockBlobStageBlockOptions options = new BlockBlobStageBlockOptions&
* .setContentMd5&
* .setLeaseId&
* System.out.printf&
* client.stageBlockWithResponse&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
*
* @param options {@link BlockBlobStageBlockOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input options is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockWithResponse(BlockBlobStageBlockOptions options, Duration timeout, Context context) {
Objects.requireNonNull(options, "options must not be null");
Mono<Response<Void>> response = client.stageBlockWithResponse(
options.getBase64BlockId(), options.getData(), options.getContentMd5(), options.getLeaseId(), context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl
* <pre>
* client.stageBlockFromUrl&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param sourceUrl The url to the blob that will be the source of the copy. A source blob in the same storage
* account can be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is public, no
* authentication is required to perform the operation.
* @param sourceRange {@link BlobRange}
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlockFromUrl(String base64BlockId, String sourceUrl, BlobRange sourceRange) {
stageBlockFromUrlWithResponse(base64BlockId, sourceUrl, sourceRange, null, null, null, null, Context.NONE);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
* <pre>
* BlobRequestConditions sourceRequestConditions = new BlobRequestConditions&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.stageBlockFromUrlWithResponse&
* leaseId, sourceRequestConditions, timeout, context&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param sourceUrl The url to the blob that will be the source of the copy. A source blob in the same storage
* account can be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is public, no
* authentication is required to perform the operation.
* @param sourceRange {@link BlobRange}
* @param sourceContentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block
* during transport. When this header is specified, the storage service compares the hash of the content that has
* arrived with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not
* match, the operation will fail.
* @param leaseId The lease ID that the active lease on the blob must match.
* @param sourceRequestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockFromUrlWithResponse(String base64BlockId, String sourceUrl, BlobRange sourceRange,
byte[] sourceContentMd5, String leaseId, BlobRequestConditions sourceRequestConditions, Duration timeout,
Context context) {
return stageBlockFromUrlWithResponse(new BlockBlobStageBlockFromUrlOptions(base64BlockId, sourceUrl)
.setSourceRange(sourceRange).setSourceContentMd5(sourceContentMd5).setLeaseId(leaseId)
.setSourceRequestConditions(sourceRequestConditions), timeout, context);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
* <pre>
* BlobRequestConditions sourceRequestConditions = new BlobRequestConditions&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.stageBlockFromUrlWithResponse&
* .setSourceRange&
* .setSourceRequestConditions&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
*
* @param options Parameters for the operation
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockFromUrlWithResponse(BlockBlobStageBlockFromUrlOptions options, Duration timeout,
Context context) {
Mono<Response<Void>> response = client.stageBlockFromUrlWithResponse(options, context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list filter.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocks
* <pre>
* BlockList block = client.listBlocks&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocks
*
* @param listType Specifies which type of blocks to return.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockList listBlocks(BlockListType listType) {
return this.listBlocksWithResponse(listType, null, null, Context.NONE).getValue();
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list
* filter. For more information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
* <pre>
* Context context = new Context&
* BlockList block = client.listBlocksWithResponse&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
*
* @param listType Specifies which type of blocks to return.
* @param leaseId The lease ID the active lease on the blob must match.
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockList> listBlocksWithResponse(BlockListType listType, String leaseId, Duration timeout,
Context context) {
return listBlocksWithResponse(new BlockBlobListBlocksOptions(listType).setLeaseId(leaseId), timeout, context);
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list
* filter. For more information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
* <pre>
* Context context = new Context&
* BlockList block = client.listBlocksWithResponse&
* .setLeaseId&
* .setIfTagsMatch&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
*
* @param options {@link BlockBlobListBlocksOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockList> listBlocksWithResponse(BlockBlobListBlocksOptions options, Duration timeout,
Context context) {
return blockWithOptionalTimeout(client.listBlocksWithResponse(options, context), timeout);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can call
* commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new and
* existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
* <pre>
* System.out.printf&
* client.commitBlockList&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem commitBlockList(List<String> base64BlockIds) {
return commitBlockList(base64BlockIds, false);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can call
* commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new and
* existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
* <pre>
* boolean overwrite = false; &
* System.out.printf&
* client.commitBlockList&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem commitBlockList(List<String> base64BlockIds, boolean overwrite) {
BlobRequestConditions requestConditions = null;
if (!overwrite) {
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return commitBlockListWithResponse(base64BlockIds, null, null, null, requestConditions, null, Context.NONE)
.getValue();
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part
* of a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can
* call commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new
* and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.commitBlockListWithResponse&
* AccessTier.HOT, requestConditions, timeout, context&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> commitBlockListWithResponse(List<String> base64BlockIds, BlobHttpHeaders headers,
Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions, Duration timeout,
Context context) {
return this.commitBlockListWithResponse(new BlockBlobCommitBlockListOptions(base64BlockIds)
.setHeaders(headers).setMetadata(metadata).setTier(tier).setRequestConditions(requestConditions),
timeout, context);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part
* of a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can
* call commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new
* and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.commitBlockListWithResponse&
* new BlockBlobCommitBlockListOptions&
* .setMetadata&
* .setRequestConditions&
* .getStatusCode&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
*
* @param options {@link BlockBlobCommitBlockListOptions options}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> commitBlockListWithResponse(BlockBlobCommitBlockListOptions options,
Duration timeout, Context context) {
Mono<Response<BlockBlobItem>> response = client.commitBlockListWithResponse(
options, context);
return blockWithOptionalTimeout(response, timeout);
}
} | class BlockBlobClient extends BlobClientBase {
private static final ClientLogger LOGGER = new ClientLogger(BlockBlobClient.class);
private final BlockBlobAsyncClient client;
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
* @deprecated Use {@link
*/
@Deprecated
public static final int MAX_UPLOAD_BLOB_BYTES = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES;
/**
* Indicates the maximum number of bytes that can be sent in a call to upload.
*/
public static final long MAX_UPLOAD_BLOB_BYTES_LONG = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES_LONG;
/**
* Indicates the maximum number of bytes that can be sent in a call to stageBlock.
* @deprecated Use {@link
*/
@Deprecated
public static final int MAX_STAGE_BLOCK_BYTES = BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES;
/**
* Indicates the maximum number of bytes that can be sent in a call to stageBlock.
*/
public static final long MAX_STAGE_BLOCK_BYTES_LONG = BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES_LONG;
/**
* Indicates the maximum number of blocks allowed in a block blob.
*/
public static final int MAX_BLOCKS = BlockBlobAsyncClient.MAX_BLOCKS;
/**
* Package-private constructor for use by {@link SpecializedBlobClientBuilder}.
*
* @param client the async block blob client
*/
BlockBlobClient(BlockBlobAsyncClient client) {
super(client);
this.client = client;
}
/**
* Creates a new {@link BlockBlobClient} with the specified {@code encryptionScope}.
*
* @param encryptionScope the encryption scope for the blob, pass {@code null} to use no encryption scope.
* @return a {@link BlockBlobClient} with the specified {@code encryptionScope}.
*/
@Override
public BlockBlobClient getEncryptionScopeClient(String encryptionScope) {
return new BlockBlobClient(client.getEncryptionScopeAsyncClient(encryptionScope));
}
/**
* Creates a new {@link BlockBlobClient} with the specified {@code customerProvidedKey}.
*
* @param customerProvidedKey the {@link CustomerProvidedKey} for the blob,
* pass {@code null} to use no customer provided key.
* @return a {@link BlockBlobClient} with the specified {@code customerProvidedKey}.
*/
@Override
public BlockBlobClient getCustomerProvidedKeyClient(CustomerProvidedKey customerProvidedKey) {
return new BlockBlobClient(client.getCustomerProvidedKeyAsyncClient(customerProvidedKey));
}
/**
* Creates and opens an output stream to write data to the block blob.
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream() {
return getBlobOutputStream(false);
}
/**
* Creates and opens an output stream to write data to the block blob.
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(boolean overwrite) {
BlobRequestConditions requestConditions = null;
if (!overwrite) {
if (exists()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS));
}
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return getBlobOutputStream(requestConditions);
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param requestConditions A {@link BlobRequestConditions} object that represents the access conditions for the
* blob.
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(BlobRequestConditions requestConditions) {
return getBlobOutputStream(null, null, null, null, requestConditions);
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
*
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(ParallelTransferOptions parallelTransferOptions,
BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier,
BlobRequestConditions requestConditions) {
return this.getBlobOutputStream(new BlockBlobOutputStreamOptions()
.setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata).setTier(tier)
.setRequestConditions(requestConditions));
}
/**
* Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it
* will be overwritten.
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
* <p>
* Note: We recommend you call write with reasonably sized buffers, you can do so by wrapping the BlobOutputStream
* obtained below with a {@link java.io.BufferedOutputStream}.
*
* @param options {@link BlockBlobOutputStreamOptions}
* @return A {@link BlobOutputStream} object used to write data to the blob.
* @throws BlobStorageException If a storage service error occurred.
*/
public BlobOutputStream getBlobOutputStream(BlockBlobOutputStreamOptions options) {
BlobAsyncClient blobClient = prepareBuilder().buildAsyncClient();
return BlobOutputStream.blockBlobOutputStream(blobClient, options, null);
}
/**
* Opens a seekable byte channel in write-only mode to upload the blob.
*
* @param options {@link BlobSeekableByteChannelReadOptions}
* @return A <code>SeekableByteChannel</code> object that represents the channel to use for writing to the blob.
* @throws BlobStorageException If a storage service error occurred.
* @throws NullPointerException if 'options' is null.
*/
private BlobClientBuilder prepareBuilder() {
BlobClientBuilder builder = new BlobClientBuilder()
.pipeline(getHttpPipeline())
.endpoint(getBlobUrl())
.snapshot(getSnapshotId())
.serviceVersion(getServiceVersion());
CpkInfo cpk = getCustomerProvidedKey();
if (cpk != null) {
builder.customerProvidedKey(new CustomerProvidedKey(cpk.getEncryptionKey()));
}
return builder;
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob. Updating an existing block
* blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content
* of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use
* PutBlock and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @return The information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(InputStream data, long length) {
return upload(data, length, false);
}
/**
* Creates a new block blob. By default, this method will not overwrite an existing blob. Updating an existing block
* blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content
* of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use
* PutBlock and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* BinaryData binaryData = BinaryData.fromStream&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(BinaryData data) {
return upload(data, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* boolean overwrite = false;
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(InputStream data, long length, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadWithResponse(data, length, null, null, null, null, blobRequestConditions, null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.upload
* <pre>
* boolean overwrite = false;
* BinaryData binaryData = BinaryData.fromStream&
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.upload
*
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem upload(BinaryData data, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadWithResponse(
new BlockBlobSimpleUploadOptions(data)
.setRequestConditions(blobRequestConditions),
null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* requestConditions, timeout, context&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
*
* @param data The data to write to the blob. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param contentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block during
* transport. When this header is specified, the storage service compares the hash of the content that has arrived
* with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the
* operation will fail.
* @param requestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the uploaded block blob.
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadWithResponse(InputStream data, long length, BlobHttpHeaders headers,
Map<String, String> metadata, AccessTier tier, byte[] contentMd5, BlobRequestConditions requestConditions,
Duration timeout, Context context) {
return this.uploadWithResponse(new BlockBlobSimpleUploadOptions(data, length).setHeaders(headers)
.setMetadata(metadata).setTier(tier).setContentMd5(contentMd5).setRequestConditions(requestConditions),
timeout, context);
}
/**
* Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob
* overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the
* existing blob is overwritten with the new content. To perform a partial update of a block blob's, use PutBlock
* and PutBlockList. For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* .setHeaders&
* .setRequestConditions&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse
*
* @param options {@link BlockBlobSimpleUploadOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the uploaded block blob.
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
* @throws UncheckedIOException If an I/O error occurs
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadWithResponse(BlockBlobSimpleUploadOptions options, Duration timeout,
Context context) {
StorageImplUtils.assertNotNull("options", options);
Mono<Response<BlockBlobItem>> upload = client.uploadWithResponse(options, context);
try {
return blockWithOptionalTimeout(upload, timeout);
} catch (UncheckedIOException e) {
throw LOGGER.logExceptionAsError(e);
}
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
* <pre>
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
*
* @param sourceUrl The source URL to upload from.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem uploadFromUrl(String sourceUrl) {
return uploadFromUrl(sourceUrl, false);
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
* <pre>
* boolean overwrite = false;
* System.out.printf&
* Base64.getEncoder&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl
*
* @param sourceUrl The source URL to upload from.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem uploadFromUrl(String sourceUrl, boolean overwrite) {
BlobRequestConditions blobRequestConditions = new BlobRequestConditions();
if (!overwrite) {
blobRequestConditions.setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return uploadFromUrlWithResponse(
new BlobUploadFromUrlOptions(sourceUrl).setDestinationRequestConditions(blobRequestConditions),
null, Context.NONE)
.getValue();
}
/**
* Creates a new block blob, or updates the content of an existing block blob.
* <p>
* Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported
* with PutBlobFromUrl; the content of the existing blob is overwritten with the new content.
* For more information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
*
* byte[] md5 = MessageDigest.getInstance&
*
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* .encodeToString&
* .setHeaders&
* .setDestinationRequestConditions&
* .getValue&
* .getContentMd5&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse
*
* @param options {@link BlobUploadFromUrlOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return The information of the uploaded block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> uploadFromUrlWithResponse(BlobUploadFromUrlOptions options, Duration timeout,
Context context) {
StorageImplUtils.assertNotNull("options", options);
Mono<Response<BlockBlobItem>> upload = client.uploadFromUrlWithResponse(options, context);
try {
return blockWithOptionalTimeout(upload, timeout);
} catch (UncheckedIOException e) {
throw LOGGER.logExceptionAsError(e);
}
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
* <pre>
* client.stageBlock&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlock(String base64BlockId, InputStream data, long length) {
stageBlockWithResponse(base64BlockId, data, length, null, null, null, Context.NONE);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
* <pre>
* BinaryData binaryData = BinaryData.fromStream&
* client.stageBlock&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlock
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. Note that this {@code BinaryData} must have defined length
* and must be replayable if retries are enabled (the default), see {@link BinaryData
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlock(String base64BlockId, BinaryData data) {
stageBlockWithResponse(new BlockBlobStageBlockOptions(base64BlockId, data), null, Context.NONE);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
* <pre>
* Context context = new Context&
* System.out.printf&
* client.stageBlockWithResponse&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param data The data to write to the block. The data must be markable. This is in order to support retries. If
* the data is not markable, consider using {@link
* Alternatively, consider wrapping your data source in a {@link java.io.BufferedInputStream} to add mark support.
* @param length The exact length of the data. It is important that this value match precisely the length of the
* data provided in the {@link InputStream}.
* @param contentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block during
* transport. When this header is specified, the storage service compares the hash of the content that has arrived
* with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the
* operation will fail.
* @param leaseId The lease ID the active lease on the blob must match.
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input data is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockWithResponse(String base64BlockId, InputStream data, long length, byte[] contentMd5,
String leaseId, Duration timeout, Context context) {
StorageImplUtils.assertNotNull("data", data);
Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length,
BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE, true);
Mono<Response<Void>> response = client.stageBlockWithResponse(base64BlockId, fbb, length, contentMd5, leaseId,
context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Uploads the specified block to the block blob's "staging area" to be later committed by a call to
* commitBlockList. For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
* <pre>
* Context context = new Context&
* BinaryData binaryData = BinaryData.fromStream&
* BlockBlobStageBlockOptions options = new BlockBlobStageBlockOptions&
* .setContentMd5&
* .setLeaseId&
* System.out.printf&
* client.stageBlockWithResponse&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse
*
* @param options {@link BlockBlobStageBlockOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
*
* @throws UnexpectedLengthException when the length of data does not match the input {@code length}.
* @throws NullPointerException if the input options is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockWithResponse(BlockBlobStageBlockOptions options, Duration timeout, Context context) {
Objects.requireNonNull(options, "options must not be null");
Mono<Response<Void>> response = client.stageBlockWithResponse(
options.getBase64BlockId(), options.getData(), options.getContentMd5(), options.getLeaseId(), context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl
* <pre>
* client.stageBlockFromUrl&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param sourceUrl The url to the blob that will be the source of the copy. A source blob in the same storage
* account can be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is public, no
* authentication is required to perform the operation.
* @param sourceRange {@link BlobRange}
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void stageBlockFromUrl(String base64BlockId, String sourceUrl, BlobRange sourceRange) {
stageBlockFromUrlWithResponse(base64BlockId, sourceUrl, sourceRange, null, null, null, null, Context.NONE);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
* <pre>
* BlobRequestConditions sourceRequestConditions = new BlobRequestConditions&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.stageBlockFromUrlWithResponse&
* leaseId, sourceRequestConditions, timeout, context&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
*
* @param base64BlockId A Base64 encoded {@code String} that specifies the ID for this block. Note that all block
* ids for a given blob must be the same length.
* @param sourceUrl The url to the blob that will be the source of the copy. A source blob in the same storage
* account can be authenticated via Shared Key. However, if the source is a blob in another account, the source blob
* must either be public or must be authenticated via a shared access signature. If the source blob is public, no
* authentication is required to perform the operation.
* @param sourceRange {@link BlobRange}
* @param sourceContentMd5 An MD5 hash of the block content. This hash is used to verify the integrity of the block
* during transport. When this header is specified, the storage service compares the hash of the content that has
* arrived with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not
* match, the operation will fail.
* @param leaseId The lease ID that the active lease on the blob must match.
* @param sourceRequestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockFromUrlWithResponse(String base64BlockId, String sourceUrl, BlobRange sourceRange,
byte[] sourceContentMd5, String leaseId, BlobRequestConditions sourceRequestConditions, Duration timeout,
Context context) {
return stageBlockFromUrlWithResponse(new BlockBlobStageBlockFromUrlOptions(base64BlockId, sourceUrl)
.setSourceRange(sourceRange).setSourceContentMd5(sourceContentMd5).setLeaseId(leaseId)
.setSourceRequestConditions(sourceRequestConditions), timeout, context);
}
/**
* Creates a new block to be committed as part of a blob where the contents are read from a URL. For more
* information, see the <a href="https:
* Docs</a>.
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
* <pre>
* BlobRequestConditions sourceRequestConditions = new BlobRequestConditions&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.stageBlockFromUrlWithResponse&
* .setSourceRange&
* .setSourceRequestConditions&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse
*
* @param options Parameters for the operation
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A response containing status code and HTTP headers
* @throws IllegalArgumentException If {@code sourceUrl} is a malformed {@link URL}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> stageBlockFromUrlWithResponse(BlockBlobStageBlockFromUrlOptions options, Duration timeout,
Context context) {
Mono<Response<Void>> response = client.stageBlockFromUrlWithResponse(options, context);
return blockWithOptionalTimeout(response, timeout);
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list filter.
* For more information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocks
* <pre>
* BlockList block = client.listBlocks&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocks
*
* @param listType Specifies which type of blocks to return.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockList listBlocks(BlockListType listType) {
return this.listBlocksWithResponse(listType, null, null, Context.NONE).getValue();
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list
* filter. For more information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
* <pre>
* Context context = new Context&
* BlockList block = client.listBlocksWithResponse&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
*
* @param listType Specifies which type of blocks to return.
* @param leaseId The lease ID the active lease on the blob must match.
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockList> listBlocksWithResponse(BlockListType listType, String leaseId, Duration timeout,
Context context) {
return listBlocksWithResponse(new BlockBlobListBlocksOptions(listType).setLeaseId(leaseId), timeout, context);
}
/**
* Returns the list of blocks that have been uploaded as part of a block blob using the specified block list
* filter. For more information, see the <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
* <pre>
* Context context = new Context&
* BlockList block = client.listBlocksWithResponse&
* .setLeaseId&
* .setIfTagsMatch&
*
* System.out.println&
* block.getCommittedBlocks&
*
* System.out.println&
* block.getUncommittedBlocks&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse
*
* @param options {@link BlockBlobListBlocksOptions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The list of blocks.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockList> listBlocksWithResponse(BlockBlobListBlocksOptions options, Duration timeout,
Context context) {
return blockWithOptionalTimeout(client.listBlocksWithResponse(options, context), timeout);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can call
* commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new and
* existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
* <pre>
* System.out.printf&
* client.commitBlockList&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem commitBlockList(List<String> base64BlockIds) {
return commitBlockList(base64BlockIds, false);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of
* a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can call
* commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new and
* existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
* <pre>
* boolean overwrite = false; &
* System.out.printf&
* client.commitBlockList&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @param overwrite Whether to overwrite, should data exist on the blob.
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public BlockBlobItem commitBlockList(List<String> base64BlockIds, boolean overwrite) {
BlobRequestConditions requestConditions = null;
if (!overwrite) {
requestConditions = new BlobRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD);
}
return commitBlockListWithResponse(base64BlockIds, null, null, null, requestConditions, null, Context.NONE)
.getValue();
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part
* of a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can
* call commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new
* and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.commitBlockListWithResponse&
* AccessTier.HOT, requestConditions, timeout, context&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
*
* @param base64BlockIds A list of base64 encode {@code String}s that specifies the block IDs to be committed.
* @param headers {@link BlobHttpHeaders}
* @param metadata Metadata to associate with the blob. If there is leading or trailing whitespace in any
* metadata key or value, it must be removed or encoded.
* @param tier {@link AccessTier} for the destination blob.
* @param requestConditions {@link BlobRequestConditions}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> commitBlockListWithResponse(List<String> base64BlockIds, BlobHttpHeaders headers,
Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions, Duration timeout,
Context context) {
return this.commitBlockListWithResponse(new BlockBlobCommitBlockListOptions(base64BlockIds)
.setHeaders(headers).setMetadata(metadata).setTier(tier).setRequestConditions(requestConditions),
timeout, context);
}
/**
* Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part
* of a blob, a block must have been successfully written to the server in a prior stageBlock operation. You can
* call commitBlockList to update a blob by uploading only those blocks that have changed, then committing the new
* and existing blocks together. Any blocks not specified in the block list and permanently deleted. For more
* information, see the
* <a href="https:
* <p>
* To avoid overwriting, pass "*" to {@link BlobRequestConditions
*
* <p><strong>Code Samples</strong></p>
*
* <!-- src_embed com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
* <pre>
* BlobHttpHeaders headers = new BlobHttpHeaders&
* .setContentMd5&
* .setContentLanguage&
* .setContentType&
*
* Map<String, String> metadata = Collections.singletonMap&
* Map<String, String> tags = Collections.singletonMap&
* BlobRequestConditions requestConditions = new BlobRequestConditions&
* .setLeaseId&
* .setIfUnmodifiedSince&
* Context context = new Context&
*
* System.out.printf&
* client.commitBlockListWithResponse&
* new BlockBlobCommitBlockListOptions&
* .setMetadata&
* .setRequestConditions&
* .getStatusCode&
* </pre>
* <!-- end com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile
*
* @param options {@link BlockBlobCommitBlockListOptions options}
* @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return The information of the block blob.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BlockBlobItem> commitBlockListWithResponse(BlockBlobCommitBlockListOptions options,
Duration timeout, Context context) {
Mono<Response<BlockBlobItem>> response = client.commitBlockListWithResponse(
options, context);
return blockWithOptionalTimeout(response, timeout);
}
} |
I am not particularly sure on how to block on a flux generated by a sink. Blocking here would cause an indefinite hang. Any ideas here? | public void openConnectionsAndInitCaches() {
this.asyncContainer.openConnectionsAndInitCaches().subscribe();
} | this.asyncContainer.openConnectionsAndInitCaches().subscribe(); | public void openConnectionsAndInitCaches() {
blockVoidResponse(this.asyncContainer.openConnectionsAndInitCaches());
} | class type of item.
* @return the Cosmos item response.
*/
public <T> CosmosItemResponse<T> readItem(
String itemId, PartitionKey partitionKey,
CosmosItemRequestOptions options, Class<T> itemType) {
return this.blockItemResponse(asyncContainer.readItem(itemId, partitionKey, options, itemType));
} | class type of item.
* @return the Cosmos item response.
*/
public <T> CosmosItemResponse<T> readItem(
String itemId, PartitionKey partitionKey,
CosmosItemRequestOptions options, Class<T> itemType) {
return this.blockItemResponse(asyncContainer.readItem(itemId, partitionKey, options, itemType));
} |
when using blockLast? do you ever signla complete on the sink? | public void openConnectionsAndInitCaches() {
this.asyncContainer.openConnectionsAndInitCaches().subscribe();
} | this.asyncContainer.openConnectionsAndInitCaches().subscribe(); | public void openConnectionsAndInitCaches() {
blockVoidResponse(this.asyncContainer.openConnectionsAndInitCaches());
} | class type of item.
* @return the Cosmos item response.
*/
public <T> CosmosItemResponse<T> readItem(
String itemId, PartitionKey partitionKey,
CosmosItemRequestOptions options, Class<T> itemType) {
return this.blockItemResponse(asyncContainer.readItem(itemId, partitionKey, options, itemType));
} | class type of item.
* @return the Cosmos item response.
*/
public <T> CosmosItemResponse<T> readItem(
String itemId, PartitionKey partitionKey,
CosmosItemRequestOptions options, Class<T> itemType) {
return this.blockItemResponse(asyncContainer.readItem(itemId, partitionKey, options, itemType));
} |
https://github.com/Azure/azure-sdk-for-java/blob/bbb09a6f10d4deee9ccc58fda29b1364de007c1e/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/BulkExecutor.java#L862-L885 | public void openConnectionsAndInitCaches() {
this.asyncContainer.openConnectionsAndInitCaches().subscribe();
} | this.asyncContainer.openConnectionsAndInitCaches().subscribe(); | public void openConnectionsAndInitCaches() {
blockVoidResponse(this.asyncContainer.openConnectionsAndInitCaches());
} | class type of item.
* @return the Cosmos item response.
*/
public <T> CosmosItemResponse<T> readItem(
String itemId, PartitionKey partitionKey,
CosmosItemRequestOptions options, Class<T> itemType) {
return this.blockItemResponse(asyncContainer.readItem(itemId, partitionKey, options, itemType));
} | class type of item.
* @return the Cosmos item response.
*/
public <T> CosmosItemResponse<T> readItem(
String itemId, PartitionKey partitionKey,
CosmosItemRequestOptions options, Class<T> itemType) {
return this.blockItemResponse(asyncContainer.readItem(itemId, partitionKey, options, itemType));
} |
maybe `setAggressiveProactiveConnectionEstablishmentTimeWindow `-> `setAggressiveProactiveConnectionEstablishmentDuration`. (just open for discussion) | void run() throws Exception {
boolean shouldOpenConnectionsAndInitCaches = configuration.getConnectionMode() == ConnectionMode.DIRECT
&& configuration.isProactiveConnectionManagementEnabled()
&& !configuration.isUseUnWarmedUpContainer();
CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder()
.endpoint(configuration.getServiceEndpoint())
.key(configuration.getMasterKey())
.preferredRegions(configuration.getPreferredRegionsList())
.directMode();
if (shouldOpenConnectionsAndInitCaches) {
logger.info("Proactively establishing connections...");
List<CosmosContainerIdentity> cosmosContainerIdentities = new ArrayList<>();
CosmosContainerIdentity cosmosContainerIdentity = new CosmosContainerIdentity(
configuration.getDatabaseId(),
configuration.getCollectionId()
);
cosmosContainerIdentities.add(cosmosContainerIdentity);
CosmosContainerProactiveInitConfigBuilder cosmosContainerProactiveInitConfigBuilder = new
CosmosContainerProactiveInitConfigBuilder(cosmosContainerIdentities)
.setProactiveConnectionRegionsCount(configuration.getProactiveConnectionRegionsCount());
if (configuration.getConnectionWarmUpTimeout() == Duration.ZERO) {
cosmosClientBuilder = cosmosClientBuilder
.openConnectionsAndInitCaches(cosmosContainerProactiveInitConfigBuilder.build())
.endpointDiscoveryEnabled(true);
} else {
cosmosContainerProactiveInitConfigBuilder = cosmosContainerProactiveInitConfigBuilder
.setAggressiveProactiveConnectionEstablishmentTimeWindow(configuration.getConnectionWarmUpTimeout());
cosmosClientBuilder = cosmosClientBuilder
.openConnectionsAndInitCaches(cosmosContainerProactiveInitConfigBuilder.build())
.endpointDiscoveryEnabled(true);
}
if (configuration.getMinConnectionPoolSizePerEndpoint() >= 1) {
System.setProperty("COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT", configuration.getMinConnectionPoolSizePerEndpoint().toString());
}
CosmosAsyncClient openConnectionsAsyncClient = cosmosClientBuilder.buildAsyncClient();
openConnectionsAsyncClient.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block();
CosmosAsyncDatabase databaseForProactiveConnectionManagement = openConnectionsAsyncClient.getDatabase(cosmosAsyncDatabase.getId());
databaseForProactiveConnectionManagement.createContainerIfNotExists(configuration.getCollectionId(), "/id").block();
cosmosAsyncContainerWithConnectionsEstablished = databaseForProactiveConnectionManagement.getContainer(configuration.getCollectionId());
}
if (!configuration.isProactiveConnectionManagementEnabled() && configuration.isUseUnWarmedUpContainer()) {
logger.info("Creating unwarmed container");
CosmosAsyncClient clientForUnwarmedContainer = new CosmosClientBuilder()
.endpoint(configuration.getServiceEndpoint())
.key(configuration.getMasterKey())
.preferredRegions(configuration.getPreferredRegionsList())
.directMode()
.buildAsyncClient();
clientForUnwarmedContainer.createDatabaseIfNotExists(configuration.getDatabaseId()).block();
CosmosAsyncDatabase databaseForUnwarmedContainer = clientForUnwarmedContainer.getDatabase(configuration.getDatabaseId());
databaseForUnwarmedContainer.createContainerIfNotExists(configuration.getCollectionId(), "/id").block();
cosmosAsyncContainerWithConnectionsUnestablished = databaseForUnwarmedContainer.getContainer(configuration.getCollectionId());
}
initializeMeter();
if (configuration.getSkipWarmUpOperations() > 0) {
logger.info("Starting warm up phase. Executing {} operations to warm up ...", configuration.getSkipWarmUpOperations());
warmupMode.set(true);
} else {
reporter.start(configuration.getPrintingInterval(), TimeUnit.SECONDS);
}
long startTime = System.currentTimeMillis();
AtomicLong count = new AtomicLong(0);
long i;
for ( i = 0; BenchmarkHelper.shouldContinue(startTime, i, configuration); i++) {
BaseSubscriber<T> baseSubscriber = new BaseSubscriber<T>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
super.hookOnSubscribe(subscription);
}
@Override
protected void hookOnNext(T value) {
logger.debug("hookOnNext: {}, count:{}", value, count.get());
}
@Override
protected void hookOnCancel() {
this.hookOnError(new CancellationException());
}
@Override
protected void hookOnComplete() {
initializeMetersIfSkippedEnoughOperations(count);
successMeter.mark();
concurrencyControlSemaphore.release();
AsyncBenchmark.this.onSuccess();
synchronized (count) {
count.incrementAndGet();
count.notify();
}
}
@Override
protected void hookOnError(Throwable throwable) {
initializeMetersIfSkippedEnoughOperations(count);
failureMeter.mark();
logger.error("Encountered failure {} on thread {}" ,
throwable.getMessage(), Thread.currentThread().getName(), throwable);
concurrencyControlSemaphore.release();
AsyncBenchmark.this.onError(throwable);
synchronized (count) {
count.incrementAndGet();
count.notify();
}
}
};
performWorkload(baseSubscriber, i);
}
System.clearProperty("COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT");
synchronized (count) {
while (count.get() < i) {
count.wait();
}
}
long endTime = System.currentTimeMillis();
logger.info("[{}] operations performed in [{}] seconds.",
configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000));
reporter.report();
reporter.close();
} | .setAggressiveProactiveConnectionEstablishmentTimeWindow(configuration.getConnectionWarmUpTimeout()); | void run() throws Exception {
initializeMeter();
if (configuration.getSkipWarmUpOperations() > 0) {
logger.info("Starting warm up phase. Executing {} operations to warm up ...", configuration.getSkipWarmUpOperations());
warmupMode.set(true);
} else {
reporter.start(configuration.getPrintingInterval(), TimeUnit.SECONDS);
}
long startTime = System.currentTimeMillis();
AtomicLong count = new AtomicLong(0);
long i;
for ( i = 0; BenchmarkHelper.shouldContinue(startTime, i, configuration); i++) {
BaseSubscriber<T> baseSubscriber = new BaseSubscriber<T>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
super.hookOnSubscribe(subscription);
}
@Override
protected void hookOnNext(T value) {
logger.debug("hookOnNext: {}, count:{}", value, count.get());
}
@Override
protected void hookOnCancel() {
this.hookOnError(new CancellationException());
}
@Override
protected void hookOnComplete() {
initializeMetersIfSkippedEnoughOperations(count);
successMeter.mark();
concurrencyControlSemaphore.release();
AsyncBenchmark.this.onSuccess();
synchronized (count) {
count.incrementAndGet();
count.notify();
}
}
@Override
protected void hookOnError(Throwable throwable) {
initializeMetersIfSkippedEnoughOperations(count);
failureMeter.mark();
logger.error("Encountered failure {} on thread {}" ,
throwable.getMessage(), Thread.currentThread().getName(), throwable);
concurrencyControlSemaphore.release();
AsyncBenchmark.this.onError(throwable);
synchronized (count) {
count.incrementAndGet();
count.notify();
}
}
};
performWorkload(baseSubscriber, i);
}
synchronized (count) {
while (count.get() < i) {
count.wait();
}
}
long endTime = System.currentTimeMillis();
logger.info("[{}] operations performed in [{}] seconds.",
configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000));
reporter.report();
reporter.close();
} | class AsyncBenchmark<T> {
private final MetricRegistry metricsRegistry = new MetricRegistry();
private final ScheduledReporter reporter;
private volatile Meter successMeter;
private volatile Meter failureMeter;
private boolean databaseCreated;
private boolean collectionCreated;
final Logger logger;
final CosmosAsyncClient cosmosClient;
CosmosAsyncContainer cosmosAsyncContainer;
CosmosAsyncDatabase cosmosAsyncDatabase;
CosmosAsyncContainer cosmosAsyncContainerWithConnectionsEstablished;
CosmosAsyncContainer cosmosAsyncContainerWithConnectionsUnestablished;
final String partitionKey;
final Configuration configuration;
final List<PojoizedJson> docsToRead;
final Semaphore concurrencyControlSemaphore;
Timer latency;
private static final String SUCCESS_COUNTER_METER_NAME = "
private static final String FAILURE_COUNTER_METER_NAME = "
private static final String LATENCY_METER_NAME = "latency";
private AtomicBoolean warmupMode = new AtomicBoolean(false);
AsyncBenchmark(Configuration cfg) {
logger = LoggerFactory.getLogger(this.getClass());
configuration = cfg;
CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder()
.endpoint(cfg.getServiceEndpoint())
.key(cfg.getMasterKey())
.preferredRegions(cfg.getPreferredRegionsList())
.consistencyLevel(cfg.getConsistencyLevel())
.userAgentSuffix(configuration.getApplicationName())
.contentResponseOnWriteEnabled(cfg.isContentResponseOnWriteEnabled());
CosmosClientTelemetryConfig telemetryConfig = new CosmosClientTelemetryConfig()
.sendClientTelemetryToService(cfg.isClientTelemetryEnabled())
.diagnosticsThresholds(
new CosmosDiagnosticsThresholds()
.setPointOperationLatencyThreshold(cfg.getPointOperationThreshold())
.setNonPointOperationLatencyThreshold(cfg.getNonPointOperationThreshold())
);
if (configuration.isDefaultLog4jLoggerEnabled()) {
telemetryConfig.diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER);
}
MeterRegistry registry = configuration.getAzureMonitorMeterRegistry();
if (registry != null) {
logger.info("USING AZURE METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(registry));
} else {
registry = configuration.getGraphiteMeterRegistry();
if (registry != null) {
logger.info("USING GRAPHITE METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(registry));
} else {
logger.info("USING DEFAULT/GLOBAL METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(
new CosmosMicrometerMetricsOptions().meterRegistry(null));
}
}
cosmosClientBuilder.clientTelemetryConfig(telemetryConfig);
if (cfg.getConnectionMode().equals(ConnectionMode.DIRECT)) {
cosmosClientBuilder = cosmosClientBuilder.directMode(DirectConnectionConfig.getDefaultConfig());
} else {
GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig();
gatewayConnectionConfig.setMaxConnectionPoolSize(cfg.getMaxConnectionPoolSize());
cosmosClientBuilder = cosmosClientBuilder.gatewayMode(gatewayConnectionConfig);
}
cosmosClient = cosmosClientBuilder.buildAsyncClient();
try {
cosmosAsyncDatabase = cosmosClient.getDatabase(this.configuration.getDatabaseId());
cosmosAsyncDatabase.read().block();
} catch (CosmosException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
cosmosClient.createDatabase(cfg.getDatabaseId()).block();
cosmosAsyncDatabase = cosmosClient.getDatabase(cfg.getDatabaseId());
logger.info("Database {} is created for this test", this.configuration.getDatabaseId());
databaseCreated = true;
} else {
throw e;
}
}
try {
cosmosAsyncContainer = cosmosAsyncDatabase.getContainer(this.configuration.getCollectionId());
cosmosAsyncContainer.read().block();
} catch (CosmosException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
cosmosAsyncDatabase.createContainer(
this.configuration.getCollectionId(),
Configuration.DEFAULT_PARTITION_KEY_PATH,
ThroughputProperties.createManualThroughput(this.configuration.getThroughput())
).block();
cosmosAsyncContainer = cosmosAsyncDatabase.getContainer(this.configuration.getCollectionId());
logger.info("Collection {} is created for this test", this.configuration.getCollectionId());
collectionCreated = true;
} else {
throw e;
}
}
partitionKey = cosmosAsyncContainer.read().block().getProperties().getPartitionKeyDefinition()
.getPaths().iterator().next().split("/")[1];
concurrencyControlSemaphore = new Semaphore(cfg.getConcurrency());
ArrayList<Flux<PojoizedJson>> createDocumentObservables = new ArrayList<>();
if (configuration.getOperationType() != Configuration.Operation.WriteLatency
&& configuration.getOperationType() != Configuration.Operation.WriteThroughput
&& configuration.getOperationType() != Configuration.Operation.ReadMyWrites) {
logger.info("PRE-populating {} documents ....", cfg.getNumberOfPreCreatedDocuments());
String dataFieldValue = RandomStringUtils.randomAlphabetic(cfg.getDocumentDataFieldSize());
for (int i = 0; i < cfg.getNumberOfPreCreatedDocuments(); i++) {
String uuid = UUID.randomUUID().toString();
PojoizedJson newDoc = BenchmarkHelper.generateDocument(uuid,
dataFieldValue,
partitionKey,
configuration.getDocumentDataFieldCount());
Flux<PojoizedJson> obs = cosmosAsyncContainer
.createItem(newDoc)
.retryWhen(Retry.max(5).filter((error) -> {
if (!(error instanceof CosmosException)) {
return false;
}
final CosmosException cosmosException = (CosmosException)error;
if (cosmosException.getStatusCode() == 410 ||
cosmosException.getStatusCode() == 408 ||
cosmosException.getStatusCode() == 429 ||
cosmosException.getStatusCode() == 503) {
return true;
}
return false;
}))
.onErrorResume(
(error) -> {
if (!(error instanceof CosmosException)) {
return false;
}
final CosmosException cosmosException = (CosmosException)error;
if (cosmosException.getStatusCode() == 409) {
return true;
}
return false;
},
(conflictException) -> cosmosAsyncContainer.readItem(
uuid, new PartitionKey(partitionKey), PojoizedJson.class)
)
.map(resp -> {
PojoizedJson x =
resp.getItem();
return x;
})
.flux();
createDocumentObservables.add(obs);
}
}
docsToRead = Flux.merge(Flux.fromIterable(createDocumentObservables), 100).collectList().block();
logger.info("Finished pre-populating {} documents", cfg.getNumberOfPreCreatedDocuments());
init();
if (configuration.isEnableJvmStats()) {
metricsRegistry.register("gc", new GarbageCollectorMetricSet());
metricsRegistry.register("threads", new CachedThreadStatesGaugeSet(10, TimeUnit.SECONDS));
metricsRegistry.register("memory", new MemoryUsageGaugeSet());
}
if (configuration.getGraphiteEndpoint() != null) {
final Graphite graphite = new Graphite(new InetSocketAddress(
configuration.getGraphiteEndpoint(),
configuration.getGraphiteEndpointPort()));
reporter = GraphiteReporter.forRegistry(metricsRegistry)
.prefixedWith(configuration.getOperationType().name())
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.filter(MetricFilter.ALL)
.build(graphite);
} else if (configuration.getReportingDirectory() != null) {
reporter = CsvReporter.forRegistry(metricsRegistry)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.build(configuration.getReportingDirectory());
} else {
reporter = ConsoleReporter.forRegistry(metricsRegistry)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.build();
}
}
protected void init() {
}
void shutdown() {
if (this.databaseCreated) {
cosmosAsyncDatabase.delete().block();
logger.info("Deleted temporary database {} created for this test", this.configuration.getDatabaseId());
} else if (this.collectionCreated) {
cosmosAsyncContainer.delete().block();
logger.info("Deleted temporary collection {} created for this test", this.configuration.getCollectionId());
}
cosmosClient.close();
}
protected void onSuccess() {
}
protected void initializeMetersIfSkippedEnoughOperations(AtomicLong count) {
if (configuration.getSkipWarmUpOperations() > 0) {
if (count.get() >= configuration.getSkipWarmUpOperations()) {
if (warmupMode.get()) {
synchronized (this) {
if (warmupMode.get()) {
logger.info("Warmup phase finished. Starting capturing perf numbers ....");
resetMeters();
initializeMeter();
reporter.start(configuration.getPrintingInterval(), TimeUnit.SECONDS);
warmupMode.set(false);
}
}
}
}
}
}
protected void onError(Throwable throwable) {
}
protected abstract void performWorkload(BaseSubscriber<T> baseSubscriber, long i) throws Exception;
private void resetMeters() {
metricsRegistry.remove(SUCCESS_COUNTER_METER_NAME);
metricsRegistry.remove(FAILURE_COUNTER_METER_NAME);
if (latencyAwareOperations(configuration.getOperationType())) {
metricsRegistry.remove(LATENCY_METER_NAME);
}
}
private void initializeMeter() {
successMeter = metricsRegistry.meter(SUCCESS_COUNTER_METER_NAME);
failureMeter = metricsRegistry.meter(FAILURE_COUNTER_METER_NAME);
if (latencyAwareOperations(configuration.getOperationType())) {
latency = metricsRegistry.register(LATENCY_METER_NAME, new Timer(new HdrHistogramResetOnSnapshotReservoir()));
}
}
private boolean latencyAwareOperations(Configuration.Operation operation) {
switch (configuration.getOperationType()) {
case ReadLatency:
case WriteLatency:
case QueryInClauseParallel:
case QueryCross:
case QuerySingle:
case QuerySingleMany:
case QueryParallel:
case QueryOrderby:
case QueryAggregate:
case QueryAggregateTopOrderby:
case QueryTopOrderby:
case Mixed:
case ReadAllItemsOfLogicalPartition:
case ReadManyLatency:
return true;
default:
return false;
}
}
protected Mono sparsityMono(long i) {
Duration duration = configuration.getSparsityWaitTime();
if (duration != null && !duration.isZero()) {
if (configuration.getSkipWarmUpOperations() > i) {
return null;
}
return Mono.delay(duration);
}
else return null;
}
} | class AsyncBenchmark<T> {
private final MetricRegistry metricsRegistry = new MetricRegistry();
private final ScheduledReporter reporter;
private volatile Meter successMeter;
private volatile Meter failureMeter;
private boolean databaseCreated;
private boolean collectionCreated;
final Logger logger;
final CosmosAsyncClient cosmosClient;
CosmosAsyncContainer cosmosAsyncContainer;
CosmosAsyncDatabase cosmosAsyncDatabase;
final String partitionKey;
final Configuration configuration;
final List<PojoizedJson> docsToRead;
final Semaphore concurrencyControlSemaphore;
Timer latency;
private static final String SUCCESS_COUNTER_METER_NAME = "
private static final String FAILURE_COUNTER_METER_NAME = "
private static final String LATENCY_METER_NAME = "latency";
private AtomicBoolean warmupMode = new AtomicBoolean(false);
AsyncBenchmark(Configuration cfg) {
logger = LoggerFactory.getLogger(this.getClass());
configuration = cfg;
CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder()
.endpoint(cfg.getServiceEndpoint())
.key(cfg.getMasterKey())
.preferredRegions(cfg.getPreferredRegionsList())
.consistencyLevel(cfg.getConsistencyLevel())
.userAgentSuffix(configuration.getApplicationName())
.contentResponseOnWriteEnabled(cfg.isContentResponseOnWriteEnabled());
CosmosClientTelemetryConfig telemetryConfig = new CosmosClientTelemetryConfig()
.sendClientTelemetryToService(cfg.isClientTelemetryEnabled())
.diagnosticsThresholds(
new CosmosDiagnosticsThresholds()
.setPointOperationLatencyThreshold(cfg.getPointOperationThreshold())
.setNonPointOperationLatencyThreshold(cfg.getNonPointOperationThreshold())
);
if (configuration.isDefaultLog4jLoggerEnabled()) {
telemetryConfig.diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER);
}
MeterRegistry registry = configuration.getAzureMonitorMeterRegistry();
if (registry != null) {
logger.info("USING AZURE METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(registry));
} else {
registry = configuration.getGraphiteMeterRegistry();
if (registry != null) {
logger.info("USING GRAPHITE METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(registry));
} else {
logger.info("USING DEFAULT/GLOBAL METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(
new CosmosMicrometerMetricsOptions().meterRegistry(null));
}
}
cosmosClientBuilder.clientTelemetryConfig(telemetryConfig);
if (cfg.getConnectionMode().equals(ConnectionMode.DIRECT)) {
cosmosClientBuilder = cosmosClientBuilder.directMode(DirectConnectionConfig.getDefaultConfig());
} else {
GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig();
gatewayConnectionConfig.setMaxConnectionPoolSize(cfg.getMaxConnectionPoolSize());
cosmosClientBuilder = cosmosClientBuilder.gatewayMode(gatewayConnectionConfig);
}
cosmosClient = cosmosClientBuilder.buildAsyncClient();
try {
cosmosAsyncDatabase = cosmosClient.getDatabase(this.configuration.getDatabaseId());
cosmosAsyncDatabase.read().block();
} catch (CosmosException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
cosmosClient.createDatabase(cfg.getDatabaseId()).block();
cosmosAsyncDatabase = cosmosClient.getDatabase(cfg.getDatabaseId());
logger.info("Database {} is created for this test", this.configuration.getDatabaseId());
databaseCreated = true;
} else {
throw e;
}
}
try {
cosmosAsyncContainer = cosmosAsyncDatabase.getContainer(this.configuration.getCollectionId());
cosmosAsyncContainer.read().block();
} catch (CosmosException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
cosmosAsyncDatabase.createContainer(
this.configuration.getCollectionId(),
Configuration.DEFAULT_PARTITION_KEY_PATH,
ThroughputProperties.createManualThroughput(this.configuration.getThroughput())
).block();
cosmosAsyncContainer = cosmosAsyncDatabase.getContainer(this.configuration.getCollectionId());
logger.info("Collection {} is created for this test", this.configuration.getCollectionId());
collectionCreated = true;
} else {
throw e;
}
}
partitionKey = cosmosAsyncContainer.read().block().getProperties().getPartitionKeyDefinition()
.getPaths().iterator().next().split("/")[1];
concurrencyControlSemaphore = new Semaphore(cfg.getConcurrency());
ArrayList<Flux<PojoizedJson>> createDocumentObservables = new ArrayList<>();
if (configuration.getOperationType() != Configuration.Operation.WriteLatency
&& configuration.getOperationType() != Configuration.Operation.WriteThroughput
&& configuration.getOperationType() != Configuration.Operation.ReadMyWrites) {
logger.info("PRE-populating {} documents ....", cfg.getNumberOfPreCreatedDocuments());
String dataFieldValue = RandomStringUtils.randomAlphabetic(cfg.getDocumentDataFieldSize());
for (int i = 0; i < cfg.getNumberOfPreCreatedDocuments(); i++) {
String uuid = UUID.randomUUID().toString();
PojoizedJson newDoc = BenchmarkHelper.generateDocument(uuid,
dataFieldValue,
partitionKey,
configuration.getDocumentDataFieldCount());
Flux<PojoizedJson> obs = cosmosAsyncContainer
.createItem(newDoc)
.retryWhen(Retry.max(5).filter((error) -> {
if (!(error instanceof CosmosException)) {
return false;
}
final CosmosException cosmosException = (CosmosException)error;
if (cosmosException.getStatusCode() == 410 ||
cosmosException.getStatusCode() == 408 ||
cosmosException.getStatusCode() == 429 ||
cosmosException.getStatusCode() == 503) {
return true;
}
return false;
}))
.onErrorResume(
(error) -> {
if (!(error instanceof CosmosException)) {
return false;
}
final CosmosException cosmosException = (CosmosException)error;
if (cosmosException.getStatusCode() == 409) {
return true;
}
return false;
},
(conflictException) -> cosmosAsyncContainer.readItem(
uuid, new PartitionKey(partitionKey), PojoizedJson.class)
)
.map(resp -> {
PojoizedJson x =
resp.getItem();
return x;
})
.flux();
createDocumentObservables.add(obs);
}
}
docsToRead = Flux.merge(Flux.fromIterable(createDocumentObservables), 100).collectList().block();
logger.info("Finished pre-populating {} documents", cfg.getNumberOfPreCreatedDocuments());
init();
if (configuration.isEnableJvmStats()) {
metricsRegistry.register("gc", new GarbageCollectorMetricSet());
metricsRegistry.register("threads", new CachedThreadStatesGaugeSet(10, TimeUnit.SECONDS));
metricsRegistry.register("memory", new MemoryUsageGaugeSet());
}
if (configuration.getGraphiteEndpoint() != null) {
final Graphite graphite = new Graphite(new InetSocketAddress(
configuration.getGraphiteEndpoint(),
configuration.getGraphiteEndpointPort()));
reporter = GraphiteReporter.forRegistry(metricsRegistry)
.prefixedWith(configuration.getOperationType().name())
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.filter(MetricFilter.ALL)
.build(graphite);
} else if (configuration.getReportingDirectory() != null) {
reporter = CsvReporter.forRegistry(metricsRegistry)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.build(configuration.getReportingDirectory());
} else {
reporter = ConsoleReporter.forRegistry(metricsRegistry)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.build();
}
boolean shouldOpenConnectionsAndInitCaches = configuration.getConnectionMode() == ConnectionMode.DIRECT
&& configuration.isProactiveConnectionManagementEnabled()
&& !configuration.isUseUnWarmedUpContainer();
CosmosClientBuilder cosmosClientBuilderForOpeningConnections = new CosmosClientBuilder()
.endpoint(configuration.getServiceEndpoint())
.key(configuration.getMasterKey())
.preferredRegions(configuration.getPreferredRegionsList())
.directMode();
if (shouldOpenConnectionsAndInitCaches) {
logger.info("Proactively establishing connections...");
List<CosmosContainerIdentity> cosmosContainerIdentities = new ArrayList<>();
CosmosContainerIdentity cosmosContainerIdentity = new CosmosContainerIdentity(
configuration.getDatabaseId(),
configuration.getCollectionId()
);
cosmosContainerIdentities.add(cosmosContainerIdentity);
CosmosContainerProactiveInitConfigBuilder cosmosContainerProactiveInitConfigBuilder = new
CosmosContainerProactiveInitConfigBuilder(cosmosContainerIdentities)
.setProactiveConnectionRegionsCount(configuration.getProactiveConnectionRegionsCount());
if (configuration.getAggressiveWarmupDuration() == Duration.ZERO) {
cosmosClientBuilder = cosmosClientBuilderForOpeningConnections
.openConnectionsAndInitCaches(cosmosContainerProactiveInitConfigBuilder.build())
.endpointDiscoveryEnabled(true);
} else {
logger.info("Setting an aggressive proactive connection establishment duration of {}", configuration.getAggressiveWarmupDuration());
cosmosContainerProactiveInitConfigBuilder = cosmosContainerProactiveInitConfigBuilder
.setAggressiveWarmupDuration(configuration.getAggressiveWarmupDuration());
cosmosClientBuilder = cosmosClientBuilder
.openConnectionsAndInitCaches(cosmosContainerProactiveInitConfigBuilder.build())
.endpointDiscoveryEnabled(true);
}
if (configuration.getMinConnectionPoolSizePerEndpoint() >= 1) {
System.setProperty("COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT", configuration.getMinConnectionPoolSizePerEndpoint().toString());
logger.info("Min connection pool size per endpoint : {}", System.getProperty("COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"));
}
CosmosAsyncClient openConnectionsAsyncClient = cosmosClientBuilder.buildAsyncClient();
openConnectionsAsyncClient.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block();
CosmosAsyncDatabase databaseForProactiveConnectionManagement = openConnectionsAsyncClient.getDatabase(cosmosAsyncDatabase.getId());
databaseForProactiveConnectionManagement.createContainerIfNotExists(configuration.getCollectionId(), "/id").block();
cosmosAsyncContainer = databaseForProactiveConnectionManagement.getContainer(configuration.getCollectionId());
}
if (!configuration.isProactiveConnectionManagementEnabled() && configuration.isUseUnWarmedUpContainer()) {
logger.info("Creating unwarmed container");
CosmosAsyncClient clientForUnwarmedContainer = new CosmosClientBuilder()
.endpoint(configuration.getServiceEndpoint())
.key(configuration.getMasterKey())
.preferredRegions(configuration.getPreferredRegionsList())
.directMode()
.buildAsyncClient();
clientForUnwarmedContainer.createDatabaseIfNotExists(configuration.getDatabaseId()).block();
CosmosAsyncDatabase databaseForUnwarmedContainer = clientForUnwarmedContainer.getDatabase(configuration.getDatabaseId());
databaseForUnwarmedContainer.createContainerIfNotExists(configuration.getCollectionId(), "/id").block();
cosmosAsyncContainer = databaseForUnwarmedContainer.getContainer(configuration.getCollectionId());
}
}
protected void init() {
}
void shutdown() {
if (this.databaseCreated) {
cosmosAsyncDatabase.delete().block();
logger.info("Deleted temporary database {} created for this test", this.configuration.getDatabaseId());
} else if (this.collectionCreated) {
cosmosAsyncContainer.delete().block();
logger.info("Deleted temporary collection {} created for this test", this.configuration.getCollectionId());
}
cosmosClient.close();
}
protected void onSuccess() {
}
protected void initializeMetersIfSkippedEnoughOperations(AtomicLong count) {
if (configuration.getSkipWarmUpOperations() > 0) {
if (count.get() >= configuration.getSkipWarmUpOperations()) {
if (warmupMode.get()) {
synchronized (this) {
if (warmupMode.get()) {
logger.info("Warmup phase finished. Starting capturing perf numbers ....");
resetMeters();
initializeMeter();
reporter.start(configuration.getPrintingInterval(), TimeUnit.SECONDS);
warmupMode.set(false);
}
}
}
}
}
}
protected void onError(Throwable throwable) {
}
protected abstract void performWorkload(BaseSubscriber<T> baseSubscriber, long i) throws Exception;
private void resetMeters() {
metricsRegistry.remove(SUCCESS_COUNTER_METER_NAME);
metricsRegistry.remove(FAILURE_COUNTER_METER_NAME);
if (latencyAwareOperations(configuration.getOperationType())) {
metricsRegistry.remove(LATENCY_METER_NAME);
}
}
private void initializeMeter() {
successMeter = metricsRegistry.meter(SUCCESS_COUNTER_METER_NAME);
failureMeter = metricsRegistry.meter(FAILURE_COUNTER_METER_NAME);
if (latencyAwareOperations(configuration.getOperationType())) {
latency = metricsRegistry.register(LATENCY_METER_NAME, new Timer(new HdrHistogramResetOnSnapshotReservoir()));
}
}
private boolean latencyAwareOperations(Configuration.Operation operation) {
switch (configuration.getOperationType()) {
case ReadLatency:
case WriteLatency:
case QueryInClauseParallel:
case QueryCross:
case QuerySingle:
case QuerySingleMany:
case QueryParallel:
case QueryOrderby:
case QueryAggregate:
case QueryAggregateTopOrderby:
case QueryTopOrderby:
case Mixed:
case ReadAllItemsOfLogicalPartition:
case ReadManyLatency:
return true;
default:
return false;
}
}
protected Mono sparsityMono(long i) {
Duration duration = configuration.getSparsityWaitTime();
if (duration != null && !duration.isZero()) {
if (configuration.getSkipWarmUpOperations() > i) {
return null;
}
return Mono.delay(duration);
}
else return null;
}
} |
`setAggressiveProactiveConnectionEstablishmentDuration` sounds like a better name. Updated it. | void run() throws Exception {
boolean shouldOpenConnectionsAndInitCaches = configuration.getConnectionMode() == ConnectionMode.DIRECT
&& configuration.isProactiveConnectionManagementEnabled()
&& !configuration.isUseUnWarmedUpContainer();
CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder()
.endpoint(configuration.getServiceEndpoint())
.key(configuration.getMasterKey())
.preferredRegions(configuration.getPreferredRegionsList())
.directMode();
if (shouldOpenConnectionsAndInitCaches) {
logger.info("Proactively establishing connections...");
List<CosmosContainerIdentity> cosmosContainerIdentities = new ArrayList<>();
CosmosContainerIdentity cosmosContainerIdentity = new CosmosContainerIdentity(
configuration.getDatabaseId(),
configuration.getCollectionId()
);
cosmosContainerIdentities.add(cosmosContainerIdentity);
CosmosContainerProactiveInitConfigBuilder cosmosContainerProactiveInitConfigBuilder = new
CosmosContainerProactiveInitConfigBuilder(cosmosContainerIdentities)
.setProactiveConnectionRegionsCount(configuration.getProactiveConnectionRegionsCount());
if (configuration.getConnectionWarmUpTimeout() == Duration.ZERO) {
cosmosClientBuilder = cosmosClientBuilder
.openConnectionsAndInitCaches(cosmosContainerProactiveInitConfigBuilder.build())
.endpointDiscoveryEnabled(true);
} else {
cosmosContainerProactiveInitConfigBuilder = cosmosContainerProactiveInitConfigBuilder
.setAggressiveProactiveConnectionEstablishmentTimeWindow(configuration.getConnectionWarmUpTimeout());
cosmosClientBuilder = cosmosClientBuilder
.openConnectionsAndInitCaches(cosmosContainerProactiveInitConfigBuilder.build())
.endpointDiscoveryEnabled(true);
}
if (configuration.getMinConnectionPoolSizePerEndpoint() >= 1) {
System.setProperty("COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT", configuration.getMinConnectionPoolSizePerEndpoint().toString());
}
CosmosAsyncClient openConnectionsAsyncClient = cosmosClientBuilder.buildAsyncClient();
openConnectionsAsyncClient.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block();
CosmosAsyncDatabase databaseForProactiveConnectionManagement = openConnectionsAsyncClient.getDatabase(cosmosAsyncDatabase.getId());
databaseForProactiveConnectionManagement.createContainerIfNotExists(configuration.getCollectionId(), "/id").block();
cosmosAsyncContainerWithConnectionsEstablished = databaseForProactiveConnectionManagement.getContainer(configuration.getCollectionId());
}
if (!configuration.isProactiveConnectionManagementEnabled() && configuration.isUseUnWarmedUpContainer()) {
logger.info("Creating unwarmed container");
CosmosAsyncClient clientForUnwarmedContainer = new CosmosClientBuilder()
.endpoint(configuration.getServiceEndpoint())
.key(configuration.getMasterKey())
.preferredRegions(configuration.getPreferredRegionsList())
.directMode()
.buildAsyncClient();
clientForUnwarmedContainer.createDatabaseIfNotExists(configuration.getDatabaseId()).block();
CosmosAsyncDatabase databaseForUnwarmedContainer = clientForUnwarmedContainer.getDatabase(configuration.getDatabaseId());
databaseForUnwarmedContainer.createContainerIfNotExists(configuration.getCollectionId(), "/id").block();
cosmosAsyncContainerWithConnectionsUnestablished = databaseForUnwarmedContainer.getContainer(configuration.getCollectionId());
}
initializeMeter();
if (configuration.getSkipWarmUpOperations() > 0) {
logger.info("Starting warm up phase. Executing {} operations to warm up ...", configuration.getSkipWarmUpOperations());
warmupMode.set(true);
} else {
reporter.start(configuration.getPrintingInterval(), TimeUnit.SECONDS);
}
long startTime = System.currentTimeMillis();
AtomicLong count = new AtomicLong(0);
long i;
for ( i = 0; BenchmarkHelper.shouldContinue(startTime, i, configuration); i++) {
BaseSubscriber<T> baseSubscriber = new BaseSubscriber<T>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
super.hookOnSubscribe(subscription);
}
@Override
protected void hookOnNext(T value) {
logger.debug("hookOnNext: {}, count:{}", value, count.get());
}
@Override
protected void hookOnCancel() {
this.hookOnError(new CancellationException());
}
@Override
protected void hookOnComplete() {
initializeMetersIfSkippedEnoughOperations(count);
successMeter.mark();
concurrencyControlSemaphore.release();
AsyncBenchmark.this.onSuccess();
synchronized (count) {
count.incrementAndGet();
count.notify();
}
}
@Override
protected void hookOnError(Throwable throwable) {
initializeMetersIfSkippedEnoughOperations(count);
failureMeter.mark();
logger.error("Encountered failure {} on thread {}" ,
throwable.getMessage(), Thread.currentThread().getName(), throwable);
concurrencyControlSemaphore.release();
AsyncBenchmark.this.onError(throwable);
synchronized (count) {
count.incrementAndGet();
count.notify();
}
}
};
performWorkload(baseSubscriber, i);
}
System.clearProperty("COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT");
synchronized (count) {
while (count.get() < i) {
count.wait();
}
}
long endTime = System.currentTimeMillis();
logger.info("[{}] operations performed in [{}] seconds.",
configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000));
reporter.report();
reporter.close();
} | .setAggressiveProactiveConnectionEstablishmentTimeWindow(configuration.getConnectionWarmUpTimeout()); | void run() throws Exception {
initializeMeter();
if (configuration.getSkipWarmUpOperations() > 0) {
logger.info("Starting warm up phase. Executing {} operations to warm up ...", configuration.getSkipWarmUpOperations());
warmupMode.set(true);
} else {
reporter.start(configuration.getPrintingInterval(), TimeUnit.SECONDS);
}
long startTime = System.currentTimeMillis();
AtomicLong count = new AtomicLong(0);
long i;
for ( i = 0; BenchmarkHelper.shouldContinue(startTime, i, configuration); i++) {
BaseSubscriber<T> baseSubscriber = new BaseSubscriber<T>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
super.hookOnSubscribe(subscription);
}
@Override
protected void hookOnNext(T value) {
logger.debug("hookOnNext: {}, count:{}", value, count.get());
}
@Override
protected void hookOnCancel() {
this.hookOnError(new CancellationException());
}
@Override
protected void hookOnComplete() {
initializeMetersIfSkippedEnoughOperations(count);
successMeter.mark();
concurrencyControlSemaphore.release();
AsyncBenchmark.this.onSuccess();
synchronized (count) {
count.incrementAndGet();
count.notify();
}
}
@Override
protected void hookOnError(Throwable throwable) {
initializeMetersIfSkippedEnoughOperations(count);
failureMeter.mark();
logger.error("Encountered failure {} on thread {}" ,
throwable.getMessage(), Thread.currentThread().getName(), throwable);
concurrencyControlSemaphore.release();
AsyncBenchmark.this.onError(throwable);
synchronized (count) {
count.incrementAndGet();
count.notify();
}
}
};
performWorkload(baseSubscriber, i);
}
synchronized (count) {
while (count.get() < i) {
count.wait();
}
}
long endTime = System.currentTimeMillis();
logger.info("[{}] operations performed in [{}] seconds.",
configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000));
reporter.report();
reporter.close();
} | class AsyncBenchmark<T> {
private final MetricRegistry metricsRegistry = new MetricRegistry();
private final ScheduledReporter reporter;
private volatile Meter successMeter;
private volatile Meter failureMeter;
private boolean databaseCreated;
private boolean collectionCreated;
final Logger logger;
final CosmosAsyncClient cosmosClient;
CosmosAsyncContainer cosmosAsyncContainer;
CosmosAsyncDatabase cosmosAsyncDatabase;
CosmosAsyncContainer cosmosAsyncContainerWithConnectionsEstablished;
CosmosAsyncContainer cosmosAsyncContainerWithConnectionsUnestablished;
final String partitionKey;
final Configuration configuration;
final List<PojoizedJson> docsToRead;
final Semaphore concurrencyControlSemaphore;
Timer latency;
private static final String SUCCESS_COUNTER_METER_NAME = "
private static final String FAILURE_COUNTER_METER_NAME = "
private static final String LATENCY_METER_NAME = "latency";
private AtomicBoolean warmupMode = new AtomicBoolean(false);
AsyncBenchmark(Configuration cfg) {
logger = LoggerFactory.getLogger(this.getClass());
configuration = cfg;
CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder()
.endpoint(cfg.getServiceEndpoint())
.key(cfg.getMasterKey())
.preferredRegions(cfg.getPreferredRegionsList())
.consistencyLevel(cfg.getConsistencyLevel())
.userAgentSuffix(configuration.getApplicationName())
.contentResponseOnWriteEnabled(cfg.isContentResponseOnWriteEnabled());
CosmosClientTelemetryConfig telemetryConfig = new CosmosClientTelemetryConfig()
.sendClientTelemetryToService(cfg.isClientTelemetryEnabled())
.diagnosticsThresholds(
new CosmosDiagnosticsThresholds()
.setPointOperationLatencyThreshold(cfg.getPointOperationThreshold())
.setNonPointOperationLatencyThreshold(cfg.getNonPointOperationThreshold())
);
if (configuration.isDefaultLog4jLoggerEnabled()) {
telemetryConfig.diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER);
}
MeterRegistry registry = configuration.getAzureMonitorMeterRegistry();
if (registry != null) {
logger.info("USING AZURE METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(registry));
} else {
registry = configuration.getGraphiteMeterRegistry();
if (registry != null) {
logger.info("USING GRAPHITE METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(registry));
} else {
logger.info("USING DEFAULT/GLOBAL METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(
new CosmosMicrometerMetricsOptions().meterRegistry(null));
}
}
cosmosClientBuilder.clientTelemetryConfig(telemetryConfig);
if (cfg.getConnectionMode().equals(ConnectionMode.DIRECT)) {
cosmosClientBuilder = cosmosClientBuilder.directMode(DirectConnectionConfig.getDefaultConfig());
} else {
GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig();
gatewayConnectionConfig.setMaxConnectionPoolSize(cfg.getMaxConnectionPoolSize());
cosmosClientBuilder = cosmosClientBuilder.gatewayMode(gatewayConnectionConfig);
}
cosmosClient = cosmosClientBuilder.buildAsyncClient();
try {
cosmosAsyncDatabase = cosmosClient.getDatabase(this.configuration.getDatabaseId());
cosmosAsyncDatabase.read().block();
} catch (CosmosException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
cosmosClient.createDatabase(cfg.getDatabaseId()).block();
cosmosAsyncDatabase = cosmosClient.getDatabase(cfg.getDatabaseId());
logger.info("Database {} is created for this test", this.configuration.getDatabaseId());
databaseCreated = true;
} else {
throw e;
}
}
try {
cosmosAsyncContainer = cosmosAsyncDatabase.getContainer(this.configuration.getCollectionId());
cosmosAsyncContainer.read().block();
} catch (CosmosException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
cosmosAsyncDatabase.createContainer(
this.configuration.getCollectionId(),
Configuration.DEFAULT_PARTITION_KEY_PATH,
ThroughputProperties.createManualThroughput(this.configuration.getThroughput())
).block();
cosmosAsyncContainer = cosmosAsyncDatabase.getContainer(this.configuration.getCollectionId());
logger.info("Collection {} is created for this test", this.configuration.getCollectionId());
collectionCreated = true;
} else {
throw e;
}
}
partitionKey = cosmosAsyncContainer.read().block().getProperties().getPartitionKeyDefinition()
.getPaths().iterator().next().split("/")[1];
concurrencyControlSemaphore = new Semaphore(cfg.getConcurrency());
ArrayList<Flux<PojoizedJson>> createDocumentObservables = new ArrayList<>();
if (configuration.getOperationType() != Configuration.Operation.WriteLatency
&& configuration.getOperationType() != Configuration.Operation.WriteThroughput
&& configuration.getOperationType() != Configuration.Operation.ReadMyWrites) {
logger.info("PRE-populating {} documents ....", cfg.getNumberOfPreCreatedDocuments());
String dataFieldValue = RandomStringUtils.randomAlphabetic(cfg.getDocumentDataFieldSize());
for (int i = 0; i < cfg.getNumberOfPreCreatedDocuments(); i++) {
String uuid = UUID.randomUUID().toString();
PojoizedJson newDoc = BenchmarkHelper.generateDocument(uuid,
dataFieldValue,
partitionKey,
configuration.getDocumentDataFieldCount());
Flux<PojoizedJson> obs = cosmosAsyncContainer
.createItem(newDoc)
.retryWhen(Retry.max(5).filter((error) -> {
if (!(error instanceof CosmosException)) {
return false;
}
final CosmosException cosmosException = (CosmosException)error;
if (cosmosException.getStatusCode() == 410 ||
cosmosException.getStatusCode() == 408 ||
cosmosException.getStatusCode() == 429 ||
cosmosException.getStatusCode() == 503) {
return true;
}
return false;
}))
.onErrorResume(
(error) -> {
if (!(error instanceof CosmosException)) {
return false;
}
final CosmosException cosmosException = (CosmosException)error;
if (cosmosException.getStatusCode() == 409) {
return true;
}
return false;
},
(conflictException) -> cosmosAsyncContainer.readItem(
uuid, new PartitionKey(partitionKey), PojoizedJson.class)
)
.map(resp -> {
PojoizedJson x =
resp.getItem();
return x;
})
.flux();
createDocumentObservables.add(obs);
}
}
docsToRead = Flux.merge(Flux.fromIterable(createDocumentObservables), 100).collectList().block();
logger.info("Finished pre-populating {} documents", cfg.getNumberOfPreCreatedDocuments());
init();
if (configuration.isEnableJvmStats()) {
metricsRegistry.register("gc", new GarbageCollectorMetricSet());
metricsRegistry.register("threads", new CachedThreadStatesGaugeSet(10, TimeUnit.SECONDS));
metricsRegistry.register("memory", new MemoryUsageGaugeSet());
}
if (configuration.getGraphiteEndpoint() != null) {
final Graphite graphite = new Graphite(new InetSocketAddress(
configuration.getGraphiteEndpoint(),
configuration.getGraphiteEndpointPort()));
reporter = GraphiteReporter.forRegistry(metricsRegistry)
.prefixedWith(configuration.getOperationType().name())
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.filter(MetricFilter.ALL)
.build(graphite);
} else if (configuration.getReportingDirectory() != null) {
reporter = CsvReporter.forRegistry(metricsRegistry)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.build(configuration.getReportingDirectory());
} else {
reporter = ConsoleReporter.forRegistry(metricsRegistry)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.build();
}
}
protected void init() {
}
void shutdown() {
if (this.databaseCreated) {
cosmosAsyncDatabase.delete().block();
logger.info("Deleted temporary database {} created for this test", this.configuration.getDatabaseId());
} else if (this.collectionCreated) {
cosmosAsyncContainer.delete().block();
logger.info("Deleted temporary collection {} created for this test", this.configuration.getCollectionId());
}
cosmosClient.close();
}
protected void onSuccess() {
}
protected void initializeMetersIfSkippedEnoughOperations(AtomicLong count) {
if (configuration.getSkipWarmUpOperations() > 0) {
if (count.get() >= configuration.getSkipWarmUpOperations()) {
if (warmupMode.get()) {
synchronized (this) {
if (warmupMode.get()) {
logger.info("Warmup phase finished. Starting capturing perf numbers ....");
resetMeters();
initializeMeter();
reporter.start(configuration.getPrintingInterval(), TimeUnit.SECONDS);
warmupMode.set(false);
}
}
}
}
}
}
protected void onError(Throwable throwable) {
}
protected abstract void performWorkload(BaseSubscriber<T> baseSubscriber, long i) throws Exception;
private void resetMeters() {
metricsRegistry.remove(SUCCESS_COUNTER_METER_NAME);
metricsRegistry.remove(FAILURE_COUNTER_METER_NAME);
if (latencyAwareOperations(configuration.getOperationType())) {
metricsRegistry.remove(LATENCY_METER_NAME);
}
}
private void initializeMeter() {
successMeter = metricsRegistry.meter(SUCCESS_COUNTER_METER_NAME);
failureMeter = metricsRegistry.meter(FAILURE_COUNTER_METER_NAME);
if (latencyAwareOperations(configuration.getOperationType())) {
latency = metricsRegistry.register(LATENCY_METER_NAME, new Timer(new HdrHistogramResetOnSnapshotReservoir()));
}
}
private boolean latencyAwareOperations(Configuration.Operation operation) {
switch (configuration.getOperationType()) {
case ReadLatency:
case WriteLatency:
case QueryInClauseParallel:
case QueryCross:
case QuerySingle:
case QuerySingleMany:
case QueryParallel:
case QueryOrderby:
case QueryAggregate:
case QueryAggregateTopOrderby:
case QueryTopOrderby:
case Mixed:
case ReadAllItemsOfLogicalPartition:
case ReadManyLatency:
return true;
default:
return false;
}
}
protected Mono sparsityMono(long i) {
Duration duration = configuration.getSparsityWaitTime();
if (duration != null && !duration.isZero()) {
if (configuration.getSkipWarmUpOperations() > i) {
return null;
}
return Mono.delay(duration);
}
else return null;
}
} | class AsyncBenchmark<T> {
private final MetricRegistry metricsRegistry = new MetricRegistry();
private final ScheduledReporter reporter;
private volatile Meter successMeter;
private volatile Meter failureMeter;
private boolean databaseCreated;
private boolean collectionCreated;
final Logger logger;
final CosmosAsyncClient cosmosClient;
CosmosAsyncContainer cosmosAsyncContainer;
CosmosAsyncDatabase cosmosAsyncDatabase;
final String partitionKey;
final Configuration configuration;
final List<PojoizedJson> docsToRead;
final Semaphore concurrencyControlSemaphore;
Timer latency;
private static final String SUCCESS_COUNTER_METER_NAME = "
private static final String FAILURE_COUNTER_METER_NAME = "
private static final String LATENCY_METER_NAME = "latency";
private AtomicBoolean warmupMode = new AtomicBoolean(false);
AsyncBenchmark(Configuration cfg) {
logger = LoggerFactory.getLogger(this.getClass());
configuration = cfg;
CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder()
.endpoint(cfg.getServiceEndpoint())
.key(cfg.getMasterKey())
.preferredRegions(cfg.getPreferredRegionsList())
.consistencyLevel(cfg.getConsistencyLevel())
.userAgentSuffix(configuration.getApplicationName())
.contentResponseOnWriteEnabled(cfg.isContentResponseOnWriteEnabled());
CosmosClientTelemetryConfig telemetryConfig = new CosmosClientTelemetryConfig()
.sendClientTelemetryToService(cfg.isClientTelemetryEnabled())
.diagnosticsThresholds(
new CosmosDiagnosticsThresholds()
.setPointOperationLatencyThreshold(cfg.getPointOperationThreshold())
.setNonPointOperationLatencyThreshold(cfg.getNonPointOperationThreshold())
);
if (configuration.isDefaultLog4jLoggerEnabled()) {
telemetryConfig.diagnosticsHandler(CosmosDiagnosticsHandler.DEFAULT_LOGGING_HANDLER);
}
MeterRegistry registry = configuration.getAzureMonitorMeterRegistry();
if (registry != null) {
logger.info("USING AZURE METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(registry));
} else {
registry = configuration.getGraphiteMeterRegistry();
if (registry != null) {
logger.info("USING GRAPHITE METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(registry));
} else {
logger.info("USING DEFAULT/GLOBAL METRIC REGISTRY - isClientTelemetryEnabled {}", cfg.isClientTelemetryEnabled());
telemetryConfig.metricsOptions(
new CosmosMicrometerMetricsOptions().meterRegistry(null));
}
}
cosmosClientBuilder.clientTelemetryConfig(telemetryConfig);
if (cfg.getConnectionMode().equals(ConnectionMode.DIRECT)) {
cosmosClientBuilder = cosmosClientBuilder.directMode(DirectConnectionConfig.getDefaultConfig());
} else {
GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig();
gatewayConnectionConfig.setMaxConnectionPoolSize(cfg.getMaxConnectionPoolSize());
cosmosClientBuilder = cosmosClientBuilder.gatewayMode(gatewayConnectionConfig);
}
cosmosClient = cosmosClientBuilder.buildAsyncClient();
try {
cosmosAsyncDatabase = cosmosClient.getDatabase(this.configuration.getDatabaseId());
cosmosAsyncDatabase.read().block();
} catch (CosmosException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
cosmosClient.createDatabase(cfg.getDatabaseId()).block();
cosmosAsyncDatabase = cosmosClient.getDatabase(cfg.getDatabaseId());
logger.info("Database {} is created for this test", this.configuration.getDatabaseId());
databaseCreated = true;
} else {
throw e;
}
}
try {
cosmosAsyncContainer = cosmosAsyncDatabase.getContainer(this.configuration.getCollectionId());
cosmosAsyncContainer.read().block();
} catch (CosmosException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
cosmosAsyncDatabase.createContainer(
this.configuration.getCollectionId(),
Configuration.DEFAULT_PARTITION_KEY_PATH,
ThroughputProperties.createManualThroughput(this.configuration.getThroughput())
).block();
cosmosAsyncContainer = cosmosAsyncDatabase.getContainer(this.configuration.getCollectionId());
logger.info("Collection {} is created for this test", this.configuration.getCollectionId());
collectionCreated = true;
} else {
throw e;
}
}
partitionKey = cosmosAsyncContainer.read().block().getProperties().getPartitionKeyDefinition()
.getPaths().iterator().next().split("/")[1];
concurrencyControlSemaphore = new Semaphore(cfg.getConcurrency());
ArrayList<Flux<PojoizedJson>> createDocumentObservables = new ArrayList<>();
if (configuration.getOperationType() != Configuration.Operation.WriteLatency
&& configuration.getOperationType() != Configuration.Operation.WriteThroughput
&& configuration.getOperationType() != Configuration.Operation.ReadMyWrites) {
logger.info("PRE-populating {} documents ....", cfg.getNumberOfPreCreatedDocuments());
String dataFieldValue = RandomStringUtils.randomAlphabetic(cfg.getDocumentDataFieldSize());
for (int i = 0; i < cfg.getNumberOfPreCreatedDocuments(); i++) {
String uuid = UUID.randomUUID().toString();
PojoizedJson newDoc = BenchmarkHelper.generateDocument(uuid,
dataFieldValue,
partitionKey,
configuration.getDocumentDataFieldCount());
Flux<PojoizedJson> obs = cosmosAsyncContainer
.createItem(newDoc)
.retryWhen(Retry.max(5).filter((error) -> {
if (!(error instanceof CosmosException)) {
return false;
}
final CosmosException cosmosException = (CosmosException)error;
if (cosmosException.getStatusCode() == 410 ||
cosmosException.getStatusCode() == 408 ||
cosmosException.getStatusCode() == 429 ||
cosmosException.getStatusCode() == 503) {
return true;
}
return false;
}))
.onErrorResume(
(error) -> {
if (!(error instanceof CosmosException)) {
return false;
}
final CosmosException cosmosException = (CosmosException)error;
if (cosmosException.getStatusCode() == 409) {
return true;
}
return false;
},
(conflictException) -> cosmosAsyncContainer.readItem(
uuid, new PartitionKey(partitionKey), PojoizedJson.class)
)
.map(resp -> {
PojoizedJson x =
resp.getItem();
return x;
})
.flux();
createDocumentObservables.add(obs);
}
}
docsToRead = Flux.merge(Flux.fromIterable(createDocumentObservables), 100).collectList().block();
logger.info("Finished pre-populating {} documents", cfg.getNumberOfPreCreatedDocuments());
init();
if (configuration.isEnableJvmStats()) {
metricsRegistry.register("gc", new GarbageCollectorMetricSet());
metricsRegistry.register("threads", new CachedThreadStatesGaugeSet(10, TimeUnit.SECONDS));
metricsRegistry.register("memory", new MemoryUsageGaugeSet());
}
if (configuration.getGraphiteEndpoint() != null) {
final Graphite graphite = new Graphite(new InetSocketAddress(
configuration.getGraphiteEndpoint(),
configuration.getGraphiteEndpointPort()));
reporter = GraphiteReporter.forRegistry(metricsRegistry)
.prefixedWith(configuration.getOperationType().name())
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.filter(MetricFilter.ALL)
.build(graphite);
} else if (configuration.getReportingDirectory() != null) {
reporter = CsvReporter.forRegistry(metricsRegistry)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.build(configuration.getReportingDirectory());
} else {
reporter = ConsoleReporter.forRegistry(metricsRegistry)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.convertRatesTo(TimeUnit.SECONDS)
.build();
}
boolean shouldOpenConnectionsAndInitCaches = configuration.getConnectionMode() == ConnectionMode.DIRECT
&& configuration.isProactiveConnectionManagementEnabled()
&& !configuration.isUseUnWarmedUpContainer();
CosmosClientBuilder cosmosClientBuilderForOpeningConnections = new CosmosClientBuilder()
.endpoint(configuration.getServiceEndpoint())
.key(configuration.getMasterKey())
.preferredRegions(configuration.getPreferredRegionsList())
.directMode();
if (shouldOpenConnectionsAndInitCaches) {
logger.info("Proactively establishing connections...");
List<CosmosContainerIdentity> cosmosContainerIdentities = new ArrayList<>();
CosmosContainerIdentity cosmosContainerIdentity = new CosmosContainerIdentity(
configuration.getDatabaseId(),
configuration.getCollectionId()
);
cosmosContainerIdentities.add(cosmosContainerIdentity);
CosmosContainerProactiveInitConfigBuilder cosmosContainerProactiveInitConfigBuilder = new
CosmosContainerProactiveInitConfigBuilder(cosmosContainerIdentities)
.setProactiveConnectionRegionsCount(configuration.getProactiveConnectionRegionsCount());
if (configuration.getAggressiveWarmupDuration() == Duration.ZERO) {
cosmosClientBuilder = cosmosClientBuilderForOpeningConnections
.openConnectionsAndInitCaches(cosmosContainerProactiveInitConfigBuilder.build())
.endpointDiscoveryEnabled(true);
} else {
logger.info("Setting an aggressive proactive connection establishment duration of {}", configuration.getAggressiveWarmupDuration());
cosmosContainerProactiveInitConfigBuilder = cosmosContainerProactiveInitConfigBuilder
.setAggressiveWarmupDuration(configuration.getAggressiveWarmupDuration());
cosmosClientBuilder = cosmosClientBuilder
.openConnectionsAndInitCaches(cosmosContainerProactiveInitConfigBuilder.build())
.endpointDiscoveryEnabled(true);
}
if (configuration.getMinConnectionPoolSizePerEndpoint() >= 1) {
System.setProperty("COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT", configuration.getMinConnectionPoolSizePerEndpoint().toString());
logger.info("Min connection pool size per endpoint : {}", System.getProperty("COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT"));
}
CosmosAsyncClient openConnectionsAsyncClient = cosmosClientBuilder.buildAsyncClient();
openConnectionsAsyncClient.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block();
CosmosAsyncDatabase databaseForProactiveConnectionManagement = openConnectionsAsyncClient.getDatabase(cosmosAsyncDatabase.getId());
databaseForProactiveConnectionManagement.createContainerIfNotExists(configuration.getCollectionId(), "/id").block();
cosmosAsyncContainer = databaseForProactiveConnectionManagement.getContainer(configuration.getCollectionId());
}
if (!configuration.isProactiveConnectionManagementEnabled() && configuration.isUseUnWarmedUpContainer()) {
logger.info("Creating unwarmed container");
CosmosAsyncClient clientForUnwarmedContainer = new CosmosClientBuilder()
.endpoint(configuration.getServiceEndpoint())
.key(configuration.getMasterKey())
.preferredRegions(configuration.getPreferredRegionsList())
.directMode()
.buildAsyncClient();
clientForUnwarmedContainer.createDatabaseIfNotExists(configuration.getDatabaseId()).block();
CosmosAsyncDatabase databaseForUnwarmedContainer = clientForUnwarmedContainer.getDatabase(configuration.getDatabaseId());
databaseForUnwarmedContainer.createContainerIfNotExists(configuration.getCollectionId(), "/id").block();
cosmosAsyncContainer = databaseForUnwarmedContainer.getContainer(configuration.getCollectionId());
}
}
protected void init() {
}
void shutdown() {
if (this.databaseCreated) {
cosmosAsyncDatabase.delete().block();
logger.info("Deleted temporary database {} created for this test", this.configuration.getDatabaseId());
} else if (this.collectionCreated) {
cosmosAsyncContainer.delete().block();
logger.info("Deleted temporary collection {} created for this test", this.configuration.getCollectionId());
}
cosmosClient.close();
}
protected void onSuccess() {
}
protected void initializeMetersIfSkippedEnoughOperations(AtomicLong count) {
if (configuration.getSkipWarmUpOperations() > 0) {
if (count.get() >= configuration.getSkipWarmUpOperations()) {
if (warmupMode.get()) {
synchronized (this) {
if (warmupMode.get()) {
logger.info("Warmup phase finished. Starting capturing perf numbers ....");
resetMeters();
initializeMeter();
reporter.start(configuration.getPrintingInterval(), TimeUnit.SECONDS);
warmupMode.set(false);
}
}
}
}
}
}
protected void onError(Throwable throwable) {
}
protected abstract void performWorkload(BaseSubscriber<T> baseSubscriber, long i) throws Exception;
private void resetMeters() {
metricsRegistry.remove(SUCCESS_COUNTER_METER_NAME);
metricsRegistry.remove(FAILURE_COUNTER_METER_NAME);
if (latencyAwareOperations(configuration.getOperationType())) {
metricsRegistry.remove(LATENCY_METER_NAME);
}
}
private void initializeMeter() {
successMeter = metricsRegistry.meter(SUCCESS_COUNTER_METER_NAME);
failureMeter = metricsRegistry.meter(FAILURE_COUNTER_METER_NAME);
if (latencyAwareOperations(configuration.getOperationType())) {
latency = metricsRegistry.register(LATENCY_METER_NAME, new Timer(new HdrHistogramResetOnSnapshotReservoir()));
}
}
private boolean latencyAwareOperations(Configuration.Operation operation) {
switch (configuration.getOperationType()) {
case ReadLatency:
case WriteLatency:
case QueryInClauseParallel:
case QueryCross:
case QuerySingle:
case QuerySingleMany:
case QueryParallel:
case QueryOrderby:
case QueryAggregate:
case QueryAggregateTopOrderby:
case QueryTopOrderby:
case Mixed:
case ReadAllItemsOfLogicalPartition:
case ReadManyLatency:
return true;
default:
return false;
}
}
protected Mono sparsityMono(long i) {
Duration duration = configuration.getSparsityWaitTime();
if (duration != null && !duration.isZero()) {
if (configuration.getSkipWarmUpOperations() > i) {
return null;
}
return Mono.delay(duration);
}
else return null;
}
} |
should we constraint to only call this method when it is `IOException` or `UnhealthyChannelException`? other exceptions (like gone, 404, partition split) should not impact the connection itself | public void onException(Throwable exception) {
checkNotNull(exception, "expect non-null exception");
this.metrics.record();
if (exception instanceof IOException) {
if (exception instanceof ClosedChannelException) {
this.metrics.recordAddressUpdated(this.onConnectionEvent(RntbdConnectionEvent.READ_EOF, exception));
} else {
this.metrics.recordAddressUpdated(this.onConnectionEvent(RntbdConnectionEvent.READ_FAILURE, exception));
}
} else if (exception instanceof RntbdRequestManager.UnhealthyChannelException) {
this.metrics.recordAddressUpdated(this.onConnectionEvent(RntbdConnectionEvent.READ_FAILURE, exception));
} else {
if (logger.isDebugEnabled()) {
logger.debug("Will not raise the connection state change event for error", exception);
}
}
openConnectionIfNeeded();
} | openConnectionIfNeeded(); | public void onException(Throwable exception) {
checkNotNull(exception, "expect non-null exception");
this.metrics.record();
if (exception instanceof IOException) {
if (exception instanceof ClosedChannelException) {
this.metrics.recordAddressUpdated(this.onConnectionEvent(RntbdConnectionEvent.READ_EOF, exception));
} else {
this.metrics.recordAddressUpdated(this.onConnectionEvent(RntbdConnectionEvent.READ_FAILURE, exception));
}
} else if (exception instanceof RntbdRequestManager.UnhealthyChannelException) {
this.metrics.recordAddressUpdated(this.onConnectionEvent(RntbdConnectionEvent.READ_FAILURE, exception));
} else {
if (logger.isDebugEnabled()) {
logger.debug("Will not raise the connection state change event for error", exception);
}
}
} | class RntbdConnectionStateListener {
private static final Logger logger = LoggerFactory.getLogger(RntbdConnectionStateListener.class);
private final RntbdEndpoint endpoint;
private final RntbdConnectionStateListenerMetrics metrics;
private final Set<Uri> addressUris;
private final RntbdOpenConnectionsHandler rntbdOpenConnectionsHandler;
private final ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor;
public RntbdConnectionStateListener(final RntbdEndpoint endpoint, final RntbdOpenConnectionsHandler openConnectionsHandler, final ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor) {
this.endpoint = checkNotNull(endpoint, "expected non-null endpoint");
this.rntbdOpenConnectionsHandler = checkNotNull(openConnectionsHandler, "expected non-null openConnectionsHandler");
this.metrics = new RntbdConnectionStateListenerMetrics();
this.addressUris = ConcurrentHashMap.newKeySet();
this.proactiveOpenConnectionsProcessor = proactiveOpenConnectionsProcessor;
}
public void onBeforeSendRequest(Uri addressUri) {
checkNotNull(addressUri, "Argument 'addressUri' should not be null");
this.addressUris.add(addressUri);
}
public RntbdConnectionStateListenerMetrics getMetrics() {
return this.metrics;
}
private void openConnectionIfNeeded() {
if (this.endpoint.isClosed()) {
return;
}
this.proactiveOpenConnectionsProcessor.decrementTotalConnectionCount();
if (Configs.getMinConnectionPoolSizePerEndpoint() > 0) {
logger.warn("Channel related exception occurred, try to open the connection.");
this.proactiveOpenConnectionsProcessor.submitOpenConnectionTask(
new OpenConnectionOperation(
rntbdOpenConnectionsHandler,
"",
endpoint.serviceEndpoint(),
this.addressUris.stream().findFirst().get(),
this.endpoint.getMinChannelsRequired()
)
);
}
this.proactiveOpenConnectionsProcessor
.getOpenConnectionsPublisher()
.subscribe();
}
private int onConnectionEvent(final RntbdConnectionEvent event, final Throwable exception) {
checkNotNull(exception, "expected non-null exception");
if (event == RntbdConnectionEvent.READ_EOF || event == RntbdConnectionEvent.READ_FAILURE) {
if (logger.isDebugEnabled()) {
logger.debug("onConnectionEvent({\"event\":{},\"time\":{},\"endpoint\":{},\"cause\":{})",
event,
RntbdObjectMapper.toJson(Instant.now()),
RntbdObjectMapper.toJson(this.endpoint),
RntbdObjectMapper.toJson(exception));
}
for (Uri addressUri : this.addressUris) {
addressUri.setUnhealthy();
}
return addressUris.size();
}
return 0;
}
} | class RntbdConnectionStateListener {
private static final Logger logger = LoggerFactory.getLogger(RntbdConnectionStateListener.class);
private final RntbdEndpoint endpoint;
private final RntbdConnectionStateListenerMetrics metrics;
private final Set<Uri> addressUris;
private final ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor;
private final AtomicBoolean endpointValidationInProgress = new AtomicBoolean(false);
public RntbdConnectionStateListener(final RntbdEndpoint endpoint, final ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor) {
this.endpoint = checkNotNull(endpoint, "expected non-null endpoint");
this.metrics = new RntbdConnectionStateListenerMetrics();
this.addressUris = ConcurrentHashMap.newKeySet();
this.proactiveOpenConnectionsProcessor = proactiveOpenConnectionsProcessor;
}
public void onBeforeSendRequest(Uri addressUri) {
checkNotNull(addressUri, "Argument 'addressUri' should not be null");
this.addressUris.add(addressUri);
}
public RntbdConnectionStateListenerMetrics getMetrics() {
return this.metrics;
}
public void openConnectionIfNeeded() {
if (this.proactiveOpenConnectionsProcessor == null) {
logger.warn("proactiveOpenConnectionsProcessor is null");
return;
}
if (this.endpointValidationInProgress.compareAndSet(false, true)) {
Mono.fromFuture(this.proactiveOpenConnectionsProcessor.submitOpenConnectionTaskOutsideLoop(
"",
this.endpoint.serviceEndpoint(),
this.addressUris.stream().findFirst().get(),
this.endpoint.getMinChannelsRequired()
))
.doFinally(signalType -> {
this.endpointValidationInProgress.compareAndSet(true, false);
})
.subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC)
.subscribe();
}
}
private int onConnectionEvent(final RntbdConnectionEvent event, final Throwable exception) {
checkNotNull(exception, "expected non-null exception");
if (event == RntbdConnectionEvent.READ_EOF || event == RntbdConnectionEvent.READ_FAILURE) {
if (logger.isDebugEnabled()) {
logger.debug("onConnectionEvent({\"event\":{},\"time\":{},\"endpoint\":{},\"cause\":{})",
event,
RntbdObjectMapper.toJson(Instant.now()),
RntbdObjectMapper.toJson(this.endpoint),
RntbdObjectMapper.toJson(exception));
}
for (Uri addressUri : this.addressUris) {
addressUri.setUnhealthy();
}
return addressUris.size();
}
return 0;
}
} |
I thought we were not throwing errors in case we can't open connections? But we are catching and throwing here. | private void blockVoidFlux(Flux<Void> voidFlux) {
try {
voidFlux.blockLast();
} catch (Exception e) {
final Throwable throwable = Exceptions.unwrap(e);
if (throwable instanceof CosmosException) {
throw (CosmosException) throwable;
} else {
throw Exceptions.propagate(throwable);
}
}
} | final Throwable throwable = Exceptions.unwrap(e); | private void blockVoidFlux(Flux<Void> voidFlux) {
try {
voidFlux.blockLast();
} catch (Exception ex) {
logger.warn("The void flux did not complete successfully", ex);
}
} | class CosmosAsyncClient implements Closeable {
private static final Logger logger = LoggerFactory.getLogger(CosmosAsyncClient.class);
private static final CosmosClientTelemetryConfig DEFAULT_TELEMETRY_CONFIG = new CosmosClientTelemetryConfig();
private static final ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor queryOptionsAccessor =
ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor();
private static final ImplementationBridgeHelpers.FeedResponseHelper.FeedResponseAccessor feedResponseAccessor =
ImplementationBridgeHelpers.FeedResponseHelper.getFeedResponseAccessor();
private static final ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.CosmosClientTelemetryConfigAccessor
telemetryConfigAccessor = ImplementationBridgeHelpers
.CosmosClientTelemetryConfigHelper
.getCosmosClientTelemetryConfigAccessor();
private final AsyncDocumentClient asyncDocumentClient;
private final String serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel desiredConsistencyLevel;
private final AzureKeyCredential credential;
private final CosmosClientTelemetryConfig clientTelemetryConfig;
private final DiagnosticsProvider diagnosticsProvider;
private final Tag clientCorrelationTag;
private final String accountTagValue;
private final boolean clientMetricsEnabled;
private final boolean isSendClientTelemetryToServiceEnabled;
private final MeterRegistry clientMetricRegistrySnapshot;
private final CosmosContainerProactiveInitConfig proactiveContainerInitConfig;
private static final ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor containerIdentityAccessor =
ImplementationBridgeHelpers.CosmosContainerIdentityHelper.getCosmosContainerIdentityAccessor();
private final ConsistencyLevel accountConsistencyLevel;
private final WriteRetryPolicy nonIdempotentWriteRetryPolicy;
CosmosAsyncClient(CosmosClientBuilder builder) {
Configs configs = builder.configs();
this.serviceEndpoint = builder.getEndpoint();
String keyOrResourceToken = builder.getKey();
this.connectionPolicy = builder.getConnectionPolicy();
this.desiredConsistencyLevel = builder.getConsistencyLevel();
List<CosmosPermissionProperties> permissions = builder.getPermissions();
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver = builder.getAuthorizationTokenResolver();
this.credential = builder.getCredential();
TokenCredential tokenCredential = builder.getTokenCredential();
boolean sessionCapturingOverride = builder.isSessionCapturingOverrideEnabled();
boolean enableTransportClientSharing = builder.isConnectionSharingAcrossClientsEnabled();
this.proactiveContainerInitConfig = builder.getProactiveContainerInitConfig();
this.nonIdempotentWriteRetryPolicy = builder.getNonIdempotentWriteRetryPolicy();
CosmosClientTelemetryConfig effectiveTelemetryConfig = telemetryConfigAccessor
.createSnapshot(
builder.getClientTelemetryConfig(),
builder.isClientTelemetryEnabled());
this.clientTelemetryConfig = effectiveTelemetryConfig;
this.isSendClientTelemetryToServiceEnabled = telemetryConfigAccessor
.isSendClientTelemetryToServiceEnabled(effectiveTelemetryConfig);
boolean contentResponseOnWriteEnabled = builder.isContentResponseOnWriteEnabled();
ApiType apiType = builder.apiType();
String clientCorrelationId = telemetryConfigAccessor
.getClientCorrelationId(effectiveTelemetryConfig);
List<Permission> permissionList = new ArrayList<>();
if (permissions != null) {
permissionList =
permissions
.stream()
.map(ModelBridgeInternal::getPermission)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
this.asyncDocumentClient = new AsyncDocumentClient.Builder()
.withServiceEndpoint(this.serviceEndpoint)
.withMasterKeyOrResourceToken(keyOrResourceToken)
.withConnectionPolicy(this.connectionPolicy)
.withConsistencyLevel(this.desiredConsistencyLevel)
.withSessionCapturingOverride(sessionCapturingOverride)
.withConfigs(configs)
.withTokenResolver(cosmosAuthorizationTokenResolver)
.withCredential(this.credential)
.withTransportClientSharing(enableTransportClientSharing)
.withContentResponseOnWriteEnabled(contentResponseOnWriteEnabled)
.withTokenCredential(tokenCredential)
.withState(builder.metadataCaches())
.withPermissionFeed(permissionList)
.withApiType(apiType)
.withClientTelemetryConfig(this.clientTelemetryConfig)
.withClientCorrelationId(clientCorrelationId)
.withAggressiveProactiveConnectionDuration(this.proactiveContainerInitConfig != null ? this.proactiveContainerInitConfig.getAggressiveProactiveConnectionEstablishmentDuration() : null)
.build();
this.accountConsistencyLevel = this.asyncDocumentClient.getDefaultConsistencyLevelOfAccount();
String effectiveClientCorrelationId = this.asyncDocumentClient.getClientCorrelationId();
String machineId = this.asyncDocumentClient.getMachineId();
if (!Strings.isNullOrWhiteSpace(machineId) && machineId.startsWith(ClientTelemetry.VM_ID_PREFIX)) {
machineId = machineId.replace(ClientTelemetry.VM_ID_PREFIX, "vmId_");
if (Strings.isNullOrWhiteSpace(effectiveClientCorrelationId)) {
effectiveClientCorrelationId = machineId;
} else {
effectiveClientCorrelationId = String.format(
"%s_%s",
machineId,
effectiveClientCorrelationId);
}
}
this.clientCorrelationTag = Tag.of(
TagName.ClientCorrelationId.toString(),
ClientTelemetryMetrics.escape(effectiveClientCorrelationId));
this.clientMetricRegistrySnapshot = telemetryConfigAccessor
.getClientMetricRegistry(effectiveTelemetryConfig);
this.clientMetricsEnabled = clientMetricRegistrySnapshot != null;
CosmosMeterOptions cpuMeterOptions = telemetryConfigAccessor
.getMeterOptions(effectiveTelemetryConfig, CosmosMetricName.SYSTEM_CPU);
CosmosMeterOptions memoryMeterOptions = telemetryConfigAccessor
.getMeterOptions(effectiveTelemetryConfig, CosmosMetricName.SYSTEM_MEMORY_FREE);
if (clientMetricRegistrySnapshot != null) {
ClientTelemetryMetrics.add(clientMetricRegistrySnapshot, cpuMeterOptions, memoryMeterOptions);
}
this.accountTagValue = URI.create(this.serviceEndpoint).getHost().replace(
".documents.azure.com", ""
);
if (this.clientMetricsEnabled) {
telemetryConfigAccessor.setClientCorrelationTag(
effectiveTelemetryConfig,
this.clientCorrelationTag );
telemetryConfigAccessor.setAccountName(
effectiveTelemetryConfig,
this.accountTagValue
);
telemetryConfigAccessor.addDiagnosticsHandler(
effectiveTelemetryConfig,
new ClientMetricsDiagnosticsHandler(this)
);
}
if (this.isSendClientTelemetryToServiceEnabled) {
telemetryConfigAccessor.setClientTelemetry(
effectiveTelemetryConfig,
asyncDocumentClient.getClientTelemetry()
);
telemetryConfigAccessor.addDiagnosticsHandler(
effectiveTelemetryConfig,
new ClientTelemetryDiagnosticsHandler(effectiveTelemetryConfig)
);
}
this.diagnosticsProvider = new DiagnosticsProvider(
effectiveTelemetryConfig,
effectiveClientCorrelationId,
this.getUserAgent(),
this.connectionPolicy.getConnectionMode());
}
AsyncDocumentClient getContextClient() {
return this.asyncDocumentClient;
}
/**
* Monitor Cosmos client performance and resource utilization using the specified meter registry.
*
* @param registry meter registry to use for performance monitoring.
*/
static void setMonitorTelemetry(MeterRegistry registry) {
RntbdMetrics.add(registry);
}
/**
* Get the service endpoint.
*
* @return the service endpoint.
*/
String getServiceEndpoint() {
return serviceEndpoint;
}
/**
* Get the connection policy.
*
* @return {@link ConnectionPolicy}.
*/
ConnectionPolicy getConnectionPolicy() {
return connectionPolicy;
}
AsyncDocumentClient getDocClientWrapper() {
return asyncDocumentClient;
}
/**
* Gets the azure key credential.
*
* @return azure key credential.
*/
AzureKeyCredential credential() {
return credential;
}
/***
* Get the client telemetry config.
*
* @return the {@link CosmosClientTelemetryConfig}.
*/
CosmosClientTelemetryConfig getClientTelemetryConfig() {
return this.clientTelemetryConfig;
}
/**
* CREATE a Database if it does not already exist on the service.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param databaseProperties CosmosDatabaseProperties.
* @return a {@link Mono} containing the cosmos database response with the created or existing database or
* an error.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(CosmosDatabaseProperties databaseProperties) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(databaseProperties.getId()),
null, context));
}
/**
* Create a Database if it does not already exist on the service.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param id the id of the database.
* @return a {@link Mono} containing the cosmos database response with the created or existing database or
* an error.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id), null, context));
}
/**
* Create a Database if it does not already exist on the service.
* <br/>
* The throughputProperties will only be used if the specified database
* does not exist and therefor a new database will be created with throughputProperties.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param id the id.
* @param throughputProperties the throughputProperties.
* @return the mono.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id, ThroughputProperties throughputProperties) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id),
throughputProperties, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param options {@link CosmosDatabaseRequestOptions}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties,
CosmosDatabaseRequestOptions options) {
final CosmosDatabaseRequestOptions requestOptions = options == null ? new CosmosDatabaseRequestOptions() : options;
Database wrappedDatabase = new Database();
wrappedDatabase.setId(databaseProperties.getId());
return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties) {
return createDatabase(databaseProperties, new CosmosDatabaseRequestOptions());
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param id id of the database.
* @return a {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(String id) {
return createDatabase(new CosmosDatabaseProperties(id), new CosmosDatabaseRequestOptions());
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param throughputProperties the throughput properties for the database.
* @param options {@link CosmosDatabaseRequestOptions}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties,
ThroughputProperties throughputProperties,
CosmosDatabaseRequestOptions options) {
if (options == null) {
options = new CosmosDatabaseRequestOptions();
}
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
Database wrappedDatabase = new Database();
wrappedDatabase.setId(databaseProperties.getId());
final CosmosDatabaseRequestOptions requestOptions = options;
return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param throughputProperties the throughput properties for the database.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties, ThroughputProperties throughputProperties) {
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
return createDatabase(databaseProperties, options);
}
/**
* Creates a database.
*
* @param id the id.
* @param throughputProperties the throughputProperties.
* @return the mono.
*/
public Mono<CosmosDatabaseResponse> createDatabase(String id, ThroughputProperties throughputProperties) {
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
return createDatabase(new CosmosDatabaseProperties(id), options);
}
/**
* Reads all databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param options {@link CosmosQueryRequestOptions}
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases(CosmosQueryRequestOptions options) {
return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> {
String spanName = "readAllDatabases";
CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions();
String operationId = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getQueryNameOrDefault(nonNullOptions, spanName);
pagedFluxOptions.setTracerInformation(
spanName,
null,
null,
operationId,
OperationType.ReadFeed,
ResourceType.Database,
this,
nonNullOptions.getConsistencyLevel(),
this.getEffectiveDiagnosticsThresholds(queryOptionsAccessor.getDiagnosticsThresholds(nonNullOptions)));
setContinuationTokenAndMaxItemCount(pagedFluxOptions, options);
return getDocClientWrapper().readDatabases(options)
.map(response ->
feedResponseAccessor.createFeedResponse(
ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()),
response.getResponseHeaders(),
response.getCosmosDiagnostics()));
});
}
/**
* Reads all databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases() {
return readAllDatabases(new CosmosQueryRequestOptions());
}
/**
* Query for databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param query the query.
* @param options the feed options.
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(String query, CosmosQueryRequestOptions options) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
return queryDatabasesInternal(new SqlQuerySpec(query), options);
}
/**
* Query for databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param querySpec the SQL query specification.
* @param options the feed options.
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
return queryDatabasesInternal(querySpec, options);
}
/**
* Gets a database object without making a service call.
*
* @param id name of the database.
* @return {@link CosmosAsyncDatabase}.
*/
public CosmosAsyncDatabase getDatabase(String id) {
return new CosmosAsyncDatabase(id, this);
}
/**
* Close this {@link CosmosAsyncClient} instance and cleans up the resources.
*/
@Override
public void close() {
if (this.clientMetricRegistrySnapshot != null) {
ClientTelemetryMetrics.remove(this.clientMetricRegistrySnapshot);
}
asyncDocumentClient.close();
}
DiagnosticsProvider getDiagnosticsProvider() {
return this.diagnosticsProvider;
}
/**
* Enable throughput control group.
*
* @param group Throughput control group going to be enabled.
* @param throughputQueryMono The throughput query mono.
*/
void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) {
checkNotNull(group, "Throughput control group cannot be null");
this.asyncDocumentClient.enableThroughputControlGroup(group, throughputQueryMono);
}
/***
* Configure fault injector provider.
*
* @param injectorProvider the injector provider.
*/
void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) {
checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null");
this.asyncDocumentClient.configureFaultInjectorProvider(injectorProvider);
}
/**
* Create global throughput control config builder which will be used to build {@link GlobalThroughputControlConfig}.
*
* @param databaseId The database id of the control container.
* @param containerId The container id of the control container.
* @return A {@link GlobalThroughputControlConfigBuilder}.
*/
public GlobalThroughputControlConfigBuilder createGlobalThroughputControlConfigBuilder(String databaseId, String containerId) {
return new GlobalThroughputControlConfigBuilder(this, databaseId, containerId);
}
WriteRetryPolicy getNonIdempotentWriteRetryPolicy() {
return this.nonIdempotentWriteRetryPolicy;
}
void openConnectionsAndInitCaches() {
blockVoidFlux(asyncDocumentClient.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig));
}
void openConnectionsAndInitCaches(Duration aggressiveProactiveConnectionEstablishmentDuration) {
Flux<Void> submitOpenConnectionTasksFlux = asyncDocumentClient.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig);
wrapSourceFluxAndSoftCompleteAfterTimeout(
submitOpenConnectionTasksFlux,
aggressiveProactiveConnectionEstablishmentDuration,
CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC)
.blockLast();
}
private <T> Flux<T> wrapSourceFluxAndSoftCompleteAfterTimeout(Flux<T> source, Duration timeout, Scheduler executionContext) {
return Flux.<T>create(sink -> {
source
.subscribeOn(executionContext)
.subscribe(t -> sink.next(t));
})
.take(timeout);
}
private CosmosPagedFlux<CosmosDatabaseProperties> queryDatabasesInternal(
SqlQuerySpec querySpec,
CosmosQueryRequestOptions options){
return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> {
String spanName = "queryDatabases";
CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions();
String operationId = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getQueryNameOrDefault(nonNullOptions, spanName);
pagedFluxOptions.setTracerInformation(
spanName,
null,
null,
operationId,
OperationType.Query,
ResourceType.Database,
this,
nonNullOptions.getConsistencyLevel(),
this.getEffectiveDiagnosticsThresholds(queryOptionsAccessor.getDiagnosticsThresholds(nonNullOptions)));
setContinuationTokenAndMaxItemCount(pagedFluxOptions, options);
return getDocClientWrapper().queryDatabases(querySpec, options)
.map(response -> feedResponseAccessor.createFeedResponse(
ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()),
response.getResponseHeaders(),
response.getCosmosDiagnostics()));
});
}
private Mono<CosmosDatabaseResponse> createDatabaseIfNotExistsInternal(CosmosAsyncDatabase database,
ThroughputProperties throughputProperties, Context context) {
String spanName = "createDatabaseIfNotExists." + database.getId();
Context nestedContext = context.addData(
DiagnosticsProvider.COSMOS_CALL_DEPTH,
DiagnosticsProvider.COSMOS_CALL_DEPTH_VAL);
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
Mono<CosmosDatabaseResponse> responseMono = database.readInternal(new CosmosDatabaseRequestOptions(),
nestedContext).onErrorResume(exception -> {
final Throwable unwrappedException = Exceptions.unwrap(exception);
if (unwrappedException instanceof CosmosException) {
final CosmosException cosmosException = (CosmosException) unwrappedException;
if (cosmosException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
if (throughputProperties != null) {
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
}
Database wrappedDatabase = new Database();
wrappedDatabase.setId(database.getId());
return createDatabaseInternal(wrappedDatabase,
options, nestedContext);
}
}
return Mono.error(unwrappedException);
});
RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options);
return this.diagnosticsProvider.traceEnabledCosmosResponsePublisher(
responseMono,
context,
spanName,
database.getId(),
null,
this,
null,
OperationType.Create,
ResourceType.Database,
this.getEffectiveDiagnosticsThresholds(requestOptions.getDiagnosticsThresholds()));
}
private Mono<CosmosDatabaseResponse> createDatabaseInternal(Database database, CosmosDatabaseRequestOptions options,
Context context) {
String spanName = "createDatabase." + database.getId();
RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options);
Mono<CosmosDatabaseResponse> responseMono = asyncDocumentClient.createDatabase(database, requestOptions)
.map(ModelBridgeInternal::createCosmosDatabaseResponse)
.single();
return this.diagnosticsProvider
.traceEnabledCosmosResponsePublisher(
responseMono,
context,
spanName,
database.getId(),
null,
this,
null,
OperationType.Create,
ResourceType.Database,
this.getEffectiveDiagnosticsThresholds(requestOptions.getDiagnosticsThresholds()));
}
private ConsistencyLevel getEffectiveConsistencyLevel(
OperationType operationType,
ConsistencyLevel desiredConsistencyLevelOfOperation) {
if (operationType.isWriteOperation()) {
return this.accountConsistencyLevel;
}
if (desiredConsistencyLevelOfOperation != null) {
return desiredConsistencyLevelOfOperation;
}
if (this.desiredConsistencyLevel != null) {
return desiredConsistencyLevel;
}
return this.accountConsistencyLevel;
}
CosmosDiagnosticsThresholds getEffectiveDiagnosticsThresholds(
CosmosDiagnosticsThresholds operationLevelThresholds) {
if (operationLevelThresholds != null) {
return operationLevelThresholds;
}
if (this.clientTelemetryConfig == null) {
return new CosmosDiagnosticsThresholds();
}
CosmosDiagnosticsThresholds clientLevelThresholds =
telemetryConfigAccessor.getDiagnosticsThresholds(this.clientTelemetryConfig);
return clientLevelThresholds != null ? clientLevelThresholds : new CosmosDiagnosticsThresholds();
}
boolean isTransportLevelTracingEnabled() {
CosmosClientTelemetryConfig effectiveConfig = this.clientTelemetryConfig != null ?
this.clientTelemetryConfig
: DEFAULT_TELEMETRY_CONFIG;
if (telemetryConfigAccessor.isLegacyTracingEnabled(effectiveConfig)) {
return false;
}
if (this.getConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) {
return false;
}
return telemetryConfigAccessor.isTransportLevelTracingEnabled(effectiveConfig);
}
String getAccountTagValue() {
return this.accountTagValue;
}
Tag getClientCorrelationTag() {
return this.clientCorrelationTag;
}
String getUserAgent() {
return this.asyncDocumentClient.getUserAgent();
}
static void initialize() {
ImplementationBridgeHelpers.CosmosAsyncClientHelper.setCosmosAsyncClientAccessor(
new ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor() {
@Override
public Tag getClientCorrelationTag(CosmosAsyncClient client) {
return client.getClientCorrelationTag();
}
@Override
public String getAccountTagValue(CosmosAsyncClient client) {
return client.getAccountTagValue();
}
@Override
public EnumSet<TagName> getMetricTagNames(CosmosAsyncClient client) {
return telemetryConfigAccessor
.getMetricTagNames(client.clientTelemetryConfig);
}
@Override
public EnumSet<MetricCategory> getMetricCategories(CosmosAsyncClient client) {
return telemetryConfigAccessor
.getMetricCategories(client.clientTelemetryConfig);
}
@Override
public boolean shouldEnableEmptyPageDiagnostics(CosmosAsyncClient client) {
return client.clientMetricsEnabled || client.isTransportLevelTracingEnabled();
}
@Override
public boolean isSendClientTelemetryToServiceEnabled(CosmosAsyncClient client) {
return client.isSendClientTelemetryToServiceEnabled;
}
@Override
public List<String> getPreferredRegions(CosmosAsyncClient client) {
return client.connectionPolicy.getPreferredRegions();
}
@Override
public boolean isEndpointDiscoveryEnabled(CosmosAsyncClient client) {
return client.connectionPolicy.isEndpointDiscoveryEnabled();
}
@Override
public CosmosMeterOptions getMeterOptions(CosmosAsyncClient client, CosmosMetricName name) {
return telemetryConfigAccessor
.getMeterOptions(client.clientTelemetryConfig, name);
}
@Override
public boolean isEffectiveContentResponseOnWriteEnabled(CosmosAsyncClient client,
Boolean requestOptionsContentResponseEnabled) {
if (requestOptionsContentResponseEnabled != null) {
return requestOptionsContentResponseEnabled;
}
return client.asyncDocumentClient.isContentResponseOnWriteEnabled();
}
@Override
public ConsistencyLevel getEffectiveConsistencyLevel(
CosmosAsyncClient client,
OperationType operationType,
ConsistencyLevel desiredConsistencyLevelOfOperation) {
return client.getEffectiveConsistencyLevel(operationType, desiredConsistencyLevelOfOperation);
}
@Override
public CosmosDiagnosticsThresholds getEffectiveDiagnosticsThresholds(
CosmosAsyncClient client,
CosmosDiagnosticsThresholds operationLevelThresholds) {
return client.getEffectiveDiagnosticsThresholds(operationLevelThresholds);
}
@Override
public DiagnosticsProvider getDiagnosticsProvider(CosmosAsyncClient client) {
return client.getDiagnosticsProvider();
}
}
);
}
static { initialize(); }
} | class CosmosAsyncClient implements Closeable {
private static final Logger logger = LoggerFactory.getLogger(CosmosAsyncClient.class);
private static final CosmosClientTelemetryConfig DEFAULT_TELEMETRY_CONFIG = new CosmosClientTelemetryConfig();
private static final ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor queryOptionsAccessor =
ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor();
private static final ImplementationBridgeHelpers.FeedResponseHelper.FeedResponseAccessor feedResponseAccessor =
ImplementationBridgeHelpers.FeedResponseHelper.getFeedResponseAccessor();
private static final ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.CosmosClientTelemetryConfigAccessor
telemetryConfigAccessor = ImplementationBridgeHelpers
.CosmosClientTelemetryConfigHelper
.getCosmosClientTelemetryConfigAccessor();
private final AsyncDocumentClient asyncDocumentClient;
private final String serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel desiredConsistencyLevel;
private final AzureKeyCredential credential;
private final CosmosClientTelemetryConfig clientTelemetryConfig;
private final DiagnosticsProvider diagnosticsProvider;
private final Tag clientCorrelationTag;
private final String accountTagValue;
private final boolean clientMetricsEnabled;
private final boolean isSendClientTelemetryToServiceEnabled;
private final MeterRegistry clientMetricRegistrySnapshot;
private final CosmosContainerProactiveInitConfig proactiveContainerInitConfig;
private static final ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor containerIdentityAccessor =
ImplementationBridgeHelpers.CosmosContainerIdentityHelper.getCosmosContainerIdentityAccessor();
private final ConsistencyLevel accountConsistencyLevel;
private final WriteRetryPolicy nonIdempotentWriteRetryPolicy;
CosmosAsyncClient(CosmosClientBuilder builder) {
Configs configs = builder.configs();
this.serviceEndpoint = builder.getEndpoint();
String keyOrResourceToken = builder.getKey();
this.connectionPolicy = builder.getConnectionPolicy();
this.desiredConsistencyLevel = builder.getConsistencyLevel();
List<CosmosPermissionProperties> permissions = builder.getPermissions();
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver = builder.getAuthorizationTokenResolver();
this.credential = builder.getCredential();
TokenCredential tokenCredential = builder.getTokenCredential();
boolean sessionCapturingOverride = builder.isSessionCapturingOverrideEnabled();
boolean enableTransportClientSharing = builder.isConnectionSharingAcrossClientsEnabled();
this.proactiveContainerInitConfig = builder.getProactiveContainerInitConfig();
this.nonIdempotentWriteRetryPolicy = builder.getNonIdempotentWriteRetryPolicy();
CosmosClientTelemetryConfig effectiveTelemetryConfig = telemetryConfigAccessor
.createSnapshot(
builder.getClientTelemetryConfig(),
builder.isClientTelemetryEnabled());
this.clientTelemetryConfig = effectiveTelemetryConfig;
this.isSendClientTelemetryToServiceEnabled = telemetryConfigAccessor
.isSendClientTelemetryToServiceEnabled(effectiveTelemetryConfig);
boolean contentResponseOnWriteEnabled = builder.isContentResponseOnWriteEnabled();
ApiType apiType = builder.apiType();
String clientCorrelationId = telemetryConfigAccessor
.getClientCorrelationId(effectiveTelemetryConfig);
List<Permission> permissionList = new ArrayList<>();
if (permissions != null) {
permissionList =
permissions
.stream()
.map(ModelBridgeInternal::getPermission)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
this.asyncDocumentClient = new AsyncDocumentClient.Builder()
.withServiceEndpoint(this.serviceEndpoint)
.withMasterKeyOrResourceToken(keyOrResourceToken)
.withConnectionPolicy(this.connectionPolicy)
.withConsistencyLevel(this.desiredConsistencyLevel)
.withSessionCapturingOverride(sessionCapturingOverride)
.withConfigs(configs)
.withTokenResolver(cosmosAuthorizationTokenResolver)
.withCredential(this.credential)
.withTransportClientSharing(enableTransportClientSharing)
.withContentResponseOnWriteEnabled(contentResponseOnWriteEnabled)
.withTokenCredential(tokenCredential)
.withState(builder.metadataCaches())
.withPermissionFeed(permissionList)
.withApiType(apiType)
.withClientTelemetryConfig(this.clientTelemetryConfig)
.withClientCorrelationId(clientCorrelationId)
.build();
this.accountConsistencyLevel = this.asyncDocumentClient.getDefaultConsistencyLevelOfAccount();
String effectiveClientCorrelationId = this.asyncDocumentClient.getClientCorrelationId();
String machineId = this.asyncDocumentClient.getMachineId();
if (!Strings.isNullOrWhiteSpace(machineId) && machineId.startsWith(ClientTelemetry.VM_ID_PREFIX)) {
machineId = machineId.replace(ClientTelemetry.VM_ID_PREFIX, "vmId_");
if (Strings.isNullOrWhiteSpace(effectiveClientCorrelationId)) {
effectiveClientCorrelationId = machineId;
} else {
effectiveClientCorrelationId = String.format(
"%s_%s",
machineId,
effectiveClientCorrelationId);
}
}
this.clientCorrelationTag = Tag.of(
TagName.ClientCorrelationId.toString(),
ClientTelemetryMetrics.escape(effectiveClientCorrelationId));
this.clientMetricRegistrySnapshot = telemetryConfigAccessor
.getClientMetricRegistry(effectiveTelemetryConfig);
this.clientMetricsEnabled = clientMetricRegistrySnapshot != null;
CosmosMeterOptions cpuMeterOptions = telemetryConfigAccessor
.getMeterOptions(effectiveTelemetryConfig, CosmosMetricName.SYSTEM_CPU);
CosmosMeterOptions memoryMeterOptions = telemetryConfigAccessor
.getMeterOptions(effectiveTelemetryConfig, CosmosMetricName.SYSTEM_MEMORY_FREE);
if (clientMetricRegistrySnapshot != null) {
ClientTelemetryMetrics.add(clientMetricRegistrySnapshot, cpuMeterOptions, memoryMeterOptions);
}
this.accountTagValue = URI.create(this.serviceEndpoint).getHost().replace(
".documents.azure.com", ""
);
if (this.clientMetricsEnabled) {
telemetryConfigAccessor.setClientCorrelationTag(
effectiveTelemetryConfig,
this.clientCorrelationTag );
telemetryConfigAccessor.setAccountName(
effectiveTelemetryConfig,
this.accountTagValue
);
telemetryConfigAccessor.addDiagnosticsHandler(
effectiveTelemetryConfig,
new ClientMetricsDiagnosticsHandler(this)
);
}
if (this.isSendClientTelemetryToServiceEnabled) {
telemetryConfigAccessor.setClientTelemetry(
effectiveTelemetryConfig,
asyncDocumentClient.getClientTelemetry()
);
telemetryConfigAccessor.addDiagnosticsHandler(
effectiveTelemetryConfig,
new ClientTelemetryDiagnosticsHandler(effectiveTelemetryConfig)
);
}
this.diagnosticsProvider = new DiagnosticsProvider(
effectiveTelemetryConfig,
effectiveClientCorrelationId,
this.getUserAgent(),
this.connectionPolicy.getConnectionMode());
}
AsyncDocumentClient getContextClient() {
return this.asyncDocumentClient;
}
/**
* Monitor Cosmos client performance and resource utilization using the specified meter registry.
*
* @param registry meter registry to use for performance monitoring.
*/
static void setMonitorTelemetry(MeterRegistry registry) {
RntbdMetrics.add(registry);
}
/**
* Get the service endpoint.
*
* @return the service endpoint.
*/
String getServiceEndpoint() {
return serviceEndpoint;
}
/**
* Get the connection policy.
*
* @return {@link ConnectionPolicy}.
*/
ConnectionPolicy getConnectionPolicy() {
return connectionPolicy;
}
AsyncDocumentClient getDocClientWrapper() {
return asyncDocumentClient;
}
/**
* Gets the azure key credential.
*
* @return azure key credential.
*/
AzureKeyCredential credential() {
return credential;
}
/***
* Get the client telemetry config.
*
* @return the {@link CosmosClientTelemetryConfig}.
*/
CosmosClientTelemetryConfig getClientTelemetryConfig() {
return this.clientTelemetryConfig;
}
/**
* CREATE a Database if it does not already exist on the service.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param databaseProperties CosmosDatabaseProperties.
* @return a {@link Mono} containing the cosmos database response with the created or existing database or
* an error.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(CosmosDatabaseProperties databaseProperties) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(databaseProperties.getId()),
null, context));
}
/**
* Create a Database if it does not already exist on the service.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param id the id of the database.
* @return a {@link Mono} containing the cosmos database response with the created or existing database or
* an error.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id), null, context));
}
/**
* Create a Database if it does not already exist on the service.
* <br/>
* The throughputProperties will only be used if the specified database
* does not exist and therefor a new database will be created with throughputProperties.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param id the id.
* @param throughputProperties the throughputProperties.
* @return the mono.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id, ThroughputProperties throughputProperties) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id),
throughputProperties, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param options {@link CosmosDatabaseRequestOptions}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties,
CosmosDatabaseRequestOptions options) {
final CosmosDatabaseRequestOptions requestOptions = options == null ? new CosmosDatabaseRequestOptions() : options;
Database wrappedDatabase = new Database();
wrappedDatabase.setId(databaseProperties.getId());
return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties) {
return createDatabase(databaseProperties, new CosmosDatabaseRequestOptions());
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param id id of the database.
* @return a {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(String id) {
return createDatabase(new CosmosDatabaseProperties(id), new CosmosDatabaseRequestOptions());
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param throughputProperties the throughput properties for the database.
* @param options {@link CosmosDatabaseRequestOptions}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties,
ThroughputProperties throughputProperties,
CosmosDatabaseRequestOptions options) {
if (options == null) {
options = new CosmosDatabaseRequestOptions();
}
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
Database wrappedDatabase = new Database();
wrappedDatabase.setId(databaseProperties.getId());
final CosmosDatabaseRequestOptions requestOptions = options;
return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param throughputProperties the throughput properties for the database.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties, ThroughputProperties throughputProperties) {
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
return createDatabase(databaseProperties, options);
}
/**
* Creates a database.
*
* @param id the id.
* @param throughputProperties the throughputProperties.
* @return the mono.
*/
public Mono<CosmosDatabaseResponse> createDatabase(String id, ThroughputProperties throughputProperties) {
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
return createDatabase(new CosmosDatabaseProperties(id), options);
}
/**
* Reads all databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param options {@link CosmosQueryRequestOptions}
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases(CosmosQueryRequestOptions options) {
return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> {
String spanName = "readAllDatabases";
CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions();
String operationId = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getQueryNameOrDefault(nonNullOptions, spanName);
pagedFluxOptions.setTracerInformation(
spanName,
null,
null,
operationId,
OperationType.ReadFeed,
ResourceType.Database,
this,
nonNullOptions.getConsistencyLevel(),
this.getEffectiveDiagnosticsThresholds(queryOptionsAccessor.getDiagnosticsThresholds(nonNullOptions)));
setContinuationTokenAndMaxItemCount(pagedFluxOptions, options);
return getDocClientWrapper().readDatabases(options)
.map(response ->
feedResponseAccessor.createFeedResponse(
ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()),
response.getResponseHeaders(),
response.getCosmosDiagnostics()));
});
}
/**
* Reads all databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases() {
return readAllDatabases(new CosmosQueryRequestOptions());
}
/**
* Query for databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param query the query.
* @param options the feed options.
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(String query, CosmosQueryRequestOptions options) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
return queryDatabasesInternal(new SqlQuerySpec(query), options);
}
/**
* Query for databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param querySpec the SQL query specification.
* @param options the feed options.
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
return queryDatabasesInternal(querySpec, options);
}
/**
* Gets a database object without making a service call.
*
* @param id name of the database.
* @return {@link CosmosAsyncDatabase}.
*/
public CosmosAsyncDatabase getDatabase(String id) {
return new CosmosAsyncDatabase(id, this);
}
/**
* Close this {@link CosmosAsyncClient} instance and cleans up the resources.
*/
@Override
public void close() {
if (this.clientMetricRegistrySnapshot != null) {
ClientTelemetryMetrics.remove(this.clientMetricRegistrySnapshot);
}
asyncDocumentClient.close();
}
DiagnosticsProvider getDiagnosticsProvider() {
return this.diagnosticsProvider;
}
/**
* Enable throughput control group.
*
* @param group Throughput control group going to be enabled.
* @param throughputQueryMono The throughput query mono.
*/
void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) {
checkNotNull(group, "Throughput control group cannot be null");
this.asyncDocumentClient.enableThroughputControlGroup(group, throughputQueryMono);
}
/***
* Configure fault injector provider.
*
* @param injectorProvider the injector provider.
*/
void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) {
checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null");
this.asyncDocumentClient.configureFaultInjectorProvider(injectorProvider);
}
/**
* Create global throughput control config builder which will be used to build {@link GlobalThroughputControlConfig}.
*
* @param databaseId The database id of the control container.
* @param containerId The container id of the control container.
* @return A {@link GlobalThroughputControlConfigBuilder}.
*/
public GlobalThroughputControlConfigBuilder createGlobalThroughputControlConfigBuilder(String databaseId, String containerId) {
return new GlobalThroughputControlConfigBuilder(this, databaseId, containerId);
}
WriteRetryPolicy getNonIdempotentWriteRetryPolicy() {
return this.nonIdempotentWriteRetryPolicy;
}
void openConnectionsAndInitCaches() {
blockVoidFlux(asyncDocumentClient.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig));
}
void openConnectionsAndInitCaches(Duration aggressiveWarmupDuration) {
Flux<Void> submitOpenConnectionTasksFlux = asyncDocumentClient.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig);
blockVoidFlux(wrapSourceFluxAndSoftCompleteAfterTimeout(submitOpenConnectionTasksFlux, aggressiveWarmupDuration));
}
private Flux<Void> wrapSourceFluxAndSoftCompleteAfterTimeout(Flux<Void> source, Duration timeout) {
return Flux.<Void>create(sink -> {
source.subscribe(t -> sink.next(t));
})
.take(timeout);
}
private CosmosPagedFlux<CosmosDatabaseProperties> queryDatabasesInternal(
SqlQuerySpec querySpec,
CosmosQueryRequestOptions options){
return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> {
String spanName = "queryDatabases";
CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions();
String operationId = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getQueryNameOrDefault(nonNullOptions, spanName);
pagedFluxOptions.setTracerInformation(
spanName,
null,
null,
operationId,
OperationType.Query,
ResourceType.Database,
this,
nonNullOptions.getConsistencyLevel(),
this.getEffectiveDiagnosticsThresholds(queryOptionsAccessor.getDiagnosticsThresholds(nonNullOptions)));
setContinuationTokenAndMaxItemCount(pagedFluxOptions, options);
return getDocClientWrapper().queryDatabases(querySpec, options)
.map(response -> feedResponseAccessor.createFeedResponse(
ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()),
response.getResponseHeaders(),
response.getCosmosDiagnostics()));
});
}
private Mono<CosmosDatabaseResponse> createDatabaseIfNotExistsInternal(CosmosAsyncDatabase database,
ThroughputProperties throughputProperties, Context context) {
String spanName = "createDatabaseIfNotExists." + database.getId();
Context nestedContext = context.addData(
DiagnosticsProvider.COSMOS_CALL_DEPTH,
DiagnosticsProvider.COSMOS_CALL_DEPTH_VAL);
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
Mono<CosmosDatabaseResponse> responseMono = database.readInternal(new CosmosDatabaseRequestOptions(),
nestedContext).onErrorResume(exception -> {
final Throwable unwrappedException = Exceptions.unwrap(exception);
if (unwrappedException instanceof CosmosException) {
final CosmosException cosmosException = (CosmosException) unwrappedException;
if (cosmosException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
if (throughputProperties != null) {
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
}
Database wrappedDatabase = new Database();
wrappedDatabase.setId(database.getId());
return createDatabaseInternal(wrappedDatabase,
options, nestedContext);
}
}
return Mono.error(unwrappedException);
});
RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options);
return this.diagnosticsProvider.traceEnabledCosmosResponsePublisher(
responseMono,
context,
spanName,
database.getId(),
null,
this,
null,
OperationType.Create,
ResourceType.Database,
this.getEffectiveDiagnosticsThresholds(requestOptions.getDiagnosticsThresholds()));
}
private Mono<CosmosDatabaseResponse> createDatabaseInternal(Database database, CosmosDatabaseRequestOptions options,
Context context) {
String spanName = "createDatabase." + database.getId();
RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options);
Mono<CosmosDatabaseResponse> responseMono = asyncDocumentClient.createDatabase(database, requestOptions)
.map(ModelBridgeInternal::createCosmosDatabaseResponse)
.single();
return this.diagnosticsProvider
.traceEnabledCosmosResponsePublisher(
responseMono,
context,
spanName,
database.getId(),
null,
this,
null,
OperationType.Create,
ResourceType.Database,
this.getEffectiveDiagnosticsThresholds(requestOptions.getDiagnosticsThresholds()));
}
private ConsistencyLevel getEffectiveConsistencyLevel(
OperationType operationType,
ConsistencyLevel desiredConsistencyLevelOfOperation) {
if (operationType.isWriteOperation()) {
return this.accountConsistencyLevel;
}
if (desiredConsistencyLevelOfOperation != null) {
return desiredConsistencyLevelOfOperation;
}
if (this.desiredConsistencyLevel != null) {
return desiredConsistencyLevel;
}
return this.accountConsistencyLevel;
}
CosmosDiagnosticsThresholds getEffectiveDiagnosticsThresholds(
CosmosDiagnosticsThresholds operationLevelThresholds) {
if (operationLevelThresholds != null) {
return operationLevelThresholds;
}
if (this.clientTelemetryConfig == null) {
return new CosmosDiagnosticsThresholds();
}
CosmosDiagnosticsThresholds clientLevelThresholds =
telemetryConfigAccessor.getDiagnosticsThresholds(this.clientTelemetryConfig);
return clientLevelThresholds != null ? clientLevelThresholds : new CosmosDiagnosticsThresholds();
}
boolean isTransportLevelTracingEnabled() {
CosmosClientTelemetryConfig effectiveConfig = this.clientTelemetryConfig != null ?
this.clientTelemetryConfig
: DEFAULT_TELEMETRY_CONFIG;
if (telemetryConfigAccessor.isLegacyTracingEnabled(effectiveConfig)) {
return false;
}
if (this.getConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) {
return false;
}
return telemetryConfigAccessor.isTransportLevelTracingEnabled(effectiveConfig);
}
void recordOpenConnectionsAndInitCachesCompleted(List<CosmosContainerIdentity> cosmosContainerIdentities) {
this.asyncDocumentClient.recordOpenConnectionsAndInitCachesCompleted(cosmosContainerIdentities);
}
void recordOpenConnectionsAndInitCachesStarted(List<CosmosContainerIdentity> cosmosContainerIdentities) {
this.asyncDocumentClient.recordOpenConnectionsAndInitCachesStarted(cosmosContainerIdentities);
}
String getAccountTagValue() {
return this.accountTagValue;
}
Tag getClientCorrelationTag() {
return this.clientCorrelationTag;
}
String getUserAgent() {
return this.asyncDocumentClient.getUserAgent();
}
static void initialize() {
ImplementationBridgeHelpers.CosmosAsyncClientHelper.setCosmosAsyncClientAccessor(
new ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor() {
@Override
public Tag getClientCorrelationTag(CosmosAsyncClient client) {
return client.getClientCorrelationTag();
}
@Override
public String getAccountTagValue(CosmosAsyncClient client) {
return client.getAccountTagValue();
}
@Override
public EnumSet<TagName> getMetricTagNames(CosmosAsyncClient client) {
return telemetryConfigAccessor
.getMetricTagNames(client.clientTelemetryConfig);
}
@Override
public EnumSet<MetricCategory> getMetricCategories(CosmosAsyncClient client) {
return telemetryConfigAccessor
.getMetricCategories(client.clientTelemetryConfig);
}
@Override
public boolean shouldEnableEmptyPageDiagnostics(CosmosAsyncClient client) {
return client.clientMetricsEnabled || client.isTransportLevelTracingEnabled();
}
@Override
public boolean isSendClientTelemetryToServiceEnabled(CosmosAsyncClient client) {
return client.isSendClientTelemetryToServiceEnabled;
}
@Override
public List<String> getPreferredRegions(CosmosAsyncClient client) {
return client.connectionPolicy.getPreferredRegions();
}
@Override
public boolean isEndpointDiscoveryEnabled(CosmosAsyncClient client) {
return client.connectionPolicy.isEndpointDiscoveryEnabled();
}
@Override
public CosmosMeterOptions getMeterOptions(CosmosAsyncClient client, CosmosMetricName name) {
return telemetryConfigAccessor
.getMeterOptions(client.clientTelemetryConfig, name);
}
@Override
public boolean isEffectiveContentResponseOnWriteEnabled(CosmosAsyncClient client,
Boolean requestOptionsContentResponseEnabled) {
if (requestOptionsContentResponseEnabled != null) {
return requestOptionsContentResponseEnabled;
}
return client.asyncDocumentClient.isContentResponseOnWriteEnabled();
}
@Override
public ConsistencyLevel getEffectiveConsistencyLevel(
CosmosAsyncClient client,
OperationType operationType,
ConsistencyLevel desiredConsistencyLevelOfOperation) {
return client.getEffectiveConsistencyLevel(operationType, desiredConsistencyLevelOfOperation);
}
@Override
public CosmosDiagnosticsThresholds getEffectiveDiagnosticsThresholds(
CosmosAsyncClient client,
CosmosDiagnosticsThresholds operationLevelThresholds) {
return client.getEffectiveDiagnosticsThresholds(operationLevelThresholds);
}
@Override
public DiagnosticsProvider getDiagnosticsProvider(CosmosAsyncClient client) {
return client.getDiagnosticsProvider();
}
}
);
}
static { initialize(); }
} |
We don't need an extra `take` operator here, we can update the above Flux with this - `return Flux.fromIterable(this.endpointManager.getReadEndpoints().subList(0, proactiveContainerInitConfig.getProactiveConnectionRegionsCount()))` | public Flux<Void> submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig) {
return Flux.fromIterable(proactiveContainerInitConfig.getCosmosContainerIdentities())
.publishOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC)
.flatMap(cosmosContainerIdentity -> {
return this
.collectionCache
.resolveByNameAsync(
null,
ImplementationBridgeHelpers
.CosmosContainerIdentityHelper
.getCosmosContainerIdentityAccessor()
.getContainerLink(cosmosContainerIdentity),
null)
.flatMapMany(collection -> {
if (collection == null) {
logger.warn("Can not find the collection, no connections will be opened");
return Flux.empty();
}
return this.routingMapProvider.tryGetOverlappingRangesAsync(
null,
collection.getResourceId(),
PartitionKeyInternalHelper.FullRange,
true,
null)
.flatMap(valueHolder -> {
String containerLink = ImplementationBridgeHelpers
.CosmosContainerIdentityHelper
.getCosmosContainerIdentityAccessor()
.getContainerLink(cosmosContainerIdentity);
if (valueHolder == null || valueHolder.v == null || valueHolder.v.size() == 0) {
logger.warn(
"There is no pkRanges found for collection {}, no connections will be opened",
collection.getResourceId());
return Mono.just(new ImmutablePair<>(containerLink, new ArrayList<PartitionKeyRangeIdentity>()));
}
List<PartitionKeyRangeIdentity> pkrs = valueHolder.v
.stream()
.map(pkRange -> new PartitionKeyRangeIdentity(collection.getResourceId(), pkRange.getId()))
.collect(Collectors.toList());
return Mono.just(new ImmutablePair<String, List<PartitionKeyRangeIdentity>>(containerLink, pkrs));
})
.flatMapMany(containerLinkToPkrs -> {
if (proactiveContainerInitConfig.getProactiveConnectionRegionsCount() > 0) {
return Flux.fromStream(this.endpointManager.getReadEndpoints().stream())
.take(proactiveContainerInitConfig.getProactiveConnectionRegionsCount())
.flatMap(readEndpoint -> {
if (this.addressCacheByEndpoint.containsKey(readEndpoint)) {
EndpointCache endpointCache = this.addressCacheByEndpoint.get(readEndpoint);
return this.resolveAddressesPerCollection(
endpointCache,
containerLinkToPkrs.left,
collection,
containerLinkToPkrs.right)
.flatMap(collectionToAddresses -> {
ImmutablePair<String, DocumentCollection> containerLinkToCollection
= collectionToAddresses.left;
AddressInformation addressInformation =
collectionToAddresses.right;
Map<String, Integer> containerLinkToMinConnectionsMap = ImplementationBridgeHelpers
.CosmosContainerProactiveInitConfigHelper
.getCosmosContainerIdentityAccessor()
.getContainerLinkToMinConnectionsMap(proactiveContainerInitConfig);
int connectionsPerEndpointCountForContainer = containerLinkToMinConnectionsMap
.getOrDefault(
containerLinkToCollection.left,
Configs.getMinConnectionPoolSizePerEndpoint()
);
return this.submitOpenConnectionInternal(
endpointCache,
addressInformation,
containerLinkToCollection.getRight(),
connectionsPerEndpointCountForContainer).then();
});
}
return Flux.empty();
}, 1);
}
return Flux.empty();
});
});
}, Configs.getCPUCnt(), Configs.getCPUCnt());
} | .take(proactiveContainerInitConfig.getProactiveConnectionRegionsCount()) | public Flux<Void> submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig) {
return Flux.fromIterable(proactiveContainerInitConfig.getCosmosContainerIdentities())
.publishOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC)
.flatMap(cosmosContainerIdentity -> {
return this
.collectionCache
.resolveByNameAsync(
null,
ImplementationBridgeHelpers
.CosmosContainerIdentityHelper
.getCosmosContainerIdentityAccessor()
.getContainerLink(cosmosContainerIdentity),
null)
.flatMapMany(collection -> {
if (collection == null) {
logger.warn("Can not find the collection, no connections will be opened");
return Flux.empty();
}
return this.routingMapProvider.tryGetOverlappingRangesAsync(
null,
collection.getResourceId(),
PartitionKeyInternalHelper.FullRange,
true,
null)
.flatMap(valueHolder -> {
String containerLink = ImplementationBridgeHelpers
.CosmosContainerIdentityHelper
.getCosmosContainerIdentityAccessor()
.getContainerLink(cosmosContainerIdentity);
if (valueHolder == null || valueHolder.v == null || valueHolder.v.size() == 0) {
logger.warn(
"There is no pkRanges found for collection {}, no connections will be opened",
collection.getResourceId());
return Mono.just(new ImmutablePair<>(containerLink, new ArrayList<PartitionKeyRangeIdentity>()));
}
List<PartitionKeyRangeIdentity> pkrs = valueHolder.v
.stream()
.map(pkRange -> new PartitionKeyRangeIdentity(collection.getResourceId(), pkRange.getId()))
.collect(Collectors.toList());
return Mono.just(new ImmutablePair<String, List<PartitionKeyRangeIdentity>>(containerLink, pkrs));
})
.flatMapMany(containerLinkToPkrs -> {
if (proactiveContainerInitConfig.getProactiveConnectionRegionsCount() > 0) {
return Flux.fromIterable(this.endpointManager.getReadEndpoints().subList(0, proactiveContainerInitConfig.getProactiveConnectionRegionsCount()))
.flatMap(readEndpoint -> {
if (this.addressCacheByEndpoint.containsKey(readEndpoint)) {
EndpointCache endpointCache = this.addressCacheByEndpoint.get(readEndpoint);
return this.resolveAddressesPerCollection(
endpointCache,
containerLinkToPkrs.left,
collection,
containerLinkToPkrs.right)
.flatMap(collectionToAddresses -> {
ImmutablePair<String, DocumentCollection> containerLinkToCollection
= collectionToAddresses.left;
AddressInformation addressInformation =
collectionToAddresses.right;
Map<String, Integer> containerLinkToMinConnectionsMap = ImplementationBridgeHelpers
.CosmosContainerProactiveInitConfigHelper
.getCosmosContainerProactiveInitConfigAccessor()
.getContainerLinkToMinConnectionsMap(proactiveContainerInitConfig);
int connectionsPerEndpointCountForContainer = containerLinkToMinConnectionsMap
.getOrDefault(
containerLinkToCollection.left,
Configs.getMinConnectionPoolSizePerEndpoint()
);
return this.submitOpenConnectionInternal(
endpointCache,
addressInformation,
containerLinkToCollection.getRight(),
connectionsPerEndpointCountForContainer).then();
});
}
return Flux.empty();
}, 1);
}
return Flux.empty();
});
});
}, Configs.getCPUCnt(), Configs.getCPUCnt());
} | class GlobalAddressResolver implements IAddressResolver {
private static final Logger logger = LoggerFactory.getLogger(GlobalAddressResolver.class);
private final static int MaxBackupReadRegions = 3;
private final DiagnosticsClientContext diagnosticsClientContext;
private final GlobalEndpointManager endpointManager;
private final Protocol protocol;
private final IAuthorizationTokenProvider tokenProvider;
private final UserAgentContainer userAgentContainer;
private final RxCollectionCache collectionCache;
private final RxPartitionKeyRangeCache routingMapProvider;
private final int maxEndpoints;
private final GatewayServiceConfigurationReader serviceConfigReader;
final Map<URI, EndpointCache> addressCacheByEndpoint;
private final boolean tcpConnectionEndpointRediscoveryEnabled;
private ApiType apiType;
private HttpClient httpClient;
private ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor;
private ConnectionPolicy connectionPolicy;
public GlobalAddressResolver(
DiagnosticsClientContext diagnosticsClientContext,
HttpClient httpClient,
GlobalEndpointManager endpointManager,
Protocol protocol,
IAuthorizationTokenProvider tokenProvider,
RxCollectionCache collectionCache,
RxPartitionKeyRangeCache routingMapProvider,
UserAgentContainer userAgentContainer,
GatewayServiceConfigurationReader serviceConfigReader,
ConnectionPolicy connectionPolicy,
ApiType apiType) {
this.diagnosticsClientContext = diagnosticsClientContext;
this.httpClient = httpClient;
this.endpointManager = endpointManager;
this.protocol = protocol;
this.tokenProvider = tokenProvider;
this.userAgentContainer = userAgentContainer;
this.collectionCache = collectionCache;
this.routingMapProvider = routingMapProvider;
this.serviceConfigReader = serviceConfigReader;
this.tcpConnectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled();
this.connectionPolicy = connectionPolicy;
int maxBackupReadEndpoints = (connectionPolicy.isReadRequestsFallbackEnabled()) ? GlobalAddressResolver.MaxBackupReadRegions : 0;
this.maxEndpoints = maxBackupReadEndpoints + 2;
this.addressCacheByEndpoint = new ConcurrentHashMap<>();
this.apiType = apiType;
for (URI endpoint : endpointManager.getWriteEndpoints()) {
this.getOrAddEndpoint(endpoint);
}
for (URI endpoint : endpointManager.getReadEndpoints()) {
this.getOrAddEndpoint(endpoint);
}
}
private Flux<ImmutablePair<ImmutablePair<String, DocumentCollection>, AddressInformation>> resolveAddressesPerCollection(
EndpointCache endpointCache,
String containerLink,
DocumentCollection collection,
List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) {
return endpointCache
.addressCache
.resolveAddressesAndInitCaches(
containerLink,
collection,
partitionKeyRangeIdentities
);
}
private Mono<OpenConnectionResponse> submitOpenConnectionInternal(
EndpointCache endpointCache,
AddressInformation address,
DocumentCollection documentCollection,
int connectionPerEndpointCount) {
return endpointCache.addressCache.submitOpenConnectionTask(address, documentCollection, connectionPerEndpointCount);
}
@Override
public void setOpenConnectionsProcessor(ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor) {
this.proactiveOpenConnectionsProcessor = proactiveOpenConnectionsProcessor;
for (EndpointCache endpointCache : this.addressCacheByEndpoint.values()) {
endpointCache.addressCache.setOpenConnectionsProcessor(this.proactiveOpenConnectionsProcessor);
}
}
@Override
public Mono<AddressInformation[]> resolveAsync(RxDocumentServiceRequest request, boolean forceRefresh) {
IAddressResolver resolver = this.getAddressResolver(request);
return resolver.resolveAsync(request, forceRefresh);
}
public void dispose() {
for (EndpointCache endpointCache : this.addressCacheByEndpoint.values()) {
endpointCache.addressCache.dispose();
}
}
private IAddressResolver getAddressResolver(RxDocumentServiceRequest rxDocumentServiceRequest) {
URI endpoint = this.endpointManager.resolveServiceEndpoint(rxDocumentServiceRequest);
return this.getOrAddEndpoint(endpoint).addressResolver;
}
private EndpointCache getOrAddEndpoint(URI endpoint) {
EndpointCache endpointCache = this.addressCacheByEndpoint.computeIfAbsent(endpoint , key -> {
GatewayAddressCache gatewayAddressCache = new GatewayAddressCache(
this.diagnosticsClientContext,
endpoint,
protocol,
this.tokenProvider,
this.userAgentContainer,
this.httpClient,
this.apiType,
this.endpointManager,
this.connectionPolicy,
this.proactiveOpenConnectionsProcessor);
AddressResolver addressResolver = new AddressResolver();
addressResolver.initializeCaches(this.collectionCache, this.routingMapProvider, gatewayAddressCache);
EndpointCache cache = new EndpointCache();
cache.addressCache = gatewayAddressCache;
cache.addressResolver = addressResolver;
return cache;
});
if (this.addressCacheByEndpoint.size() > this.maxEndpoints) {
List<URI> allEndpoints = new ArrayList<>(this.endpointManager.getWriteEndpoints());
allEndpoints.addAll(this.endpointManager.getReadEndpoints());
Collections.reverse(allEndpoints);
LinkedList<URI> endpoints = new LinkedList<>(allEndpoints);
while (this.addressCacheByEndpoint.size() > this.maxEndpoints) {
if (endpoints.size() > 0) {
URI dequeueEndpoint = endpoints.pop();
if (this.addressCacheByEndpoint.get(dequeueEndpoint) != null) {
this.addressCacheByEndpoint.remove(dequeueEndpoint);
}
} else {
break;
}
}
}
return endpointCache;
}
static class EndpointCache {
GatewayAddressCache addressCache;
AddressResolver addressResolver;
}
} | class GlobalAddressResolver implements IAddressResolver {
private static final Logger logger = LoggerFactory.getLogger(GlobalAddressResolver.class);
private final static int MaxBackupReadRegions = 3;
private final DiagnosticsClientContext diagnosticsClientContext;
private final GlobalEndpointManager endpointManager;
private final Protocol protocol;
private final IAuthorizationTokenProvider tokenProvider;
private final UserAgentContainer userAgentContainer;
private final RxCollectionCache collectionCache;
private final RxPartitionKeyRangeCache routingMapProvider;
private final int maxEndpoints;
private final GatewayServiceConfigurationReader serviceConfigReader;
final Map<URI, EndpointCache> addressCacheByEndpoint;
private final boolean tcpConnectionEndpointRediscoveryEnabled;
private ApiType apiType;
private HttpClient httpClient;
private ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor;
private ConnectionPolicy connectionPolicy;
public GlobalAddressResolver(
DiagnosticsClientContext diagnosticsClientContext,
HttpClient httpClient,
GlobalEndpointManager endpointManager,
Protocol protocol,
IAuthorizationTokenProvider tokenProvider,
RxCollectionCache collectionCache,
RxPartitionKeyRangeCache routingMapProvider,
UserAgentContainer userAgentContainer,
GatewayServiceConfigurationReader serviceConfigReader,
ConnectionPolicy connectionPolicy,
ApiType apiType) {
this.diagnosticsClientContext = diagnosticsClientContext;
this.httpClient = httpClient;
this.endpointManager = endpointManager;
this.protocol = protocol;
this.tokenProvider = tokenProvider;
this.userAgentContainer = userAgentContainer;
this.collectionCache = collectionCache;
this.routingMapProvider = routingMapProvider;
this.serviceConfigReader = serviceConfigReader;
this.tcpConnectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled();
this.connectionPolicy = connectionPolicy;
int maxBackupReadEndpoints = (connectionPolicy.isReadRequestsFallbackEnabled()) ? GlobalAddressResolver.MaxBackupReadRegions : 0;
this.maxEndpoints = maxBackupReadEndpoints + 2;
this.addressCacheByEndpoint = new ConcurrentHashMap<>();
this.apiType = apiType;
for (URI endpoint : endpointManager.getWriteEndpoints()) {
this.getOrAddEndpoint(endpoint);
}
for (URI endpoint : endpointManager.getReadEndpoints()) {
this.getOrAddEndpoint(endpoint);
}
}
private Flux<ImmutablePair<ImmutablePair<String, DocumentCollection>, AddressInformation>> resolveAddressesPerCollection(
EndpointCache endpointCache,
String containerLink,
DocumentCollection collection,
List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) {
return endpointCache
.addressCache
.resolveAddressesAndInitCaches(
containerLink,
collection,
partitionKeyRangeIdentities
);
}
private Mono<OpenConnectionResponse> submitOpenConnectionInternal(
EndpointCache endpointCache,
AddressInformation address,
DocumentCollection documentCollection,
int connectionPerEndpointCount) {
return endpointCache.addressCache.submitOpenConnectionTask(address, documentCollection, connectionPerEndpointCount);
}
@Override
public void setOpenConnectionsProcessor(ProactiveOpenConnectionsProcessor proactiveOpenConnectionsProcessor) {
this.proactiveOpenConnectionsProcessor = proactiveOpenConnectionsProcessor;
for (EndpointCache endpointCache : this.addressCacheByEndpoint.values()) {
endpointCache.addressCache.setOpenConnectionsProcessor(this.proactiveOpenConnectionsProcessor);
}
}
@Override
public Mono<AddressInformation[]> resolveAsync(RxDocumentServiceRequest request, boolean forceRefresh) {
IAddressResolver resolver = this.getAddressResolver(request);
return resolver.resolveAsync(request, forceRefresh);
}
public void dispose() {
for (EndpointCache endpointCache : this.addressCacheByEndpoint.values()) {
endpointCache.addressCache.dispose();
}
}
private IAddressResolver getAddressResolver(RxDocumentServiceRequest rxDocumentServiceRequest) {
URI endpoint = this.endpointManager.resolveServiceEndpoint(rxDocumentServiceRequest);
return this.getOrAddEndpoint(endpoint).addressResolver;
}
private EndpointCache getOrAddEndpoint(URI endpoint) {
EndpointCache endpointCache = this.addressCacheByEndpoint.computeIfAbsent(endpoint , key -> {
GatewayAddressCache gatewayAddressCache = new GatewayAddressCache(
this.diagnosticsClientContext,
endpoint,
protocol,
this.tokenProvider,
this.userAgentContainer,
this.httpClient,
this.apiType,
this.endpointManager,
this.connectionPolicy,
this.proactiveOpenConnectionsProcessor);
AddressResolver addressResolver = new AddressResolver();
addressResolver.initializeCaches(this.collectionCache, this.routingMapProvider, gatewayAddressCache);
EndpointCache cache = new EndpointCache();
cache.addressCache = gatewayAddressCache;
cache.addressResolver = addressResolver;
return cache;
});
if (this.addressCacheByEndpoint.size() > this.maxEndpoints) {
List<URI> allEndpoints = new ArrayList<>(this.endpointManager.getWriteEndpoints());
allEndpoints.addAll(this.endpointManager.getReadEndpoints());
Collections.reverse(allEndpoints);
LinkedList<URI> endpoints = new LinkedList<>(allEndpoints);
while (this.addressCacheByEndpoint.size() > this.maxEndpoints) {
if (endpoints.size() > 0) {
URI dequeueEndpoint = endpoints.pop();
if (this.addressCacheByEndpoint.get(dequeueEndpoint) != null) {
this.addressCacheByEndpoint.remove(dequeueEndpoint);
}
} else {
break;
}
}
}
return endpointCache;
}
static class EndpointCache {
GatewayAddressCache addressCache;
AddressResolver addressResolver;
}
} |
why the check of Duration.ZERO here? | public CosmosClient buildClient() {
StopWatch stopwatch = new StopWatch();
stopwatch.start();
validateConfig();
buildConnectionPolicy();
CosmosClient cosmosClient = new CosmosClient(this);
if (proactiveContainerInitConfig != null) {
Duration aggressiveProactiveConnectionEstablishmentTimeWindow = proactiveContainerInitConfig
.getAggressiveProactiveConnectionEstablishmentDuration();
if (aggressiveProactiveConnectionEstablishmentTimeWindow != Duration.ZERO) {
cosmosClient.openConnectionsAndInitCaches(aggressiveProactiveConnectionEstablishmentTimeWindow);
} else {
cosmosClient.openConnectionsAndInitCaches();
}
}
logStartupInfo(stopwatch, cosmosClient.asyncClient());
return cosmosClient;
} | if (aggressiveProactiveConnectionEstablishmentTimeWindow != Duration.ZERO) { | public CosmosClient buildClient() {
StopWatch stopwatch = new StopWatch();
stopwatch.start();
validateConfig();
buildConnectionPolicy();
CosmosClient cosmosClient = new CosmosClient(this);
if (proactiveContainerInitConfig != null) {
Duration aggressiveWarmupDuration = proactiveContainerInitConfig
.getAggressiveWarmupDuration();
if (aggressiveWarmupDuration != null) {
cosmosClient.openConnectionsAndInitCaches(aggressiveWarmupDuration);
} else {
cosmosClient.openConnectionsAndInitCaches();
}
}
logStartupInfo(stopwatch, cosmosClient.asyncClient());
return cosmosClient;
} | class to instantiate {@link CosmosContainerProactiveInitConfig} | class to instantiate {@link CosmosContainerProactiveInitConfig} |
I wish if we could move this logic of validating in the proactive connection management class, may be something to consider in next follow up PR. | private void validateConfig() {
URI uri;
try {
uri = new URI(serviceEndpoint);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("invalid serviceEndpoint", e);
}
if (preferredRegions != null) {
preferredRegions.forEach(
preferredRegion -> {
Preconditions.checkArgument(StringUtils.trimToNull(preferredRegion) != null, "preferredRegion can't be empty");
String trimmedPreferredRegion = preferredRegion.toLowerCase(Locale.ROOT).replace(" ", "");
LocationHelper.getLocationEndpoint(uri, trimmedPreferredRegion);
}
);
}
if (proactiveContainerInitConfig != null) {
Preconditions.checkArgument(preferredRegions != null, "preferredRegions cannot be null when proactiveContainerInitConfig has been set");
Preconditions.checkArgument(this.proactiveContainerInitConfig.getProactiveConnectionRegionsCount() <= this.preferredRegions.size(), "no. of regions to proactively connect to " +
"cannot be greater than the no.of preferred regions");
Preconditions.checkArgument(this.proactiveContainerInitConfig.getProactiveConnectionRegionsCount() > 0, "no. of proactive connection regions should be greater than 0");
if (this.proactiveContainerInitConfig.getProactiveConnectionRegionsCount() > 1) {
Preconditions.checkArgument(this.isEndpointDiscoveryEnabled(), "endpoint discovery should be enabled when no. " +
"of proactive regions is greater than 1");
}
}
ifThrowIllegalArgException(this.serviceEndpoint == null,
"cannot buildAsyncClient client without service endpoint");
ifThrowIllegalArgException(
this.keyOrResourceToken == null && (permissions == null || permissions.isEmpty())
&& this.credential == null && this.tokenCredential == null && this.cosmosAuthorizationTokenResolver == null,
"cannot buildAsyncClient client without any one of key, resource token, permissions, and "
+ "azure key credential");
ifThrowIllegalArgException(credential != null && StringUtils.isEmpty(credential.getKey()),
"cannot buildAsyncClient client without key credential");
} | Preconditions.checkArgument(this.proactiveContainerInitConfig.getProactiveConnectionRegionsCount() > 0, "no. of proactive connection regions should be greater than 0"); | private void validateConfig() {
URI uri;
try {
uri = new URI(serviceEndpoint);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("invalid serviceEndpoint", e);
}
if (preferredRegions != null) {
preferredRegions.forEach(
preferredRegion -> {
Preconditions.checkArgument(StringUtils.trimToNull(preferredRegion) != null, "preferredRegion can't be empty");
String trimmedPreferredRegion = preferredRegion.toLowerCase(Locale.ROOT).replace(" ", "");
LocationHelper.getLocationEndpoint(uri, trimmedPreferredRegion);
}
);
}
if (proactiveContainerInitConfig != null) {
Preconditions.checkArgument(preferredRegions != null, "preferredRegions cannot be null when proactiveContainerInitConfig has been set");
Preconditions.checkArgument(this.proactiveContainerInitConfig.getProactiveConnectionRegionsCount() <= this.preferredRegions.size(), "no. of regions to proactively connect to " +
"cannot be greater than the no.of preferred regions");
Preconditions.checkArgument(this.proactiveContainerInitConfig.getProactiveConnectionRegionsCount() > 0, "no. of proactive connection regions should be greater than 0");
if (this.proactiveContainerInitConfig.getProactiveConnectionRegionsCount() > 1) {
Preconditions.checkArgument(this.isEndpointDiscoveryEnabled(), "endpoint discovery should be enabled when no. " +
"of proactive regions is greater than 1");
}
}
ifThrowIllegalArgException(this.serviceEndpoint == null,
"cannot buildAsyncClient client without service endpoint");
ifThrowIllegalArgException(
this.keyOrResourceToken == null && (permissions == null || permissions.isEmpty())
&& this.credential == null && this.tokenCredential == null && this.cosmosAuthorizationTokenResolver == null,
"cannot buildAsyncClient client without any one of key, resource token, permissions, and "
+ "azure key credential");
ifThrowIllegalArgException(credential != null && StringUtils.isEmpty(credential.getKey()),
"cannot buildAsyncClient client without key credential");
} | class to instantiate {@link CosmosContainerProactiveInitConfig} | class to instantiate {@link CosmosContainerProactiveInitConfig} |
Was this added for debugging? | public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
this.getClass().getName();
return this;
} | this.getClass().getName(); | public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) {
this.allowedQueryParamNames.add(allowedQueryParamName);
return this;
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private List<HeaderName> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private HttpRequestLogger requestLogger;
private HttpResponseLogger responseLogger;
private static final List<HeaderName> DEFAULT_HEADERS_ALLOWLIST = Arrays.asList(
HeaderName.TRACEPARENT,
HeaderName.ACCEPT,
HeaderName.CACHE_CONTROL,
HeaderName.CONNECTION,
HeaderName.CONTENT_LENGTH,
HeaderName.CONTENT_TYPE,
HeaderName.DATE,
HeaderName.ETAG,
HeaderName.EXPIRES,
HeaderName.IF_MATCH,
HeaderName.IF_MODIFIED_SINCE,
HeaderName.IF_NONE_MATCH,
HeaderName.IF_UNMODIFIED_SINCE,
HeaderName.LAST_MODIFIED,
HeaderName.PRAGMA,
HeaderName.CLIENT_REQUEST_ID,
HeaderName.RETRY_AFTER,
HeaderName.SERVER,
HeaderName.TRANSFER_ENCODING,
HeaderName.USER_AGENT,
HeaderName.WWW_AUTHENTICATE
);
private static final List<String> DEFAULT_QUERY_PARAMS_ALLOWLIST = Collections.singletonList(
"api-version"
);
/**
* Creates a new instance that does not log any information about HTTP requests or responses.
*/
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.ENVIRONMENT_HTTP_LOG_DETAIL_LEVEL;
allowedHeaderNames = new ArrayList<>(DEFAULT_HEADERS_ALLOWLIST);
allowedQueryParamNames = new HashSet<>(DEFAULT_QUERY_PARAMS_ALLOWLIST);
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the allowed headers that should be logged.
*
* @return The list of allowed headers.
*/
public List<HeaderName> getAllowedHeaderNames() {
return Collections.unmodifiableList(allowedHeaderNames);
}
/**
* Sets the given allowed headers that should be logged.
*
* <p>
* This method sets the provided header names to be the allowed header names which will be logged for all HTTP
* requests and responses, overwriting any previously configured headers. Additionally, users can use
* {@link HttpLogOptions
* remove more headers names to the existing set of allowed header names.
* </p>
*
* @param allowedHeaderNames The list of allowed header names from the user.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedHeaderNames(final List<HeaderName> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new ArrayList<>() : allowedHeaderNames;
return this;
}
/**
* Sets the given allowed header to the default header set that should be logged.
*
* @param allowedHeaderName The allowed header name from the user.
*
* @return The updated HttpLogOptions object.
*
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(HeaderName.fromString(allowedHeaderName));
return this;
}
/**
* Gets the allowed query parameters.
*
* @return The list of allowed query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return Collections.unmodifiableSet(allowedQueryParamNames);
}
/**
* Sets the given allowed query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of allowed query params from the user.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames == null ? new HashSet<>() : allowedQueryParamNames;
return this;
}
/**
* Sets the given allowed query param that should be logged.
*
* @param allowedQueryParamName The allowed query param name from the user.
*
* @return The updated HttpLogOptions object.
*
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
/**
* Gets the {@link HttpRequestLogger} that will be used to log HTTP requests.
*
* <p>A default {@link HttpRequestLogger} will be used if one isn't supplied.
*
* @return The {@link HttpRequestLogger} that will be used to log HTTP requests.
*/
public HttpRequestLogger getRequestLogger() {
return requestLogger;
}
/**
* Sets the {@link HttpRequestLogger} that will be used to log HTTP requests.
*
* <p>A default {@link HttpRequestLogger} will be used if one isn't supplied.
*
* @param requestLogger The {@link HttpRequestLogger} that will be used to log HTTP requests.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setRequestLogger(HttpRequestLogger requestLogger) {
this.requestLogger = requestLogger;
return this;
}
/**
* Gets the {@link HttpResponseLogger} that will be used to log HTTP responses.
*
* <p>A default {@link HttpResponseLogger} will be used if one isn't supplied.
*
* @return The {@link HttpResponseLogger} that will be used to log HTTP responses.
*/
public HttpResponseLogger getResponseLogger() {
return responseLogger;
}
/**
* Sets the {@link HttpResponseLogger} that will be used to log HTTP responses.
*
* <p>A default {@link HttpResponseLogger} will be used if one isn't supplied.
*
* @param responseLogger The {@link HttpResponseLogger} that will be used to log HTTP responses.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setResponseLogger(HttpResponseLogger responseLogger) {
this.responseLogger = responseLogger;
return this;
}
/**
* The level of detail to log on HTTP messages.
*/
public enum HttpLogDetailLevel {
/**
* Logging is turned off.
*/
NONE,
/**
* Logs only URLs, HTTP methods, and time to finish the request.
*/
BASIC,
/**
* Logs everything in BASIC, plus all the request and response headers.
*/
HEADERS,
/**
* Logs everything in BASIC, plus all the request and response body. Note that only payloads in plain text or
* plain text encoded in GZIP will be logged.
*/
BODY,
/**
* Logs everything in HEADERS and BODY.
*/
BODYANDHEADERS;
static final String BASIC_VALUE = "basic";
static final String HEADERS_VALUE = "headers";
static final String BODY_VALUE = "body";
static final String BODY_AND_HEADERS_VALUE = "body_and_headers";
static final String BODYANDHEADERS_VALUE = "bodyandheaders";
static final HttpLogDetailLevel ENVIRONMENT_HTTP_LOG_DETAIL_LEVEL = fromConfiguration(getGlobalConfiguration());
static HttpLogDetailLevel fromConfiguration(Configuration configuration) {
String detailLevel = configuration.get(Configuration.PROPERTY_HTTP_LOG_DETAIL_LEVEL, "none");
HttpLogDetailLevel logDetailLevel;
if (BASIC_VALUE.equalsIgnoreCase(detailLevel)) {
logDetailLevel = BASIC;
} else if (HEADERS_VALUE.equalsIgnoreCase(detailLevel)) {
logDetailLevel = HEADERS;
} else if (BODY_VALUE.equalsIgnoreCase(detailLevel)) {
logDetailLevel = BODY;
} else if (BODY_AND_HEADERS_VALUE.equalsIgnoreCase(detailLevel)
|| BODYANDHEADERS_VALUE.equalsIgnoreCase(detailLevel)) {
logDetailLevel = BODYANDHEADERS;
} else {
logDetailLevel = NONE;
}
return logDetailLevel;
}
/**
* Whether a URL should be logged.
*
* @return Whether a URL should be logged.
*/
public boolean shouldLogUrl() {
return this != NONE;
}
/**
* Whether headers should be logged.
*
* @return Whether headers should be logged.
*/
public boolean shouldLogHeaders() {
return this == HEADERS || this == BODYANDHEADERS;
}
/**
* Whether a body should be logged.
*
* @return Whether a body should be logged.
*/
public boolean shouldLogBody() {
return this == BODY || this == BODYANDHEADERS;
}
}
} | class HttpLogOptions {
private HttpLogDetailLevel logLevel;
private List<HeaderName> allowedHeaderNames;
private Set<String> allowedQueryParamNames;
private HttpRequestLogger requestLogger;
private HttpResponseLogger responseLogger;
private static final List<HeaderName> DEFAULT_HEADERS_ALLOWLIST = Arrays.asList(
HeaderName.TRACEPARENT,
HeaderName.ACCEPT,
HeaderName.CACHE_CONTROL,
HeaderName.CONNECTION,
HeaderName.CONTENT_LENGTH,
HeaderName.CONTENT_TYPE,
HeaderName.DATE,
HeaderName.ETAG,
HeaderName.EXPIRES,
HeaderName.IF_MATCH,
HeaderName.IF_MODIFIED_SINCE,
HeaderName.IF_NONE_MATCH,
HeaderName.IF_UNMODIFIED_SINCE,
HeaderName.LAST_MODIFIED,
HeaderName.PRAGMA,
HeaderName.CLIENT_REQUEST_ID,
HeaderName.RETRY_AFTER,
HeaderName.SERVER,
HeaderName.TRANSFER_ENCODING,
HeaderName.USER_AGENT,
HeaderName.WWW_AUTHENTICATE
);
private static final List<String> DEFAULT_QUERY_PARAMS_ALLOWLIST = Collections.singletonList(
"api-version"
);
/**
* Creates a new instance that does not log any information about HTTP requests or responses.
*/
public HttpLogOptions() {
logLevel = HttpLogDetailLevel.ENVIRONMENT_HTTP_LOG_DETAIL_LEVEL;
allowedHeaderNames = new ArrayList<>(DEFAULT_HEADERS_ALLOWLIST);
allowedQueryParamNames = new HashSet<>(DEFAULT_QUERY_PARAMS_ALLOWLIST);
}
/**
* Gets the level of detail to log on HTTP messages.
*
* @return The {@link HttpLogDetailLevel}.
*/
public HttpLogDetailLevel getLogLevel() {
return logLevel;
}
/**
* Sets the level of detail to log on Http messages.
*
* <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logLevel The {@link HttpLogDetailLevel}.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) {
this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel;
return this;
}
/**
* Gets the allowed headers that should be logged.
*
* @return The list of allowed headers.
*/
public List<HeaderName> getAllowedHeaderNames() {
return Collections.unmodifiableList(allowedHeaderNames);
}
/**
* Sets the given allowed headers that should be logged.
*
* <p>
* This method sets the provided header names to be the allowed header names which will be logged for all HTTP
* requests and responses, overwriting any previously configured headers. Additionally, users can use
* {@link HttpLogOptions
* remove more headers names to the existing set of allowed header names.
* </p>
*
* @param allowedHeaderNames The list of allowed header names from the user.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedHeaderNames(final List<HeaderName> allowedHeaderNames) {
this.allowedHeaderNames = allowedHeaderNames == null ? new ArrayList<>() : allowedHeaderNames;
return this;
}
/**
* Sets the given allowed header to the default header set that should be logged.
*
* @param allowedHeaderName The allowed header name from the user.
*
* @return The updated HttpLogOptions object.
*
* @throws NullPointerException If {@code allowedHeaderName} is {@code null}.
*/
public HttpLogOptions addAllowedHeaderName(final HeaderName allowedHeaderName) {
Objects.requireNonNull(allowedHeaderName);
this.allowedHeaderNames.add(allowedHeaderName);
return this;
}
/**
* Gets the allowed query parameters.
*
* @return The list of allowed query parameters.
*/
public Set<String> getAllowedQueryParamNames() {
return Collections.unmodifiableSet(allowedQueryParamNames);
}
/**
* Sets the given allowed query params to be displayed in the logging info.
*
* @param allowedQueryParamNames The list of allowed query params from the user.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) {
this.allowedQueryParamNames = allowedQueryParamNames == null ? new HashSet<>() : allowedQueryParamNames;
return this;
}
/**
* Sets the given allowed query param that should be logged.
*
* @param allowedQueryParamName The allowed query param name from the user.
*
* @return The updated HttpLogOptions object.
*
* @throws NullPointerException If {@code allowedQueryParamName} is {@code null}.
*/
/**
* Gets the {@link HttpRequestLogger} that will be used to log HTTP requests.
*
* <p>A default {@link HttpRequestLogger} will be used if one isn't supplied.
*
* @return The {@link HttpRequestLogger} that will be used to log HTTP requests.
*/
public HttpRequestLogger getRequestLogger() {
return requestLogger;
}
/**
* Sets the {@link HttpRequestLogger} that will be used to log HTTP requests.
*
* <p>A default {@link HttpRequestLogger} will be used if one isn't supplied.
*
* @param requestLogger The {@link HttpRequestLogger} that will be used to log HTTP requests.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setRequestLogger(HttpRequestLogger requestLogger) {
this.requestLogger = requestLogger;
return this;
}
/**
* Gets the {@link HttpResponseLogger} that will be used to log HTTP responses.
*
* <p>A default {@link HttpResponseLogger} will be used if one isn't supplied.
*
* @return The {@link HttpResponseLogger} that will be used to log HTTP responses.
*/
public HttpResponseLogger getResponseLogger() {
return responseLogger;
}
/**
* Sets the {@link HttpResponseLogger} that will be used to log HTTP responses.
*
* <p>A default {@link HttpResponseLogger} will be used if one isn't supplied.
*
* @param responseLogger The {@link HttpResponseLogger} that will be used to log HTTP responses.
*
* @return The updated HttpLogOptions object.
*/
public HttpLogOptions setResponseLogger(HttpResponseLogger responseLogger) {
this.responseLogger = responseLogger;
return this;
}
/**
* The level of detail to log on HTTP messages.
*/
public enum HttpLogDetailLevel {
/**
* Logging is turned off.
*/
NONE,
/**
* Logs only URLs, HTTP methods, and time to finish the request.
*/
BASIC,
/**
* Logs everything in BASIC, plus all allowed request and response headers.
*/
HEADERS,
/**
* Logs everything in BASIC, plus all the request and response body. Note that only payloads in plain text or
* plain text encoded in GZIP will be logged.
*/
BODY,
/**
* Logs everything in HEADERS and BODY.
*/
BODYANDHEADERS;
static final String BASIC_VALUE = "basic";
static final String HEADERS_VALUE = "headers";
static final String BODY_VALUE = "body";
static final String BODY_AND_HEADERS_VALUE = "body_and_headers";
static final String BODYANDHEADERS_VALUE = "bodyandheaders";
static final HttpLogDetailLevel ENVIRONMENT_HTTP_LOG_DETAIL_LEVEL = fromConfiguration(getGlobalConfiguration());
static HttpLogDetailLevel fromConfiguration(Configuration configuration) {
String detailLevel = configuration.get(Configuration.PROPERTY_HTTP_LOG_DETAIL_LEVEL, "none");
HttpLogDetailLevel logDetailLevel;
if (BASIC_VALUE.equalsIgnoreCase(detailLevel)) {
logDetailLevel = BASIC;
} else if (HEADERS_VALUE.equalsIgnoreCase(detailLevel)) {
logDetailLevel = HEADERS;
} else if (BODY_VALUE.equalsIgnoreCase(detailLevel)) {
logDetailLevel = BODY;
} else if (BODY_AND_HEADERS_VALUE.equalsIgnoreCase(detailLevel)
|| BODYANDHEADERS_VALUE.equalsIgnoreCase(detailLevel)) {
logDetailLevel = BODYANDHEADERS;
} else {
logDetailLevel = NONE;
}
return logDetailLevel;
}
/**
* Whether a URL should be logged.
*
* @return Whether a URL should be logged.
*/
public boolean shouldLogUrl() {
return this != NONE;
}
/**
* Whether headers should be logged.
*
* @return Whether headers should be logged.
*/
public boolean shouldLogHeaders() {
return this == HEADERS || this == BODYANDHEADERS;
}
/**
* Whether a body should be logged.
*
* @return Whether a body should be logged.
*/
public boolean shouldLogBody() {
return this == BODY || this == BODYANDHEADERS;
}
}
} |
Resolved to do a `null` check instead. | public CosmosClient buildClient() {
StopWatch stopwatch = new StopWatch();
stopwatch.start();
validateConfig();
buildConnectionPolicy();
CosmosClient cosmosClient = new CosmosClient(this);
if (proactiveContainerInitConfig != null) {
Duration aggressiveProactiveConnectionEstablishmentTimeWindow = proactiveContainerInitConfig
.getAggressiveProactiveConnectionEstablishmentDuration();
if (aggressiveProactiveConnectionEstablishmentTimeWindow != Duration.ZERO) {
cosmosClient.openConnectionsAndInitCaches(aggressiveProactiveConnectionEstablishmentTimeWindow);
} else {
cosmosClient.openConnectionsAndInitCaches();
}
}
logStartupInfo(stopwatch, cosmosClient.asyncClient());
return cosmosClient;
} | if (aggressiveProactiveConnectionEstablishmentTimeWindow != Duration.ZERO) { | public CosmosClient buildClient() {
StopWatch stopwatch = new StopWatch();
stopwatch.start();
validateConfig();
buildConnectionPolicy();
CosmosClient cosmosClient = new CosmosClient(this);
if (proactiveContainerInitConfig != null) {
Duration aggressiveWarmupDuration = proactiveContainerInitConfig
.getAggressiveWarmupDuration();
if (aggressiveWarmupDuration != null) {
cosmosClient.openConnectionsAndInitCaches(aggressiveWarmupDuration);
} else {
cosmosClient.openConnectionsAndInitCaches();
}
}
logStartupInfo(stopwatch, cosmosClient.asyncClient());
return cosmosClient;
} | class to instantiate {@link CosmosContainerProactiveInitConfig} | class to instantiate {@link CosmosContainerProactiveInitConfig} |
Yes, I modified `ComosAsyncClient`'s and `CosmosContainer`'s behaviour to swallow exceptions instead when opening connections. | private void blockVoidFlux(Flux<Void> voidFlux) {
try {
voidFlux.blockLast();
} catch (Exception e) {
final Throwable throwable = Exceptions.unwrap(e);
if (throwable instanceof CosmosException) {
throw (CosmosException) throwable;
} else {
throw Exceptions.propagate(throwable);
}
}
} | final Throwable throwable = Exceptions.unwrap(e); | private void blockVoidFlux(Flux<Void> voidFlux) {
try {
voidFlux.blockLast();
} catch (Exception ex) {
logger.warn("The void flux did not complete successfully", ex);
}
} | class CosmosAsyncClient implements Closeable {
private static final Logger logger = LoggerFactory.getLogger(CosmosAsyncClient.class);
private static final CosmosClientTelemetryConfig DEFAULT_TELEMETRY_CONFIG = new CosmosClientTelemetryConfig();
private static final ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor queryOptionsAccessor =
ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor();
private static final ImplementationBridgeHelpers.FeedResponseHelper.FeedResponseAccessor feedResponseAccessor =
ImplementationBridgeHelpers.FeedResponseHelper.getFeedResponseAccessor();
private static final ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.CosmosClientTelemetryConfigAccessor
telemetryConfigAccessor = ImplementationBridgeHelpers
.CosmosClientTelemetryConfigHelper
.getCosmosClientTelemetryConfigAccessor();
private final AsyncDocumentClient asyncDocumentClient;
private final String serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel desiredConsistencyLevel;
private final AzureKeyCredential credential;
private final CosmosClientTelemetryConfig clientTelemetryConfig;
private final DiagnosticsProvider diagnosticsProvider;
private final Tag clientCorrelationTag;
private final String accountTagValue;
private final boolean clientMetricsEnabled;
private final boolean isSendClientTelemetryToServiceEnabled;
private final MeterRegistry clientMetricRegistrySnapshot;
private final CosmosContainerProactiveInitConfig proactiveContainerInitConfig;
private static final ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor containerIdentityAccessor =
ImplementationBridgeHelpers.CosmosContainerIdentityHelper.getCosmosContainerIdentityAccessor();
private final ConsistencyLevel accountConsistencyLevel;
private final WriteRetryPolicy nonIdempotentWriteRetryPolicy;
CosmosAsyncClient(CosmosClientBuilder builder) {
Configs configs = builder.configs();
this.serviceEndpoint = builder.getEndpoint();
String keyOrResourceToken = builder.getKey();
this.connectionPolicy = builder.getConnectionPolicy();
this.desiredConsistencyLevel = builder.getConsistencyLevel();
List<CosmosPermissionProperties> permissions = builder.getPermissions();
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver = builder.getAuthorizationTokenResolver();
this.credential = builder.getCredential();
TokenCredential tokenCredential = builder.getTokenCredential();
boolean sessionCapturingOverride = builder.isSessionCapturingOverrideEnabled();
boolean enableTransportClientSharing = builder.isConnectionSharingAcrossClientsEnabled();
this.proactiveContainerInitConfig = builder.getProactiveContainerInitConfig();
this.nonIdempotentWriteRetryPolicy = builder.getNonIdempotentWriteRetryPolicy();
CosmosClientTelemetryConfig effectiveTelemetryConfig = telemetryConfigAccessor
.createSnapshot(
builder.getClientTelemetryConfig(),
builder.isClientTelemetryEnabled());
this.clientTelemetryConfig = effectiveTelemetryConfig;
this.isSendClientTelemetryToServiceEnabled = telemetryConfigAccessor
.isSendClientTelemetryToServiceEnabled(effectiveTelemetryConfig);
boolean contentResponseOnWriteEnabled = builder.isContentResponseOnWriteEnabled();
ApiType apiType = builder.apiType();
String clientCorrelationId = telemetryConfigAccessor
.getClientCorrelationId(effectiveTelemetryConfig);
List<Permission> permissionList = new ArrayList<>();
if (permissions != null) {
permissionList =
permissions
.stream()
.map(ModelBridgeInternal::getPermission)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
this.asyncDocumentClient = new AsyncDocumentClient.Builder()
.withServiceEndpoint(this.serviceEndpoint)
.withMasterKeyOrResourceToken(keyOrResourceToken)
.withConnectionPolicy(this.connectionPolicy)
.withConsistencyLevel(this.desiredConsistencyLevel)
.withSessionCapturingOverride(sessionCapturingOverride)
.withConfigs(configs)
.withTokenResolver(cosmosAuthorizationTokenResolver)
.withCredential(this.credential)
.withTransportClientSharing(enableTransportClientSharing)
.withContentResponseOnWriteEnabled(contentResponseOnWriteEnabled)
.withTokenCredential(tokenCredential)
.withState(builder.metadataCaches())
.withPermissionFeed(permissionList)
.withApiType(apiType)
.withClientTelemetryConfig(this.clientTelemetryConfig)
.withClientCorrelationId(clientCorrelationId)
.withAggressiveProactiveConnectionDuration(this.proactiveContainerInitConfig != null ? this.proactiveContainerInitConfig.getAggressiveProactiveConnectionEstablishmentDuration() : null)
.build();
this.accountConsistencyLevel = this.asyncDocumentClient.getDefaultConsistencyLevelOfAccount();
String effectiveClientCorrelationId = this.asyncDocumentClient.getClientCorrelationId();
String machineId = this.asyncDocumentClient.getMachineId();
if (!Strings.isNullOrWhiteSpace(machineId) && machineId.startsWith(ClientTelemetry.VM_ID_PREFIX)) {
machineId = machineId.replace(ClientTelemetry.VM_ID_PREFIX, "vmId_");
if (Strings.isNullOrWhiteSpace(effectiveClientCorrelationId)) {
effectiveClientCorrelationId = machineId;
} else {
effectiveClientCorrelationId = String.format(
"%s_%s",
machineId,
effectiveClientCorrelationId);
}
}
this.clientCorrelationTag = Tag.of(
TagName.ClientCorrelationId.toString(),
ClientTelemetryMetrics.escape(effectiveClientCorrelationId));
this.clientMetricRegistrySnapshot = telemetryConfigAccessor
.getClientMetricRegistry(effectiveTelemetryConfig);
this.clientMetricsEnabled = clientMetricRegistrySnapshot != null;
CosmosMeterOptions cpuMeterOptions = telemetryConfigAccessor
.getMeterOptions(effectiveTelemetryConfig, CosmosMetricName.SYSTEM_CPU);
CosmosMeterOptions memoryMeterOptions = telemetryConfigAccessor
.getMeterOptions(effectiveTelemetryConfig, CosmosMetricName.SYSTEM_MEMORY_FREE);
if (clientMetricRegistrySnapshot != null) {
ClientTelemetryMetrics.add(clientMetricRegistrySnapshot, cpuMeterOptions, memoryMeterOptions);
}
this.accountTagValue = URI.create(this.serviceEndpoint).getHost().replace(
".documents.azure.com", ""
);
if (this.clientMetricsEnabled) {
telemetryConfigAccessor.setClientCorrelationTag(
effectiveTelemetryConfig,
this.clientCorrelationTag );
telemetryConfigAccessor.setAccountName(
effectiveTelemetryConfig,
this.accountTagValue
);
telemetryConfigAccessor.addDiagnosticsHandler(
effectiveTelemetryConfig,
new ClientMetricsDiagnosticsHandler(this)
);
}
if (this.isSendClientTelemetryToServiceEnabled) {
telemetryConfigAccessor.setClientTelemetry(
effectiveTelemetryConfig,
asyncDocumentClient.getClientTelemetry()
);
telemetryConfigAccessor.addDiagnosticsHandler(
effectiveTelemetryConfig,
new ClientTelemetryDiagnosticsHandler(effectiveTelemetryConfig)
);
}
this.diagnosticsProvider = new DiagnosticsProvider(
effectiveTelemetryConfig,
effectiveClientCorrelationId,
this.getUserAgent(),
this.connectionPolicy.getConnectionMode());
}
AsyncDocumentClient getContextClient() {
return this.asyncDocumentClient;
}
/**
* Monitor Cosmos client performance and resource utilization using the specified meter registry.
*
* @param registry meter registry to use for performance monitoring.
*/
static void setMonitorTelemetry(MeterRegistry registry) {
RntbdMetrics.add(registry);
}
/**
* Get the service endpoint.
*
* @return the service endpoint.
*/
String getServiceEndpoint() {
return serviceEndpoint;
}
/**
* Get the connection policy.
*
* @return {@link ConnectionPolicy}.
*/
ConnectionPolicy getConnectionPolicy() {
return connectionPolicy;
}
AsyncDocumentClient getDocClientWrapper() {
return asyncDocumentClient;
}
/**
* Gets the azure key credential.
*
* @return azure key credential.
*/
AzureKeyCredential credential() {
return credential;
}
/***
* Get the client telemetry config.
*
* @return the {@link CosmosClientTelemetryConfig}.
*/
CosmosClientTelemetryConfig getClientTelemetryConfig() {
return this.clientTelemetryConfig;
}
/**
* CREATE a Database if it does not already exist on the service.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param databaseProperties CosmosDatabaseProperties.
* @return a {@link Mono} containing the cosmos database response with the created or existing database or
* an error.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(CosmosDatabaseProperties databaseProperties) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(databaseProperties.getId()),
null, context));
}
/**
* Create a Database if it does not already exist on the service.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param id the id of the database.
* @return a {@link Mono} containing the cosmos database response with the created or existing database or
* an error.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id), null, context));
}
/**
* Create a Database if it does not already exist on the service.
* <br/>
* The throughputProperties will only be used if the specified database
* does not exist and therefor a new database will be created with throughputProperties.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param id the id.
* @param throughputProperties the throughputProperties.
* @return the mono.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id, ThroughputProperties throughputProperties) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id),
throughputProperties, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param options {@link CosmosDatabaseRequestOptions}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties,
CosmosDatabaseRequestOptions options) {
final CosmosDatabaseRequestOptions requestOptions = options == null ? new CosmosDatabaseRequestOptions() : options;
Database wrappedDatabase = new Database();
wrappedDatabase.setId(databaseProperties.getId());
return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties) {
return createDatabase(databaseProperties, new CosmosDatabaseRequestOptions());
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param id id of the database.
* @return a {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(String id) {
return createDatabase(new CosmosDatabaseProperties(id), new CosmosDatabaseRequestOptions());
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param throughputProperties the throughput properties for the database.
* @param options {@link CosmosDatabaseRequestOptions}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties,
ThroughputProperties throughputProperties,
CosmosDatabaseRequestOptions options) {
if (options == null) {
options = new CosmosDatabaseRequestOptions();
}
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
Database wrappedDatabase = new Database();
wrappedDatabase.setId(databaseProperties.getId());
final CosmosDatabaseRequestOptions requestOptions = options;
return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param throughputProperties the throughput properties for the database.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties, ThroughputProperties throughputProperties) {
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
return createDatabase(databaseProperties, options);
}
/**
* Creates a database.
*
* @param id the id.
* @param throughputProperties the throughputProperties.
* @return the mono.
*/
public Mono<CosmosDatabaseResponse> createDatabase(String id, ThroughputProperties throughputProperties) {
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
return createDatabase(new CosmosDatabaseProperties(id), options);
}
/**
* Reads all databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param options {@link CosmosQueryRequestOptions}
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases(CosmosQueryRequestOptions options) {
return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> {
String spanName = "readAllDatabases";
CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions();
String operationId = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getQueryNameOrDefault(nonNullOptions, spanName);
pagedFluxOptions.setTracerInformation(
spanName,
null,
null,
operationId,
OperationType.ReadFeed,
ResourceType.Database,
this,
nonNullOptions.getConsistencyLevel(),
this.getEffectiveDiagnosticsThresholds(queryOptionsAccessor.getDiagnosticsThresholds(nonNullOptions)));
setContinuationTokenAndMaxItemCount(pagedFluxOptions, options);
return getDocClientWrapper().readDatabases(options)
.map(response ->
feedResponseAccessor.createFeedResponse(
ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()),
response.getResponseHeaders(),
response.getCosmosDiagnostics()));
});
}
/**
* Reads all databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases() {
return readAllDatabases(new CosmosQueryRequestOptions());
}
/**
* Query for databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param query the query.
* @param options the feed options.
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(String query, CosmosQueryRequestOptions options) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
return queryDatabasesInternal(new SqlQuerySpec(query), options);
}
/**
* Query for databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param querySpec the SQL query specification.
* @param options the feed options.
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
return queryDatabasesInternal(querySpec, options);
}
/**
* Gets a database object without making a service call.
*
* @param id name of the database.
* @return {@link CosmosAsyncDatabase}.
*/
public CosmosAsyncDatabase getDatabase(String id) {
return new CosmosAsyncDatabase(id, this);
}
/**
* Close this {@link CosmosAsyncClient} instance and cleans up the resources.
*/
@Override
public void close() {
if (this.clientMetricRegistrySnapshot != null) {
ClientTelemetryMetrics.remove(this.clientMetricRegistrySnapshot);
}
asyncDocumentClient.close();
}
DiagnosticsProvider getDiagnosticsProvider() {
return this.diagnosticsProvider;
}
/**
* Enable throughput control group.
*
* @param group Throughput control group going to be enabled.
* @param throughputQueryMono The throughput query mono.
*/
void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) {
checkNotNull(group, "Throughput control group cannot be null");
this.asyncDocumentClient.enableThroughputControlGroup(group, throughputQueryMono);
}
/***
* Configure fault injector provider.
*
* @param injectorProvider the injector provider.
*/
void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) {
checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null");
this.asyncDocumentClient.configureFaultInjectorProvider(injectorProvider);
}
/**
* Create global throughput control config builder which will be used to build {@link GlobalThroughputControlConfig}.
*
* @param databaseId The database id of the control container.
* @param containerId The container id of the control container.
* @return A {@link GlobalThroughputControlConfigBuilder}.
*/
public GlobalThroughputControlConfigBuilder createGlobalThroughputControlConfigBuilder(String databaseId, String containerId) {
return new GlobalThroughputControlConfigBuilder(this, databaseId, containerId);
}
WriteRetryPolicy getNonIdempotentWriteRetryPolicy() {
return this.nonIdempotentWriteRetryPolicy;
}
void openConnectionsAndInitCaches() {
blockVoidFlux(asyncDocumentClient.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig));
}
void openConnectionsAndInitCaches(Duration aggressiveProactiveConnectionEstablishmentDuration) {
Flux<Void> submitOpenConnectionTasksFlux = asyncDocumentClient.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig);
wrapSourceFluxAndSoftCompleteAfterTimeout(
submitOpenConnectionTasksFlux,
aggressiveProactiveConnectionEstablishmentDuration,
CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC)
.blockLast();
}
private <T> Flux<T> wrapSourceFluxAndSoftCompleteAfterTimeout(Flux<T> source, Duration timeout, Scheduler executionContext) {
return Flux.<T>create(sink -> {
source
.subscribeOn(executionContext)
.subscribe(t -> sink.next(t));
})
.take(timeout);
}
private CosmosPagedFlux<CosmosDatabaseProperties> queryDatabasesInternal(
SqlQuerySpec querySpec,
CosmosQueryRequestOptions options){
return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> {
String spanName = "queryDatabases";
CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions();
String operationId = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getQueryNameOrDefault(nonNullOptions, spanName);
pagedFluxOptions.setTracerInformation(
spanName,
null,
null,
operationId,
OperationType.Query,
ResourceType.Database,
this,
nonNullOptions.getConsistencyLevel(),
this.getEffectiveDiagnosticsThresholds(queryOptionsAccessor.getDiagnosticsThresholds(nonNullOptions)));
setContinuationTokenAndMaxItemCount(pagedFluxOptions, options);
return getDocClientWrapper().queryDatabases(querySpec, options)
.map(response -> feedResponseAccessor.createFeedResponse(
ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()),
response.getResponseHeaders(),
response.getCosmosDiagnostics()));
});
}
private Mono<CosmosDatabaseResponse> createDatabaseIfNotExistsInternal(CosmosAsyncDatabase database,
ThroughputProperties throughputProperties, Context context) {
String spanName = "createDatabaseIfNotExists." + database.getId();
Context nestedContext = context.addData(
DiagnosticsProvider.COSMOS_CALL_DEPTH,
DiagnosticsProvider.COSMOS_CALL_DEPTH_VAL);
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
Mono<CosmosDatabaseResponse> responseMono = database.readInternal(new CosmosDatabaseRequestOptions(),
nestedContext).onErrorResume(exception -> {
final Throwable unwrappedException = Exceptions.unwrap(exception);
if (unwrappedException instanceof CosmosException) {
final CosmosException cosmosException = (CosmosException) unwrappedException;
if (cosmosException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
if (throughputProperties != null) {
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
}
Database wrappedDatabase = new Database();
wrappedDatabase.setId(database.getId());
return createDatabaseInternal(wrappedDatabase,
options, nestedContext);
}
}
return Mono.error(unwrappedException);
});
RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options);
return this.diagnosticsProvider.traceEnabledCosmosResponsePublisher(
responseMono,
context,
spanName,
database.getId(),
null,
this,
null,
OperationType.Create,
ResourceType.Database,
this.getEffectiveDiagnosticsThresholds(requestOptions.getDiagnosticsThresholds()));
}
private Mono<CosmosDatabaseResponse> createDatabaseInternal(Database database, CosmosDatabaseRequestOptions options,
Context context) {
String spanName = "createDatabase." + database.getId();
RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options);
Mono<CosmosDatabaseResponse> responseMono = asyncDocumentClient.createDatabase(database, requestOptions)
.map(ModelBridgeInternal::createCosmosDatabaseResponse)
.single();
return this.diagnosticsProvider
.traceEnabledCosmosResponsePublisher(
responseMono,
context,
spanName,
database.getId(),
null,
this,
null,
OperationType.Create,
ResourceType.Database,
this.getEffectiveDiagnosticsThresholds(requestOptions.getDiagnosticsThresholds()));
}
private ConsistencyLevel getEffectiveConsistencyLevel(
OperationType operationType,
ConsistencyLevel desiredConsistencyLevelOfOperation) {
if (operationType.isWriteOperation()) {
return this.accountConsistencyLevel;
}
if (desiredConsistencyLevelOfOperation != null) {
return desiredConsistencyLevelOfOperation;
}
if (this.desiredConsistencyLevel != null) {
return desiredConsistencyLevel;
}
return this.accountConsistencyLevel;
}
CosmosDiagnosticsThresholds getEffectiveDiagnosticsThresholds(
CosmosDiagnosticsThresholds operationLevelThresholds) {
if (operationLevelThresholds != null) {
return operationLevelThresholds;
}
if (this.clientTelemetryConfig == null) {
return new CosmosDiagnosticsThresholds();
}
CosmosDiagnosticsThresholds clientLevelThresholds =
telemetryConfigAccessor.getDiagnosticsThresholds(this.clientTelemetryConfig);
return clientLevelThresholds != null ? clientLevelThresholds : new CosmosDiagnosticsThresholds();
}
boolean isTransportLevelTracingEnabled() {
CosmosClientTelemetryConfig effectiveConfig = this.clientTelemetryConfig != null ?
this.clientTelemetryConfig
: DEFAULT_TELEMETRY_CONFIG;
if (telemetryConfigAccessor.isLegacyTracingEnabled(effectiveConfig)) {
return false;
}
if (this.getConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) {
return false;
}
return telemetryConfigAccessor.isTransportLevelTracingEnabled(effectiveConfig);
}
String getAccountTagValue() {
return this.accountTagValue;
}
Tag getClientCorrelationTag() {
return this.clientCorrelationTag;
}
String getUserAgent() {
return this.asyncDocumentClient.getUserAgent();
}
static void initialize() {
ImplementationBridgeHelpers.CosmosAsyncClientHelper.setCosmosAsyncClientAccessor(
new ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor() {
@Override
public Tag getClientCorrelationTag(CosmosAsyncClient client) {
return client.getClientCorrelationTag();
}
@Override
public String getAccountTagValue(CosmosAsyncClient client) {
return client.getAccountTagValue();
}
@Override
public EnumSet<TagName> getMetricTagNames(CosmosAsyncClient client) {
return telemetryConfigAccessor
.getMetricTagNames(client.clientTelemetryConfig);
}
@Override
public EnumSet<MetricCategory> getMetricCategories(CosmosAsyncClient client) {
return telemetryConfigAccessor
.getMetricCategories(client.clientTelemetryConfig);
}
@Override
public boolean shouldEnableEmptyPageDiagnostics(CosmosAsyncClient client) {
return client.clientMetricsEnabled || client.isTransportLevelTracingEnabled();
}
@Override
public boolean isSendClientTelemetryToServiceEnabled(CosmosAsyncClient client) {
return client.isSendClientTelemetryToServiceEnabled;
}
@Override
public List<String> getPreferredRegions(CosmosAsyncClient client) {
return client.connectionPolicy.getPreferredRegions();
}
@Override
public boolean isEndpointDiscoveryEnabled(CosmosAsyncClient client) {
return client.connectionPolicy.isEndpointDiscoveryEnabled();
}
@Override
public CosmosMeterOptions getMeterOptions(CosmosAsyncClient client, CosmosMetricName name) {
return telemetryConfigAccessor
.getMeterOptions(client.clientTelemetryConfig, name);
}
@Override
public boolean isEffectiveContentResponseOnWriteEnabled(CosmosAsyncClient client,
Boolean requestOptionsContentResponseEnabled) {
if (requestOptionsContentResponseEnabled != null) {
return requestOptionsContentResponseEnabled;
}
return client.asyncDocumentClient.isContentResponseOnWriteEnabled();
}
@Override
public ConsistencyLevel getEffectiveConsistencyLevel(
CosmosAsyncClient client,
OperationType operationType,
ConsistencyLevel desiredConsistencyLevelOfOperation) {
return client.getEffectiveConsistencyLevel(operationType, desiredConsistencyLevelOfOperation);
}
@Override
public CosmosDiagnosticsThresholds getEffectiveDiagnosticsThresholds(
CosmosAsyncClient client,
CosmosDiagnosticsThresholds operationLevelThresholds) {
return client.getEffectiveDiagnosticsThresholds(operationLevelThresholds);
}
@Override
public DiagnosticsProvider getDiagnosticsProvider(CosmosAsyncClient client) {
return client.getDiagnosticsProvider();
}
}
);
}
static { initialize(); }
} | class CosmosAsyncClient implements Closeable {
private static final Logger logger = LoggerFactory.getLogger(CosmosAsyncClient.class);
private static final CosmosClientTelemetryConfig DEFAULT_TELEMETRY_CONFIG = new CosmosClientTelemetryConfig();
private static final ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor queryOptionsAccessor =
ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor();
private static final ImplementationBridgeHelpers.FeedResponseHelper.FeedResponseAccessor feedResponseAccessor =
ImplementationBridgeHelpers.FeedResponseHelper.getFeedResponseAccessor();
private static final ImplementationBridgeHelpers.CosmosClientTelemetryConfigHelper.CosmosClientTelemetryConfigAccessor
telemetryConfigAccessor = ImplementationBridgeHelpers
.CosmosClientTelemetryConfigHelper
.getCosmosClientTelemetryConfigAccessor();
private final AsyncDocumentClient asyncDocumentClient;
private final String serviceEndpoint;
private final ConnectionPolicy connectionPolicy;
private final ConsistencyLevel desiredConsistencyLevel;
private final AzureKeyCredential credential;
private final CosmosClientTelemetryConfig clientTelemetryConfig;
private final DiagnosticsProvider diagnosticsProvider;
private final Tag clientCorrelationTag;
private final String accountTagValue;
private final boolean clientMetricsEnabled;
private final boolean isSendClientTelemetryToServiceEnabled;
private final MeterRegistry clientMetricRegistrySnapshot;
private final CosmosContainerProactiveInitConfig proactiveContainerInitConfig;
private static final ImplementationBridgeHelpers.CosmosContainerIdentityHelper.CosmosContainerIdentityAccessor containerIdentityAccessor =
ImplementationBridgeHelpers.CosmosContainerIdentityHelper.getCosmosContainerIdentityAccessor();
private final ConsistencyLevel accountConsistencyLevel;
private final WriteRetryPolicy nonIdempotentWriteRetryPolicy;
CosmosAsyncClient(CosmosClientBuilder builder) {
Configs configs = builder.configs();
this.serviceEndpoint = builder.getEndpoint();
String keyOrResourceToken = builder.getKey();
this.connectionPolicy = builder.getConnectionPolicy();
this.desiredConsistencyLevel = builder.getConsistencyLevel();
List<CosmosPermissionProperties> permissions = builder.getPermissions();
CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver = builder.getAuthorizationTokenResolver();
this.credential = builder.getCredential();
TokenCredential tokenCredential = builder.getTokenCredential();
boolean sessionCapturingOverride = builder.isSessionCapturingOverrideEnabled();
boolean enableTransportClientSharing = builder.isConnectionSharingAcrossClientsEnabled();
this.proactiveContainerInitConfig = builder.getProactiveContainerInitConfig();
this.nonIdempotentWriteRetryPolicy = builder.getNonIdempotentWriteRetryPolicy();
CosmosClientTelemetryConfig effectiveTelemetryConfig = telemetryConfigAccessor
.createSnapshot(
builder.getClientTelemetryConfig(),
builder.isClientTelemetryEnabled());
this.clientTelemetryConfig = effectiveTelemetryConfig;
this.isSendClientTelemetryToServiceEnabled = telemetryConfigAccessor
.isSendClientTelemetryToServiceEnabled(effectiveTelemetryConfig);
boolean contentResponseOnWriteEnabled = builder.isContentResponseOnWriteEnabled();
ApiType apiType = builder.apiType();
String clientCorrelationId = telemetryConfigAccessor
.getClientCorrelationId(effectiveTelemetryConfig);
List<Permission> permissionList = new ArrayList<>();
if (permissions != null) {
permissionList =
permissions
.stream()
.map(ModelBridgeInternal::getPermission)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
this.asyncDocumentClient = new AsyncDocumentClient.Builder()
.withServiceEndpoint(this.serviceEndpoint)
.withMasterKeyOrResourceToken(keyOrResourceToken)
.withConnectionPolicy(this.connectionPolicy)
.withConsistencyLevel(this.desiredConsistencyLevel)
.withSessionCapturingOverride(sessionCapturingOverride)
.withConfigs(configs)
.withTokenResolver(cosmosAuthorizationTokenResolver)
.withCredential(this.credential)
.withTransportClientSharing(enableTransportClientSharing)
.withContentResponseOnWriteEnabled(contentResponseOnWriteEnabled)
.withTokenCredential(tokenCredential)
.withState(builder.metadataCaches())
.withPermissionFeed(permissionList)
.withApiType(apiType)
.withClientTelemetryConfig(this.clientTelemetryConfig)
.withClientCorrelationId(clientCorrelationId)
.build();
this.accountConsistencyLevel = this.asyncDocumentClient.getDefaultConsistencyLevelOfAccount();
String effectiveClientCorrelationId = this.asyncDocumentClient.getClientCorrelationId();
String machineId = this.asyncDocumentClient.getMachineId();
if (!Strings.isNullOrWhiteSpace(machineId) && machineId.startsWith(ClientTelemetry.VM_ID_PREFIX)) {
machineId = machineId.replace(ClientTelemetry.VM_ID_PREFIX, "vmId_");
if (Strings.isNullOrWhiteSpace(effectiveClientCorrelationId)) {
effectiveClientCorrelationId = machineId;
} else {
effectiveClientCorrelationId = String.format(
"%s_%s",
machineId,
effectiveClientCorrelationId);
}
}
this.clientCorrelationTag = Tag.of(
TagName.ClientCorrelationId.toString(),
ClientTelemetryMetrics.escape(effectiveClientCorrelationId));
this.clientMetricRegistrySnapshot = telemetryConfigAccessor
.getClientMetricRegistry(effectiveTelemetryConfig);
this.clientMetricsEnabled = clientMetricRegistrySnapshot != null;
CosmosMeterOptions cpuMeterOptions = telemetryConfigAccessor
.getMeterOptions(effectiveTelemetryConfig, CosmosMetricName.SYSTEM_CPU);
CosmosMeterOptions memoryMeterOptions = telemetryConfigAccessor
.getMeterOptions(effectiveTelemetryConfig, CosmosMetricName.SYSTEM_MEMORY_FREE);
if (clientMetricRegistrySnapshot != null) {
ClientTelemetryMetrics.add(clientMetricRegistrySnapshot, cpuMeterOptions, memoryMeterOptions);
}
this.accountTagValue = URI.create(this.serviceEndpoint).getHost().replace(
".documents.azure.com", ""
);
if (this.clientMetricsEnabled) {
telemetryConfigAccessor.setClientCorrelationTag(
effectiveTelemetryConfig,
this.clientCorrelationTag );
telemetryConfigAccessor.setAccountName(
effectiveTelemetryConfig,
this.accountTagValue
);
telemetryConfigAccessor.addDiagnosticsHandler(
effectiveTelemetryConfig,
new ClientMetricsDiagnosticsHandler(this)
);
}
if (this.isSendClientTelemetryToServiceEnabled) {
telemetryConfigAccessor.setClientTelemetry(
effectiveTelemetryConfig,
asyncDocumentClient.getClientTelemetry()
);
telemetryConfigAccessor.addDiagnosticsHandler(
effectiveTelemetryConfig,
new ClientTelemetryDiagnosticsHandler(effectiveTelemetryConfig)
);
}
this.diagnosticsProvider = new DiagnosticsProvider(
effectiveTelemetryConfig,
effectiveClientCorrelationId,
this.getUserAgent(),
this.connectionPolicy.getConnectionMode());
}
AsyncDocumentClient getContextClient() {
return this.asyncDocumentClient;
}
/**
* Monitor Cosmos client performance and resource utilization using the specified meter registry.
*
* @param registry meter registry to use for performance monitoring.
*/
static void setMonitorTelemetry(MeterRegistry registry) {
RntbdMetrics.add(registry);
}
/**
* Get the service endpoint.
*
* @return the service endpoint.
*/
String getServiceEndpoint() {
return serviceEndpoint;
}
/**
* Get the connection policy.
*
* @return {@link ConnectionPolicy}.
*/
ConnectionPolicy getConnectionPolicy() {
return connectionPolicy;
}
AsyncDocumentClient getDocClientWrapper() {
return asyncDocumentClient;
}
/**
* Gets the azure key credential.
*
* @return azure key credential.
*/
AzureKeyCredential credential() {
return credential;
}
/***
* Get the client telemetry config.
*
* @return the {@link CosmosClientTelemetryConfig}.
*/
CosmosClientTelemetryConfig getClientTelemetryConfig() {
return this.clientTelemetryConfig;
}
/**
* CREATE a Database if it does not already exist on the service.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param databaseProperties CosmosDatabaseProperties.
* @return a {@link Mono} containing the cosmos database response with the created or existing database or
* an error.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(CosmosDatabaseProperties databaseProperties) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(databaseProperties.getId()),
null, context));
}
/**
* Create a Database if it does not already exist on the service.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param id the id of the database.
* @return a {@link Mono} containing the cosmos database response with the created or existing database or
* an error.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id), null, context));
}
/**
* Create a Database if it does not already exist on the service.
* <br/>
* The throughputProperties will only be used if the specified database
* does not exist and therefor a new database will be created with throughputProperties.
* <br/>
* The {@link Mono} upon successful completion will contain a single cosmos database response with the
* created or existing database.
*
* @param id the id.
* @param throughputProperties the throughputProperties.
* @return the mono.
*/
public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id, ThroughputProperties throughputProperties) {
return withContext(context -> createDatabaseIfNotExistsInternal(getDatabase(id),
throughputProperties, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param options {@link CosmosDatabaseRequestOptions}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties,
CosmosDatabaseRequestOptions options) {
final CosmosDatabaseRequestOptions requestOptions = options == null ? new CosmosDatabaseRequestOptions() : options;
Database wrappedDatabase = new Database();
wrappedDatabase.setId(databaseProperties.getId());
return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties) {
return createDatabase(databaseProperties, new CosmosDatabaseRequestOptions());
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param id id of the database.
* @return a {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(String id) {
return createDatabase(new CosmosDatabaseProperties(id), new CosmosDatabaseRequestOptions());
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param throughputProperties the throughput properties for the database.
* @param options {@link CosmosDatabaseRequestOptions}.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties,
ThroughputProperties throughputProperties,
CosmosDatabaseRequestOptions options) {
if (options == null) {
options = new CosmosDatabaseRequestOptions();
}
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
Database wrappedDatabase = new Database();
wrappedDatabase.setId(databaseProperties.getId());
final CosmosDatabaseRequestOptions requestOptions = options;
return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context));
}
/**
* Creates a database.
* <br/>
* After subscription the operation will be performed.
* The {@link Mono} upon successful completion will contain a single resource response with the
* created database.
* In case of failure the {@link Mono} will error.
*
* @param databaseProperties {@link CosmosDatabaseProperties}.
* @param throughputProperties the throughput properties for the database.
* @return an {@link Mono} containing the single cosmos database response with the created database or an error.
*/
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties, ThroughputProperties throughputProperties) {
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
return createDatabase(databaseProperties, options);
}
/**
* Creates a database.
*
* @param id the id.
* @param throughputProperties the throughputProperties.
* @return the mono.
*/
public Mono<CosmosDatabaseResponse> createDatabase(String id, ThroughputProperties throughputProperties) {
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
return createDatabase(new CosmosDatabaseProperties(id), options);
}
/**
* Reads all databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param options {@link CosmosQueryRequestOptions}
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases(CosmosQueryRequestOptions options) {
return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> {
String spanName = "readAllDatabases";
CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions();
String operationId = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getQueryNameOrDefault(nonNullOptions, spanName);
pagedFluxOptions.setTracerInformation(
spanName,
null,
null,
operationId,
OperationType.ReadFeed,
ResourceType.Database,
this,
nonNullOptions.getConsistencyLevel(),
this.getEffectiveDiagnosticsThresholds(queryOptionsAccessor.getDiagnosticsThresholds(nonNullOptions)));
setContinuationTokenAndMaxItemCount(pagedFluxOptions, options);
return getDocClientWrapper().readDatabases(options)
.map(response ->
feedResponseAccessor.createFeedResponse(
ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()),
response.getResponseHeaders(),
response.getCosmosDiagnostics()));
});
}
/**
* Reads all databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases() {
return readAllDatabases(new CosmosQueryRequestOptions());
}
/**
* Query for databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param query the query.
* @param options the feed options.
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(String query, CosmosQueryRequestOptions options) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
return queryDatabasesInternal(new SqlQuerySpec(query), options);
}
/**
* Query for databases.
* <br/>
* After subscription the operation will be performed.
* The {@link CosmosPagedFlux} will contain one or several feed response of the read databases.
* In case of failure the {@link CosmosPagedFlux} will error.
*
* @param querySpec the SQL query specification.
* @param options the feed options.
* @return a {@link CosmosPagedFlux} containing one or several feed response pages of read databases or an error.
*/
public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) {
if (options == null) {
options = new CosmosQueryRequestOptions();
}
return queryDatabasesInternal(querySpec, options);
}
/**
* Gets a database object without making a service call.
*
* @param id name of the database.
* @return {@link CosmosAsyncDatabase}.
*/
public CosmosAsyncDatabase getDatabase(String id) {
return new CosmosAsyncDatabase(id, this);
}
/**
* Close this {@link CosmosAsyncClient} instance and cleans up the resources.
*/
@Override
public void close() {
if (this.clientMetricRegistrySnapshot != null) {
ClientTelemetryMetrics.remove(this.clientMetricRegistrySnapshot);
}
asyncDocumentClient.close();
}
DiagnosticsProvider getDiagnosticsProvider() {
return this.diagnosticsProvider;
}
/**
* Enable throughput control group.
*
* @param group Throughput control group going to be enabled.
* @param throughputQueryMono The throughput query mono.
*/
void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) {
checkNotNull(group, "Throughput control group cannot be null");
this.asyncDocumentClient.enableThroughputControlGroup(group, throughputQueryMono);
}
/***
* Configure fault injector provider.
*
* @param injectorProvider the injector provider.
*/
void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) {
checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null");
this.asyncDocumentClient.configureFaultInjectorProvider(injectorProvider);
}
/**
* Create global throughput control config builder which will be used to build {@link GlobalThroughputControlConfig}.
*
* @param databaseId The database id of the control container.
* @param containerId The container id of the control container.
* @return A {@link GlobalThroughputControlConfigBuilder}.
*/
public GlobalThroughputControlConfigBuilder createGlobalThroughputControlConfigBuilder(String databaseId, String containerId) {
return new GlobalThroughputControlConfigBuilder(this, databaseId, containerId);
}
WriteRetryPolicy getNonIdempotentWriteRetryPolicy() {
return this.nonIdempotentWriteRetryPolicy;
}
void openConnectionsAndInitCaches() {
blockVoidFlux(asyncDocumentClient.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig));
}
void openConnectionsAndInitCaches(Duration aggressiveWarmupDuration) {
Flux<Void> submitOpenConnectionTasksFlux = asyncDocumentClient.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig);
blockVoidFlux(wrapSourceFluxAndSoftCompleteAfterTimeout(submitOpenConnectionTasksFlux, aggressiveWarmupDuration));
}
private Flux<Void> wrapSourceFluxAndSoftCompleteAfterTimeout(Flux<Void> source, Duration timeout) {
return Flux.<Void>create(sink -> {
source.subscribe(t -> sink.next(t));
})
.take(timeout);
}
private CosmosPagedFlux<CosmosDatabaseProperties> queryDatabasesInternal(
SqlQuerySpec querySpec,
CosmosQueryRequestOptions options){
return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> {
String spanName = "queryDatabases";
CosmosQueryRequestOptions nonNullOptions = options != null ? options : new CosmosQueryRequestOptions();
String operationId = ImplementationBridgeHelpers
.CosmosQueryRequestOptionsHelper
.getCosmosQueryRequestOptionsAccessor()
.getQueryNameOrDefault(nonNullOptions, spanName);
pagedFluxOptions.setTracerInformation(
spanName,
null,
null,
operationId,
OperationType.Query,
ResourceType.Database,
this,
nonNullOptions.getConsistencyLevel(),
this.getEffectiveDiagnosticsThresholds(queryOptionsAccessor.getDiagnosticsThresholds(nonNullOptions)));
setContinuationTokenAndMaxItemCount(pagedFluxOptions, options);
return getDocClientWrapper().queryDatabases(querySpec, options)
.map(response -> feedResponseAccessor.createFeedResponse(
ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()),
response.getResponseHeaders(),
response.getCosmosDiagnostics()));
});
}
private Mono<CosmosDatabaseResponse> createDatabaseIfNotExistsInternal(CosmosAsyncDatabase database,
ThroughputProperties throughputProperties, Context context) {
String spanName = "createDatabaseIfNotExists." + database.getId();
Context nestedContext = context.addData(
DiagnosticsProvider.COSMOS_CALL_DEPTH,
DiagnosticsProvider.COSMOS_CALL_DEPTH_VAL);
CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
Mono<CosmosDatabaseResponse> responseMono = database.readInternal(new CosmosDatabaseRequestOptions(),
nestedContext).onErrorResume(exception -> {
final Throwable unwrappedException = Exceptions.unwrap(exception);
if (unwrappedException instanceof CosmosException) {
final CosmosException cosmosException = (CosmosException) unwrappedException;
if (cosmosException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) {
if (throughputProperties != null) {
ModelBridgeInternal.setThroughputProperties(options, throughputProperties);
}
Database wrappedDatabase = new Database();
wrappedDatabase.setId(database.getId());
return createDatabaseInternal(wrappedDatabase,
options, nestedContext);
}
}
return Mono.error(unwrappedException);
});
RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options);
return this.diagnosticsProvider.traceEnabledCosmosResponsePublisher(
responseMono,
context,
spanName,
database.getId(),
null,
this,
null,
OperationType.Create,
ResourceType.Database,
this.getEffectiveDiagnosticsThresholds(requestOptions.getDiagnosticsThresholds()));
}
private Mono<CosmosDatabaseResponse> createDatabaseInternal(Database database, CosmosDatabaseRequestOptions options,
Context context) {
String spanName = "createDatabase." + database.getId();
RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options);
Mono<CosmosDatabaseResponse> responseMono = asyncDocumentClient.createDatabase(database, requestOptions)
.map(ModelBridgeInternal::createCosmosDatabaseResponse)
.single();
return this.diagnosticsProvider
.traceEnabledCosmosResponsePublisher(
responseMono,
context,
spanName,
database.getId(),
null,
this,
null,
OperationType.Create,
ResourceType.Database,
this.getEffectiveDiagnosticsThresholds(requestOptions.getDiagnosticsThresholds()));
}
private ConsistencyLevel getEffectiveConsistencyLevel(
OperationType operationType,
ConsistencyLevel desiredConsistencyLevelOfOperation) {
if (operationType.isWriteOperation()) {
return this.accountConsistencyLevel;
}
if (desiredConsistencyLevelOfOperation != null) {
return desiredConsistencyLevelOfOperation;
}
if (this.desiredConsistencyLevel != null) {
return desiredConsistencyLevel;
}
return this.accountConsistencyLevel;
}
CosmosDiagnosticsThresholds getEffectiveDiagnosticsThresholds(
CosmosDiagnosticsThresholds operationLevelThresholds) {
if (operationLevelThresholds != null) {
return operationLevelThresholds;
}
if (this.clientTelemetryConfig == null) {
return new CosmosDiagnosticsThresholds();
}
CosmosDiagnosticsThresholds clientLevelThresholds =
telemetryConfigAccessor.getDiagnosticsThresholds(this.clientTelemetryConfig);
return clientLevelThresholds != null ? clientLevelThresholds : new CosmosDiagnosticsThresholds();
}
boolean isTransportLevelTracingEnabled() {
CosmosClientTelemetryConfig effectiveConfig = this.clientTelemetryConfig != null ?
this.clientTelemetryConfig
: DEFAULT_TELEMETRY_CONFIG;
if (telemetryConfigAccessor.isLegacyTracingEnabled(effectiveConfig)) {
return false;
}
if (this.getConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) {
return false;
}
return telemetryConfigAccessor.isTransportLevelTracingEnabled(effectiveConfig);
}
void recordOpenConnectionsAndInitCachesCompleted(List<CosmosContainerIdentity> cosmosContainerIdentities) {
this.asyncDocumentClient.recordOpenConnectionsAndInitCachesCompleted(cosmosContainerIdentities);
}
void recordOpenConnectionsAndInitCachesStarted(List<CosmosContainerIdentity> cosmosContainerIdentities) {
this.asyncDocumentClient.recordOpenConnectionsAndInitCachesStarted(cosmosContainerIdentities);
}
String getAccountTagValue() {
return this.accountTagValue;
}
Tag getClientCorrelationTag() {
return this.clientCorrelationTag;
}
String getUserAgent() {
return this.asyncDocumentClient.getUserAgent();
}
static void initialize() {
ImplementationBridgeHelpers.CosmosAsyncClientHelper.setCosmosAsyncClientAccessor(
new ImplementationBridgeHelpers.CosmosAsyncClientHelper.CosmosAsyncClientAccessor() {
@Override
public Tag getClientCorrelationTag(CosmosAsyncClient client) {
return client.getClientCorrelationTag();
}
@Override
public String getAccountTagValue(CosmosAsyncClient client) {
return client.getAccountTagValue();
}
@Override
public EnumSet<TagName> getMetricTagNames(CosmosAsyncClient client) {
return telemetryConfigAccessor
.getMetricTagNames(client.clientTelemetryConfig);
}
@Override
public EnumSet<MetricCategory> getMetricCategories(CosmosAsyncClient client) {
return telemetryConfigAccessor
.getMetricCategories(client.clientTelemetryConfig);
}
@Override
public boolean shouldEnableEmptyPageDiagnostics(CosmosAsyncClient client) {
return client.clientMetricsEnabled || client.isTransportLevelTracingEnabled();
}
@Override
public boolean isSendClientTelemetryToServiceEnabled(CosmosAsyncClient client) {
return client.isSendClientTelemetryToServiceEnabled;
}
@Override
public List<String> getPreferredRegions(CosmosAsyncClient client) {
return client.connectionPolicy.getPreferredRegions();
}
@Override
public boolean isEndpointDiscoveryEnabled(CosmosAsyncClient client) {
return client.connectionPolicy.isEndpointDiscoveryEnabled();
}
@Override
public CosmosMeterOptions getMeterOptions(CosmosAsyncClient client, CosmosMetricName name) {
return telemetryConfigAccessor
.getMeterOptions(client.clientTelemetryConfig, name);
}
@Override
public boolean isEffectiveContentResponseOnWriteEnabled(CosmosAsyncClient client,
Boolean requestOptionsContentResponseEnabled) {
if (requestOptionsContentResponseEnabled != null) {
return requestOptionsContentResponseEnabled;
}
return client.asyncDocumentClient.isContentResponseOnWriteEnabled();
}
@Override
public ConsistencyLevel getEffectiveConsistencyLevel(
CosmosAsyncClient client,
OperationType operationType,
ConsistencyLevel desiredConsistencyLevelOfOperation) {
return client.getEffectiveConsistencyLevel(operationType, desiredConsistencyLevelOfOperation);
}
@Override
public CosmosDiagnosticsThresholds getEffectiveDiagnosticsThresholds(
CosmosAsyncClient client,
CosmosDiagnosticsThresholds operationLevelThresholds) {
return client.getEffectiveDiagnosticsThresholds(operationLevelThresholds);
}
@Override
public DiagnosticsProvider getDiagnosticsProvider(CosmosAsyncClient client) {
return client.getDiagnosticsProvider();
}
}
);
}
static { initialize(); }
} |
indentation (and the next few too) | public void testValidIdentityEndpointMSICodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.APP_SERVICE)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForMSICodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
} | .setConfiguration(configuration); | public void testValidIdentityEndpointMSICodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.APP_SERVICE)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForMSICodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
});
}
@Test
public void testValidCertificate() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testPemCertificate() {
String pemPath;
URL pemUrl = getClass().getClassLoader().getResource("certificate.pem");
if (pemUrl.getPath().contains(":")) {
pemPath = pemUrl.getPath().substring(1);
} else {
pemPath = pemUrl.getPath();
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidCertificatePassword() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.verifyErrorSatisfies(e -> Assert.assertTrue(e.getMessage().contains("password was incorrect")));
});
}
@Test
public void testValidDeviceCodeFlow() {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.identityClientOptions(options)
.build();
StepVerifier.create(client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testValidServiceFabricCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
String thumbprint = "950a2c88d57b5e19ac5119315f9ec199ff3cb823";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret)
.put("IDENTITY_SERVER_THUMBPRINT", thumbprint));
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.toEpochSecond() + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.SERVICE_FABRIC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret)
.setIdentityServerThumbprint(thumbprint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForServiceFabricCodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointSecretArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(401, () -> {
client.getTokenFromTargetManagedIdentity(request).block();
});
}
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointResponseCodeArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(200, () -> client.getTokenFromTargetManagedIdentity(request).block());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("MSI_ENDPOINT", endpoint)
.put("MSI_SECRET", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(IdentityConstants.DEFAULT_IMDS_ENDPOINT, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testCustomIMDSCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put(Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(endpoint, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUserRefreshTokenflow() {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUsernamePasswordCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testBrowserAuthenicationCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
mockForBrowserAuthenticationCodeFlow(token, request, expiresOn, () -> {
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567, null, null))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testOpenUrl() throws Exception {
try (MockedStatic<Runtime> runtimeMockedStatic = mockStatic(Runtime.class)) {
Runtime runtimeMock = mock(Runtime.class);
runtimeMockedStatic.when(Runtime::getRuntime).thenReturn(runtimeMock);
when(runtimeMock.exec(anyString())).thenReturn(null);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
verify(runtimeMock).exec(ArgumentMatchers.contains("https:
}
}
@Test
public void testAuthWithManagedIdentityFlow() {
String secret = "SYSTEM-ASSIGNED-CLIENT-SECRET";
String clientId = "SYSTEM-ASSIGNED-CLIENT-ID";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForManagedIdentityFlow(secret, clientId, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID)
.clientId(clientId)
.clientSecret(secret)
.identityClientOptions(new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM))
.build();
AccessToken token = client.authenticateWithManagedIdentityConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
});
}
/****** mocks ******/
private void mockForManagedIdentityFlow(String secret, String clientId, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
when(builder.appTokenProvider(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(clientId), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(clientId)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientCertificate) cred) != null))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> ((IClientCertificate) cred) == null))).thenThrow(new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientCertificate.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
when(builder.build()).thenReturn(application);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<CertificateUtil> certificateUtilMock = mockStatic(CertificateUtil.class);
MockedStatic<ClientCredentialFactory> clientCredentialFactoryMock = mockStatic(ClientCredentialFactory.class);
MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class);
MockedConstruction<ConfidentialClientApplication.Builder> builderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
ConfidentialClientApplication application = mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})
) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), any())).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any())).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
PrivateKey privateKey = mock(PrivateKey.class);
IClientCertificate clientCertificate = mock(IClientCertificate.class);
certificateUtilMock.when(() -> CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
clientCredentialFactoryMock.when(() -> ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class))).thenReturn(clientCertificate);
test.run();
Assert.assertNotNull(builderMock);
}
}
private void mockForMSICodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForServiceFabricCodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpsURLConnection huc = mock(HttpsURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setSSLSocketFactory(any());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForArcCodeFlow(int responseCode, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestProperty(anyString(), anyString());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
when(huc.getInputStream()).thenThrow(new IOException());
when(huc.getResponseCode()).thenReturn(responseCode);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForIMDSCodeFlow(String endpoint, String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setConnectTimeout(anyInt());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForBrowserAuthenticationCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(InteractiveRequestParameters.class))).thenAnswer(invocation -> {
InteractiveRequestParameters argument = (InteractiveRequestParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class))).thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUserRefreshTokenFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any())).thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
});
}
@Test
public void testValidCertificate() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testPemCertificate() {
String pemPath;
URL pemUrl = getClass().getClassLoader().getResource("certificate.pem");
if (pemUrl.getPath().contains(":")) {
pemPath = pemUrl.getPath().substring(1);
} else {
pemPath = pemUrl.getPath();
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidCertificatePassword() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.verifyErrorSatisfies(e -> Assert.assertTrue(e.getMessage().contains("password was incorrect")));
});
}
@Test
public void testValidDeviceCodeFlow() {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.identityClientOptions(options)
.build();
StepVerifier.create(client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testValidServiceFabricCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
String thumbprint = "950a2c88d57b5e19ac5119315f9ec199ff3cb823";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret)
.put("IDENTITY_SERVER_THUMBPRINT", thumbprint));
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.toEpochSecond() + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.SERVICE_FABRIC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret)
.setIdentityServerThumbprint(thumbprint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForServiceFabricCodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointSecretArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(401, () -> {
client.getTokenFromTargetManagedIdentity(request).block();
});
}
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointResponseCodeArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(200, () -> client.getTokenFromTargetManagedIdentity(request).block());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("MSI_ENDPOINT", endpoint)
.put("MSI_SECRET", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(IdentityConstants.DEFAULT_IMDS_ENDPOINT, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testCustomIMDSCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put(Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(endpoint, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUserRefreshTokenflow() {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUsernamePasswordCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testBrowserAuthenicationCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
mockForBrowserAuthenticationCodeFlow(token, request, expiresOn, () -> {
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567, null, null))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testOpenUrl() throws Exception {
try (MockedStatic<Runtime> runtimeMockedStatic = mockStatic(Runtime.class)) {
Runtime runtimeMock = mock(Runtime.class);
runtimeMockedStatic.when(Runtime::getRuntime).thenReturn(runtimeMock);
when(runtimeMock.exec(anyString())).thenReturn(null);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
verify(runtimeMock).exec(ArgumentMatchers.contains("https:
}
}
@Test
public void testAuthWithManagedIdentityFlow() {
String secret = "SYSTEM-ASSIGNED-CLIENT-SECRET";
String clientId = "SYSTEM-ASSIGNED-CLIENT-ID";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForManagedIdentityFlow(secret, clientId, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID)
.clientId(clientId)
.clientSecret(secret)
.identityClientOptions(new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM))
.build();
AccessToken token = client.authenticateWithManagedIdentityConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
});
}
/****** mocks ******/
private void mockForManagedIdentityFlow(String secret, String clientId, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
when(builder.appTokenProvider(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(clientId), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(clientId)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientCertificate) cred) != null))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> ((IClientCertificate) cred) == null))).thenThrow(new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientCertificate.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
when(builder.build()).thenReturn(application);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<CertificateUtil> certificateUtilMock = mockStatic(CertificateUtil.class);
MockedStatic<ClientCredentialFactory> clientCredentialFactoryMock = mockStatic(ClientCredentialFactory.class);
MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class);
MockedConstruction<ConfidentialClientApplication.Builder> builderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
ConfidentialClientApplication application = mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})
) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), any())).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any())).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
PrivateKey privateKey = mock(PrivateKey.class);
IClientCertificate clientCertificate = mock(IClientCertificate.class);
certificateUtilMock.when(() -> CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
clientCredentialFactoryMock.when(() -> ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class))).thenReturn(clientCertificate);
test.run();
Assert.assertNotNull(builderMock);
}
}
private void mockForMSICodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForServiceFabricCodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpsURLConnection huc = mock(HttpsURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setSSLSocketFactory(any());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForArcCodeFlow(int responseCode, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestProperty(anyString(), anyString());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
when(huc.getInputStream()).thenThrow(new IOException());
when(huc.getResponseCode()).thenReturn(responseCode);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForIMDSCodeFlow(String endpoint, String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setConnectTimeout(anyInt());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForBrowserAuthenticationCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(InteractiveRequestParameters.class))).thenAnswer(invocation -> {
InteractiveRequestParameters argument = (InteractiveRequestParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class))).thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUserRefreshTokenFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any())).thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
} |
This is the correct indentation as the deeper indented lines are creating an Object which closes before setting configuration | public void testValidIdentityEndpointMSICodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.APP_SERVICE)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForMSICodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
} | .setConfiguration(configuration); | public void testValidIdentityEndpointMSICodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.APP_SERVICE)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForMSICodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
});
}
@Test
public void testValidCertificate() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testPemCertificate() {
String pemPath;
URL pemUrl = getClass().getClassLoader().getResource("certificate.pem");
if (pemUrl.getPath().contains(":")) {
pemPath = pemUrl.getPath().substring(1);
} else {
pemPath = pemUrl.getPath();
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidCertificatePassword() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.verifyErrorSatisfies(e -> Assert.assertTrue(e.getMessage().contains("password was incorrect")));
});
}
@Test
public void testValidDeviceCodeFlow() {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.identityClientOptions(options)
.build();
StepVerifier.create(client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testValidServiceFabricCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
String thumbprint = "950a2c88d57b5e19ac5119315f9ec199ff3cb823";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret)
.put("IDENTITY_SERVER_THUMBPRINT", thumbprint));
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.toEpochSecond() + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.SERVICE_FABRIC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret)
.setIdentityServerThumbprint(thumbprint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForServiceFabricCodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointSecretArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(401, () -> {
client.getTokenFromTargetManagedIdentity(request).block();
});
}
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointResponseCodeArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(200, () -> client.getTokenFromTargetManagedIdentity(request).block());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("MSI_ENDPOINT", endpoint)
.put("MSI_SECRET", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(IdentityConstants.DEFAULT_IMDS_ENDPOINT, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testCustomIMDSCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put(Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(endpoint, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUserRefreshTokenflow() {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUsernamePasswordCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testBrowserAuthenicationCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
mockForBrowserAuthenticationCodeFlow(token, request, expiresOn, () -> {
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567, null, null))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testOpenUrl() throws Exception {
try (MockedStatic<Runtime> runtimeMockedStatic = mockStatic(Runtime.class)) {
Runtime runtimeMock = mock(Runtime.class);
runtimeMockedStatic.when(Runtime::getRuntime).thenReturn(runtimeMock);
when(runtimeMock.exec(anyString())).thenReturn(null);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
verify(runtimeMock).exec(ArgumentMatchers.contains("https:
}
}
@Test
public void testAuthWithManagedIdentityFlow() {
String secret = "SYSTEM-ASSIGNED-CLIENT-SECRET";
String clientId = "SYSTEM-ASSIGNED-CLIENT-ID";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForManagedIdentityFlow(secret, clientId, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID)
.clientId(clientId)
.clientSecret(secret)
.identityClientOptions(new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM))
.build();
AccessToken token = client.authenticateWithManagedIdentityConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
});
}
/****** mocks ******/
private void mockForManagedIdentityFlow(String secret, String clientId, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
when(builder.appTokenProvider(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(clientId), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(clientId)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientCertificate) cred) != null))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> ((IClientCertificate) cred) == null))).thenThrow(new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientCertificate.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
when(builder.build()).thenReturn(application);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<CertificateUtil> certificateUtilMock = mockStatic(CertificateUtil.class);
MockedStatic<ClientCredentialFactory> clientCredentialFactoryMock = mockStatic(ClientCredentialFactory.class);
MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class);
MockedConstruction<ConfidentialClientApplication.Builder> builderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
ConfidentialClientApplication application = mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})
) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), any())).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any())).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
PrivateKey privateKey = mock(PrivateKey.class);
IClientCertificate clientCertificate = mock(IClientCertificate.class);
certificateUtilMock.when(() -> CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
clientCredentialFactoryMock.when(() -> ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class))).thenReturn(clientCertificate);
test.run();
Assert.assertNotNull(builderMock);
}
}
private void mockForMSICodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForServiceFabricCodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpsURLConnection huc = mock(HttpsURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setSSLSocketFactory(any());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForArcCodeFlow(int responseCode, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestProperty(anyString(), anyString());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
when(huc.getInputStream()).thenThrow(new IOException());
when(huc.getResponseCode()).thenReturn(responseCode);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForIMDSCodeFlow(String endpoint, String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setConnectTimeout(anyInt());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForBrowserAuthenticationCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(InteractiveRequestParameters.class))).thenAnswer(invocation -> {
InteractiveRequestParameters argument = (InteractiveRequestParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class))).thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUserRefreshTokenFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any())).thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
});
}
@Test
public void testValidCertificate() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testPemCertificate() {
String pemPath;
URL pemUrl = getClass().getClassLoader().getResource("certificate.pem");
if (pemUrl.getPath().contains(":")) {
pemPath = pemUrl.getPath().substring(1);
} else {
pemPath = pemUrl.getPath();
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidCertificatePassword() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.verifyErrorSatisfies(e -> Assert.assertTrue(e.getMessage().contains("password was incorrect")));
});
}
@Test
public void testValidDeviceCodeFlow() {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.identityClientOptions(options)
.build();
StepVerifier.create(client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testValidServiceFabricCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
String thumbprint = "950a2c88d57b5e19ac5119315f9ec199ff3cb823";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret)
.put("IDENTITY_SERVER_THUMBPRINT", thumbprint));
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.toEpochSecond() + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.SERVICE_FABRIC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret)
.setIdentityServerThumbprint(thumbprint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForServiceFabricCodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointSecretArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(401, () -> {
client.getTokenFromTargetManagedIdentity(request).block();
});
}
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointResponseCodeArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(200, () -> client.getTokenFromTargetManagedIdentity(request).block());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("MSI_ENDPOINT", endpoint)
.put("MSI_SECRET", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(IdentityConstants.DEFAULT_IMDS_ENDPOINT, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testCustomIMDSCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put(Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(endpoint, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUserRefreshTokenflow() {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUsernamePasswordCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testBrowserAuthenicationCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
mockForBrowserAuthenticationCodeFlow(token, request, expiresOn, () -> {
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567, null, null))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testOpenUrl() throws Exception {
try (MockedStatic<Runtime> runtimeMockedStatic = mockStatic(Runtime.class)) {
Runtime runtimeMock = mock(Runtime.class);
runtimeMockedStatic.when(Runtime::getRuntime).thenReturn(runtimeMock);
when(runtimeMock.exec(anyString())).thenReturn(null);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
verify(runtimeMock).exec(ArgumentMatchers.contains("https:
}
}
@Test
public void testAuthWithManagedIdentityFlow() {
String secret = "SYSTEM-ASSIGNED-CLIENT-SECRET";
String clientId = "SYSTEM-ASSIGNED-CLIENT-ID";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForManagedIdentityFlow(secret, clientId, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID)
.clientId(clientId)
.clientSecret(secret)
.identityClientOptions(new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM))
.build();
AccessToken token = client.authenticateWithManagedIdentityConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
});
}
/****** mocks ******/
private void mockForManagedIdentityFlow(String secret, String clientId, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
when(builder.appTokenProvider(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(clientId), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(clientId)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientCertificate) cred) != null))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> ((IClientCertificate) cred) == null))).thenThrow(new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientCertificate.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
when(builder.build()).thenReturn(application);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<CertificateUtil> certificateUtilMock = mockStatic(CertificateUtil.class);
MockedStatic<ClientCredentialFactory> clientCredentialFactoryMock = mockStatic(ClientCredentialFactory.class);
MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class);
MockedConstruction<ConfidentialClientApplication.Builder> builderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
ConfidentialClientApplication application = mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})
) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), any())).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any())).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
PrivateKey privateKey = mock(PrivateKey.class);
IClientCertificate clientCertificate = mock(IClientCertificate.class);
certificateUtilMock.when(() -> CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
clientCredentialFactoryMock.when(() -> ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class))).thenReturn(clientCertificate);
test.run();
Assert.assertNotNull(builderMock);
}
}
private void mockForMSICodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForServiceFabricCodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpsURLConnection huc = mock(HttpsURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setSSLSocketFactory(any());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForArcCodeFlow(int responseCode, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestProperty(anyString(), anyString());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
when(huc.getInputStream()).thenThrow(new IOException());
when(huc.getResponseCode()).thenReturn(responseCode);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForIMDSCodeFlow(String endpoint, String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setConnectTimeout(anyInt());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForBrowserAuthenticationCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(InteractiveRequestParameters.class))).thenAnswer(invocation -> {
InteractiveRequestParameters argument = (InteractiveRequestParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class))).thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUserRefreshTokenFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any())).thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
} |
Oh I missed the second constructor, my bad. | public void testValidIdentityEndpointMSICodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.APP_SERVICE)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForMSICodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
} | .setConfiguration(configuration); | public void testValidIdentityEndpointMSICodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.APP_SERVICE)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForMSICodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
});
}
@Test
public void testValidCertificate() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testPemCertificate() {
String pemPath;
URL pemUrl = getClass().getClassLoader().getResource("certificate.pem");
if (pemUrl.getPath().contains(":")) {
pemPath = pemUrl.getPath().substring(1);
} else {
pemPath = pemUrl.getPath();
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidCertificatePassword() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.verifyErrorSatisfies(e -> Assert.assertTrue(e.getMessage().contains("password was incorrect")));
});
}
@Test
public void testValidDeviceCodeFlow() {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.identityClientOptions(options)
.build();
StepVerifier.create(client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testValidServiceFabricCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
String thumbprint = "950a2c88d57b5e19ac5119315f9ec199ff3cb823";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret)
.put("IDENTITY_SERVER_THUMBPRINT", thumbprint));
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.toEpochSecond() + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.SERVICE_FABRIC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret)
.setIdentityServerThumbprint(thumbprint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForServiceFabricCodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointSecretArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(401, () -> {
client.getTokenFromTargetManagedIdentity(request).block();
});
}
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointResponseCodeArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(200, () -> client.getTokenFromTargetManagedIdentity(request).block());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("MSI_ENDPOINT", endpoint)
.put("MSI_SECRET", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(IdentityConstants.DEFAULT_IMDS_ENDPOINT, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testCustomIMDSCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put(Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(endpoint, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUserRefreshTokenflow() {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUsernamePasswordCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testBrowserAuthenicationCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
mockForBrowserAuthenticationCodeFlow(token, request, expiresOn, () -> {
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567, null, null))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testOpenUrl() throws Exception {
try (MockedStatic<Runtime> runtimeMockedStatic = mockStatic(Runtime.class)) {
Runtime runtimeMock = mock(Runtime.class);
runtimeMockedStatic.when(Runtime::getRuntime).thenReturn(runtimeMock);
when(runtimeMock.exec(anyString())).thenReturn(null);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
verify(runtimeMock).exec(ArgumentMatchers.contains("https:
}
}
@Test
public void testAuthWithManagedIdentityFlow() {
String secret = "SYSTEM-ASSIGNED-CLIENT-SECRET";
String clientId = "SYSTEM-ASSIGNED-CLIENT-ID";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForManagedIdentityFlow(secret, clientId, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID)
.clientId(clientId)
.clientSecret(secret)
.identityClientOptions(new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM))
.build();
AccessToken token = client.authenticateWithManagedIdentityConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
});
}
/****** mocks ******/
private void mockForManagedIdentityFlow(String secret, String clientId, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
when(builder.appTokenProvider(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(clientId), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(clientId)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientCertificate) cred) != null))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> ((IClientCertificate) cred) == null))).thenThrow(new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientCertificate.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
when(builder.build()).thenReturn(application);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<CertificateUtil> certificateUtilMock = mockStatic(CertificateUtil.class);
MockedStatic<ClientCredentialFactory> clientCredentialFactoryMock = mockStatic(ClientCredentialFactory.class);
MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class);
MockedConstruction<ConfidentialClientApplication.Builder> builderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
ConfidentialClientApplication application = mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})
) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), any())).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any())).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
PrivateKey privateKey = mock(PrivateKey.class);
IClientCertificate clientCertificate = mock(IClientCertificate.class);
certificateUtilMock.when(() -> CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
clientCredentialFactoryMock.when(() -> ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class))).thenReturn(clientCertificate);
test.run();
Assert.assertNotNull(builderMock);
}
}
private void mockForMSICodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForServiceFabricCodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpsURLConnection huc = mock(HttpsURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setSSLSocketFactory(any());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForArcCodeFlow(int responseCode, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestProperty(anyString(), anyString());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
when(huc.getInputStream()).thenThrow(new IOException());
when(huc.getResponseCode()).thenReturn(responseCode);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForIMDSCodeFlow(String endpoint, String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setConnectTimeout(anyInt());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForBrowserAuthenticationCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(InteractiveRequestParameters.class))).thenAnswer(invocation -> {
InteractiveRequestParameters argument = (InteractiveRequestParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class))).thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUserRefreshTokenFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any())).thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidSecret() {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn, () -> {
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
});
}
@Test
public void testValidCertificate() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testPemCertificate() {
String pemPath;
URL pemUrl = getClass().getClassLoader().getResource("certificate.pem");
if (pemUrl.getPath().contains(":")) {
pemPath = pemUrl.getPath().substring(1);
} else {
pemPath = pemUrl.getPath();
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testInvalidCertificatePassword() {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
StepVerifier.create(client.authenticateWithConfidentialClient(request))
.verifyErrorSatisfies(e -> Assert.assertTrue(e.getMessage().contains("password was incorrect")));
});
}
@Test
public void testValidDeviceCodeFlow() {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.identityClientOptions(options)
.build();
StepVerifier.create(client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }))
.assertNext(token -> {
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testValidServiceFabricCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
String thumbprint = "950a2c88d57b5e19ac5119315f9ec199ff3cb823";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint)
.put("IDENTITY_HEADER", secret)
.put("IDENTITY_SERVER_THUMBPRINT", thumbprint));
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.toEpochSecond() + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.SERVICE_FABRIC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint)
.setIdentityHeader(secret)
.setIdentityServerThumbprint(thumbprint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForServiceFabricCodeFlow(tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointSecretArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(401, () -> {
client.getTokenFromTargetManagedIdentity(request).block();
});
}
@Test(expected = ClientAuthenticationException.class)
public void testInValidIdentityEndpointResponseCodeArcCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("IDENTITY_ENDPOINT", endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.ARC)
.setManagedIdentityParameters(new ManagedIdentityParameters()
.setIdentityEndpoint(endpoint))
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForArcCodeFlow(200, () -> client.getTokenFromTargetManagedIdentity(request).block());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
String endpoint = "http:
String secret = "secret";
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put("MSI_ENDPOINT", endpoint)
.put("MSI_SECRET", secret));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(IdentityConstants.DEFAULT_IMDS_ENDPOINT, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testCustomIMDSCodeFlow() throws Exception {
String endpoint = "http:
Configuration configuration = TestUtils.createTestConfiguration(new TestConfigurationSource()
.put(Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, endpoint));
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
IdentityClientOptions options = new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM)
.setConfiguration(configuration);
IdentityClient client = new IdentityClientBuilder().identityClientOptions(options).build();
mockForIMDSCodeFlow(endpoint, tokenJson, () -> {
StepVerifier.create(client.getTokenFromTargetManagedIdentity(request))
.assertNext(token -> {
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
})
.verifyComplete();
});
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUserRefreshTokenflow() {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testUsernamePasswordCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn, () -> {
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testBrowserAuthenicationCodeFlow() {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
mockForBrowserAuthenticationCodeFlow(token, request, expiresOn, () -> {
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567, null, null))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
});
}
@Test
public void testOpenUrl() throws Exception {
try (MockedStatic<Runtime> runtimeMockedStatic = mockStatic(Runtime.class)) {
Runtime runtimeMock = mock(Runtime.class);
runtimeMockedStatic.when(Runtime::getRuntime).thenReturn(runtimeMock);
when(runtimeMock.exec(anyString())).thenReturn(null);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
verify(runtimeMock).exec(ArgumentMatchers.contains("https:
}
}
@Test
public void testAuthWithManagedIdentityFlow() {
String secret = "SYSTEM-ASSIGNED-CLIENT-SECRET";
String clientId = "SYSTEM-ASSIGNED-CLIENT-ID";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForManagedIdentityFlow(secret, clientId, request, accessToken, expiresOn, () -> {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID)
.clientId(clientId)
.clientSecret(secret)
.identityClientOptions(new IdentityClientOptions()
.setManagedIdentityType(ManagedIdentityType.VM))
.build();
AccessToken token = client.authenticateWithManagedIdentityConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
});
}
/****** mocks ******/
private void mockForManagedIdentityFlow(String secret, String clientId, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
when(builder.appTokenProvider(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(clientId), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(clientId)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientSecret) cred).clientSecret().equals(secret)))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> !((IClientSecret) cred).clientSecret().equals(secret)))).thenThrow(new MsalServiceException("Invalid clientSecret", "InvalidClientSecret"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientSecret.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class); MockedConstruction<ConfidentialClientApplication.Builder> confidentialClientApplicationBuilderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
ConfidentialClientApplication application = Mockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
})) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), argThat(cred -> ((IClientCertificate) cred) != null))).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(anyString(), argThat(cred -> ((IClientCertificate) cred) == null))).thenThrow(new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate"));
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any(IClientCertificate.class))).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
test.run();
Assert.assertNotNull(confidentialClientApplicationBuilderMock);
}
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
when(builder.build()).thenReturn(application);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedStatic<CertificateUtil> certificateUtilMock = mockStatic(CertificateUtil.class);
MockedStatic<ClientCredentialFactory> clientCredentialFactoryMock = mockStatic(ClientCredentialFactory.class);
MockedStatic<ConfidentialClientApplication> staticConfidentialClientApplicationMock = mockStatic(ConfidentialClientApplication.class);
MockedConstruction<ConfidentialClientApplication.Builder> builderMock = mockConstruction(ConfidentialClientApplication.Builder.class, (builder, context) -> {
ConfidentialClientApplication application = mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})
) {
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(eq(CLIENT_ID), any())).thenCallRealMethod();
staticConfidentialClientApplicationMock.when(() -> ConfidentialClientApplication.builder(AdditionalMatchers.not(eq(CLIENT_ID)), any())).thenThrow(new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId"));
PrivateKey privateKey = mock(PrivateKey.class);
IClientCertificate clientCertificate = mock(IClientCertificate.class);
certificateUtilMock.when(() -> CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
clientCredentialFactoryMock.when(() -> ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class))).thenReturn(clientCertificate);
test.run();
Assert.assertNotNull(builderMock);
}
}
private void mockForMSICodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForServiceFabricCodeFlow(String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpsURLConnection huc = mock(HttpsURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setSSLSocketFactory(any());
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForArcCodeFlow(int responseCode, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setRequestProperty(anyString(), anyString());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
when(huc.getInputStream()).thenThrow(new IOException());
when(huc.getResponseCode()).thenReturn(responseCode);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForIMDSCodeFlow(String endpoint, String tokenJson, Runnable test) throws Exception {
try (MockedStatic<IdentityClient> identityClientMockedStatic = mockStatic(IdentityClient.class)) {
URL url = mock(URL.class);
HttpURLConnection huc = mock(HttpURLConnection.class);
doNothing().when(huc).setRequestMethod(anyString());
doNothing().when(huc).setConnectTimeout(anyInt());
doNothing().when(huc).connect();
when(url.openConnection()).thenReturn(huc);
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
identityClientMockedStatic.when(() -> IdentityClient.getUrl(anyString())).thenReturn(url);
test.run();
}
}
private void mockForBrowserAuthenticationCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(InteractiveRequestParameters.class))).thenAnswer(invocation -> {
InteractiveRequestParameters argument = (InteractiveRequestParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class))).thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
private void mockForUserRefreshTokenFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn, Runnable test) {
try (MockedConstruction<PublicClientApplication.Builder> publicClientApplicationMock = mockConstruction(PublicClientApplication.Builder.class, (builder, context) -> {
PublicClientApplication application = Mockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any())).thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.instanceDiscovery(anyBoolean())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
})) {
test.run();
Assert.assertNotNull(publicClientApplicationMock);
}
}
} |
why is needed to convert to char? why not to to string directly and you remove one step? | public String convertToString() {
return dtmfTones.stream()
.map(x -> x.toChar())
.map(x -> x.toString())
.collect(Collectors.joining());
} | .map(x -> x.toChar()) | public String convertToString() {
if (this.dtmfTones == null) {
return "";
}
return this.dtmfTones.stream()
.map(x -> x.convertToString())
.collect(Collectors.joining());
} | class CollectTonesResult extends RecognizeResult {
/*
* The tones property.
*/
@JsonProperty(value = "tones")
private List<DtmfTone> dtmfTones;
/**
* Get the tones property: The tones property.
*
* @return the tones value.
*/
public List<DtmfTone> getTones() {
return this.dtmfTones;
}
/**
* Set the tones property: The tones property.
*
* @param dtmfTones the tones value to set.
* @return the CollectTonesResult object itself.
*/
public CollectTonesResult setTones(List<DtmfTone> dtmfTones) {
this.dtmfTones = dtmfTones;
return this;
}
/**
* Set the tones property: The tones property.
*
* @return the CollectTonesResult object itself.
*/
} | class CollectTonesResult extends RecognizeResult {
/*
* The tones property.
*/
@JsonProperty(value = "tones")
private List<DtmfTone> dtmfTones;
/**
* Get the tones property: The tones property.
*
* @return the tones value.
*/
public List<DtmfTone> getTones() {
return this.dtmfTones;
}
/**
* Set the tones property: The tones property.
*
* @param dtmfTones the tones value to set.
* @return the CollectTonesResult object itself.
*/
public CollectTonesResult setTones(List<DtmfTone> dtmfTones) {
this.dtmfTones = dtmfTones;
return this;
}
/**
* Set the tones property: The tones property.
*
* @return the CollectTonesResult object itself.
*/
} |
it is a naming that the converted type is an element in char format, we could convert it to string directly, but the naming would be toString or convertToString, which doesn't reflect the motivation of the change purpose. | public String convertToString() {
return dtmfTones.stream()
.map(x -> x.toChar())
.map(x -> x.toString())
.collect(Collectors.joining());
} | .map(x -> x.toChar()) | public String convertToString() {
if (this.dtmfTones == null) {
return "";
}
return this.dtmfTones.stream()
.map(x -> x.convertToString())
.collect(Collectors.joining());
} | class CollectTonesResult extends RecognizeResult {
/*
* The tones property.
*/
@JsonProperty(value = "tones")
private List<DtmfTone> dtmfTones;
/**
* Get the tones property: The tones property.
*
* @return the tones value.
*/
public List<DtmfTone> getTones() {
return this.dtmfTones;
}
/**
* Set the tones property: The tones property.
*
* @param dtmfTones the tones value to set.
* @return the CollectTonesResult object itself.
*/
public CollectTonesResult setTones(List<DtmfTone> dtmfTones) {
this.dtmfTones = dtmfTones;
return this;
}
/**
* Set the tones property: The tones property.
*
* @return the CollectTonesResult object itself.
*/
} | class CollectTonesResult extends RecognizeResult {
/*
* The tones property.
*/
@JsonProperty(value = "tones")
private List<DtmfTone> dtmfTones;
/**
* Get the tones property: The tones property.
*
* @return the tones value.
*/
public List<DtmfTone> getTones() {
return this.dtmfTones;
}
/**
* Set the tones property: The tones property.
*
* @param dtmfTones the tones value to set.
* @return the CollectTonesResult object itself.
*/
public CollectTonesResult setTones(List<DtmfTone> dtmfTones) {
this.dtmfTones = dtmfTones;
return this;
}
/**
* Set the tones property: The tones property.
*
* @return the CollectTonesResult object itself.
*/
} |
> which doesn't reflect the motivation of the change purpose. I thought that the change purpose is to create a string out of the CollectTonesResult object and `toChar` was just an intermediate operation. If you get rid of `toChar` and call directly `toString` you do the same work with one step less. | public String convertToString() {
return dtmfTones.stream()
.map(x -> x.toChar())
.map(x -> x.toString())
.collect(Collectors.joining());
} | .map(x -> x.toChar()) | public String convertToString() {
if (this.dtmfTones == null) {
return "";
}
return this.dtmfTones.stream()
.map(x -> x.convertToString())
.collect(Collectors.joining());
} | class CollectTonesResult extends RecognizeResult {
/*
* The tones property.
*/
@JsonProperty(value = "tones")
private List<DtmfTone> dtmfTones;
/**
* Get the tones property: The tones property.
*
* @return the tones value.
*/
public List<DtmfTone> getTones() {
return this.dtmfTones;
}
/**
* Set the tones property: The tones property.
*
* @param dtmfTones the tones value to set.
* @return the CollectTonesResult object itself.
*/
public CollectTonesResult setTones(List<DtmfTone> dtmfTones) {
this.dtmfTones = dtmfTones;
return this;
}
/**
* Set the tones property: The tones property.
*
* @return the CollectTonesResult object itself.
*/
} | class CollectTonesResult extends RecognizeResult {
/*
* The tones property.
*/
@JsonProperty(value = "tones")
private List<DtmfTone> dtmfTones;
/**
* Get the tones property: The tones property.
*
* @return the tones value.
*/
public List<DtmfTone> getTones() {
return this.dtmfTones;
}
/**
* Set the tones property: The tones property.
*
* @param dtmfTones the tones value to set.
* @return the CollectTonesResult object itself.
*/
public CollectTonesResult setTones(List<DtmfTone> dtmfTones) {
this.dtmfTones = dtmfTones;
return this;
}
/**
* Set the tones property: The tones property.
*
* @return the CollectTonesResult object itself.
*/
} |
`Flux<ByteBuffer>` is replaced by `BinaryData` in mgmt as well? | public Mono<PublishingProfile> getPublishingProfileAsync() {
return manager()
.serviceClient()
.getWebApps()
.listPublishingProfileXmlWithSecretsAsync(resourceGroupName(), name(), new CsmPublishingProfileOptions())
.map(binaryData -> new PublishingProfileImpl(binaryData.toString(), this));
} | .map(binaryData -> new PublishingProfileImpl(binaryData.toString(), this)); | public Mono<PublishingProfile> getPublishingProfileAsync() {
return manager()
.serviceClient()
.getWebApps()
.listPublishingProfileXmlWithSecretsAsync(resourceGroupName(), name(), new CsmPublishingProfileOptions())
.map(binaryData -> new PublishingProfileImpl(binaryData.toString(), this));
} | class AppServiceBaseImpl<
FluentT extends WebAppBase,
FluentImplT extends AppServiceBaseImpl<FluentT, FluentImplT, FluentWithCreateT, FluentUpdateT>,
FluentWithCreateT,
FluentUpdateT>
extends WebAppBaseImpl<FluentT, FluentImplT>
implements
SupportsListingPrivateLinkResource,
SupportsListingPrivateEndpointConnection,
SupportsUpdatingPrivateEndpointConnection {
private final ClientLogger logger = new ClientLogger(getClass());
AppServiceBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, siteConfig, logConfig, manager);
}
@Override
Mono<SiteInner> createOrUpdateInner(SiteInner site) {
return this.manager().serviceClient().getWebApps().createOrUpdateAsync(resourceGroupName(), name(), site);
}
@Override
Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate) {
return this.manager().serviceClient().getWebApps().updateAsync(resourceGroupName(), name(), siteUpdate);
}
@Override
Mono<SiteInner> getInner() {
return this.manager().serviceClient().getWebApps().getByResourceGroupAsync(resourceGroupName(), name());
}
@Override
Mono<SiteConfigResourceInner> getConfigInner() {
return this.manager().serviceClient().getWebApps().getConfigurationAsync(resourceGroupName(), name());
}
@Override
Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) {
return this
.manager()
.serviceClient()
.getWebApps()
.createOrUpdateConfigurationAsync(resourceGroupName(), name(), siteConfig);
}
@Override
Mono<Void> deleteHostnameBinding(String hostname) {
return this.manager().serviceClient().getWebApps()
.deleteHostnameBindingAsync(resourceGroupName(), name(), hostname);
}
@Override
Mono<StringDictionaryInner> listAppSettings() {
return this.manager().serviceClient().getWebApps().listApplicationSettingsAsync(resourceGroupName(), name());
}
@Override
Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner) {
return this.manager().serviceClient().getWebApps()
.updateApplicationSettingsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<ConnectionStringDictionaryInner> listConnectionStrings() {
return this.manager().serviceClient().getWebApps().listConnectionStringsAsync(resourceGroupName(), name());
}
@Override
Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner) {
return this.manager().serviceClient().getWebApps()
.updateConnectionStringsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SlotConfigNamesResourceInner> listSlotConfigurations() {
return this.manager().serviceClient().getWebApps().listSlotConfigurationNamesAsync(resourceGroupName(), name());
}
@Override
Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner) {
return this.manager().serviceClient().getWebApps()
.updateSlotConfigurationNamesAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner) {
return this.manager().serviceClient().getWebApps()
.createOrUpdateSourceControlAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<Void> deleteSourceControl() {
return this.manager().serviceClient().getWebApps().deleteSourceControlAsync(resourceGroupName(), name());
}
@Override
Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner) {
return manager().serviceClient().getWebApps().updateAuthSettingsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SiteAuthSettingsInner> getAuthentication() {
return manager().serviceClient().getWebApps().getAuthSettingsAsync(resourceGroupName(), name());
}
@Override
public Map<String, HostnameBinding> getHostnameBindings() {
return getHostnameBindingsAsync().block();
}
@Override
@SuppressWarnings("unchecked")
public Mono<Map<String, HostnameBinding>> getHostnameBindingsAsync() {
return PagedConverter.mapPage(this
.manager()
.serviceClient()
.getWebApps()
.listHostnameBindingsAsync(resourceGroupName(), name()),
hostNameBindingInner ->
new HostnameBindingImpl<>(hostNameBindingInner, (FluentImplT) AppServiceBaseImpl.this))
.collectList()
.map(
hostNameBindings ->
Collections
.<String, HostnameBinding>unmodifiableMap(
hostNameBindings
.stream()
.collect(
Collectors
.toMap(
binding -> binding.name().replace(name() + "/", ""),
Function.identity()))));
}
@Override
public PublishingProfile getPublishingProfile() {
return getPublishingProfileAsync().block();
}
@Override
public WebAppSourceControl getSourceControl() {
return getSourceControlAsync().block();
}
@Override
public Mono<WebAppSourceControl> getSourceControlAsync() {
return manager()
.serviceClient()
.getWebApps()
.getSourceControlAsync(resourceGroupName(), name())
.map(
siteSourceControlInner ->
new WebAppSourceControlImpl<>(siteSourceControlInner, AppServiceBaseImpl.this));
}
@Override
Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner) {
return manager().serviceClient().getWebApps()
.createMSDeployOperationAsync(resourceGroupName(), name(), msDeployInner);
}
@Override
public void verifyDomainOwnership(String certificateOrderName, String domainVerificationToken) {
verifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken).block();
}
@Override
public Mono<Void> verifyDomainOwnershipAsync(String certificateOrderName, String domainVerificationToken) {
IdentifierInner identifierInner = new IdentifierInner().withValue(domainVerificationToken);
return this
.manager()
.serviceClient()
.getWebApps()
.createOrUpdateDomainOwnershipIdentifierAsync(
resourceGroupName(), name(), certificateOrderName, identifierInner)
.then(Mono.empty());
}
@Override
public void start() {
startAsync().block();
}
@Override
public Mono<Void> startAsync() {
return manager()
.serviceClient()
.getWebApps()
.startAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void stop() {
stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return manager()
.serviceClient()
.getWebApps()
.stopAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void restart() {
restartAsync().block();
}
@Override
public Mono<Void> restartAsync() {
return manager()
.serviceClient()
.getWebApps()
.restartAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void swap(String slotName) {
swapAsync(slotName).block();
}
@Override
public Mono<Void> swapAsync(String slotName) {
return manager()
.serviceClient()
.getWebApps()
.swapSlotWithProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName))
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void applySlotConfigurations(String slotName) {
applySlotConfigurationsAsync(slotName).block();
}
@Override
public Mono<Void> applySlotConfigurationsAsync(String slotName) {
return manager()
.serviceClient()
.getWebApps()
.applySlotConfigToProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName))
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void resetSlotConfigurations() {
resetSlotConfigurationsAsync().block();
}
@Override
public Mono<Void> resetSlotConfigurationsAsync() {
return manager()
.serviceClient()
.getWebApps()
.resetProductionSlotConfigAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public byte[] getContainerLogs() {
return getContainerLogsAsync().block();
}
@Override
public Mono<byte[]> getContainerLogsAsync() {
return manager().serviceClient().getWebApps().getWebSiteContainerLogsAsync(resourceGroupName(), name())
.map(BinaryData::toBytes);
}
@Override
public byte[] getContainerLogsZip() {
return getContainerLogsZipAsync().block();
}
@Override
public Mono<byte[]> getContainerLogsZipAsync() {
return manager().serviceClient().getWebApps().getContainerLogsZipAsync(resourceGroupName(), name())
.map(BinaryData::toBytes);
}
@Override
Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner) {
return manager()
.serviceClient()
.getWebApps()
.updateDiagnosticLogsConfigAsync(resourceGroupName(), name(), siteLogsConfigInner);
}
private AppServicePlanImpl newDefaultAppServicePlan() {
String planName = this.manager().resourceManager().internalContext().randomResourceName(name() + "plan", 32);
return newDefaultAppServicePlan(planName);
}
private AppServicePlanImpl newDefaultAppServicePlan(String appServicePlanName) {
AppServicePlanImpl appServicePlan =
(AppServicePlanImpl) (this.manager().appServicePlans().define(appServicePlanName)).withRegion(regionName());
if (super.creatableGroup != null && isInCreateMode()) {
appServicePlan = appServicePlan.withNewResourceGroup(super.creatableGroup);
} else {
appServicePlan = appServicePlan.withExistingResourceGroup(resourceGroupName());
}
return appServicePlan;
}
public FluentImplT withNewFreeAppServicePlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, PricingTier.FREE_F1);
}
public FluentImplT withNewSharedAppServicePlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, PricingTier.SHARED_D1);
}
FluentImplT withNewAppServicePlan(OperatingSystem operatingSystem, PricingTier pricingTier) {
return withNewAppServicePlan(
newDefaultAppServicePlan().withOperatingSystem(operatingSystem).withPricingTier(pricingTier));
}
FluentImplT withNewAppServicePlan(
String appServicePlanName, OperatingSystem operatingSystem, PricingTier pricingTier) {
return withNewAppServicePlan(
newDefaultAppServicePlan(appServicePlanName)
.withOperatingSystem(operatingSystem)
.withPricingTier(pricingTier));
}
public FluentImplT withNewAppServicePlan(PricingTier pricingTier) {
return withNewAppServicePlan(operatingSystem(), pricingTier);
}
public FluentImplT withNewAppServicePlan(String appServicePlanName, PricingTier pricingTier) {
return withNewAppServicePlan(appServicePlanName, operatingSystem(), pricingTier);
}
public FluentImplT withNewAppServicePlan(Creatable<AppServicePlan> appServicePlanCreatable) {
this.addDependency(appServicePlanCreatable);
String id =
ResourceUtils
.constructResourceId(
this.manager().subscriptionId(),
resourceGroupName(),
"Microsoft.Web",
"serverFarms",
appServicePlanCreatable.name(),
"");
innerModel().withServerFarmId(id);
if (appServicePlanCreatable instanceof AppServicePlanImpl) {
return withOperatingSystem(((AppServicePlanImpl) appServicePlanCreatable).operatingSystem());
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Internal error, appServicePlanCreatable must be class AppServicePlanImpl"));
}
}
@SuppressWarnings("unchecked")
private FluentImplT withOperatingSystem(OperatingSystem os) {
if (os == OperatingSystem.LINUX) {
innerModel().withReserved(true);
innerModel().withKind(innerModel().kind() + ",linux");
}
return (FluentImplT) this;
}
public FluentImplT withExistingAppServicePlan(AppServicePlan appServicePlan) {
innerModel().withServerFarmId(appServicePlan.id());
this.withRegion(appServicePlan.regionName());
return withOperatingSystem(appServicePlanOperatingSystem(appServicePlan));
}
@SuppressWarnings("unchecked")
public FluentImplT withPublicDockerHubImage(String imageAndTag) {
cleanUpContainerSettings();
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag));
withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag);
return (FluentImplT) this;
}
public FluentImplT withPrivateDockerHubImage(String imageAndTag) {
return withPublicDockerHubImage(imageAndTag);
}
@SuppressWarnings("unchecked")
public FluentImplT withPrivateRegistryImage(String imageAndTag, String serverUrl) {
imageAndTag = Utils.smartCompletionPrivateRegistryImage(imageAndTag, serverUrl);
cleanUpContainerSettings();
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag));
withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag);
withAppSetting(SETTING_REGISTRY_SERVER, serverUrl);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withCredentials(String username, String password) {
withAppSetting(SETTING_REGISTRY_USERNAME, username);
withAppSetting(SETTING_REGISTRY_PASSWORD, password);
return (FluentImplT) this;
}
protected abstract void cleanUpContainerSettings();
protected void ensureLinuxPlan() {
if (OperatingSystem.WINDOWS.equals(operatingSystem())) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Docker container settings only apply to Linux app service plans."));
}
}
protected OperatingSystem appServicePlanOperatingSystem(AppServicePlan appServicePlan) {
return appServicePlan.operatingSystem();
}
@Override
public PagedIterable<PrivateLinkResource> listPrivateLinkResources() {
return new PagedIterable<>(listPrivateLinkResourcesAsync());
}
@Override
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() {
Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getWebApps()
.getPrivateLinkResourcesWithResponseAsync(this.resourceGroupName(), this.name())
.map(response -> new SimpleResponse<>(response, response.getValue().value().stream()
.map(PrivateLinkResourceImpl::new)
.collect(Collectors.toList())));
return PagedConverter.convertListToPagedFlux(retList);
}
@Override
public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() {
return new PagedIterable<>(listPrivateEndpointConnectionsAsync());
}
@Override
public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() {
return PagedConverter.mapPage(this.manager().serviceClient().getWebApps()
.getPrivateEndpointConnectionListAsync(this.resourceGroupName(), this.name()),
PrivateEndpointConnectionImpl::new);
}
@Override
public void approvePrivateEndpointConnection(String privateEndpointConnectionName) {
approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return this.manager().serviceClient().getWebApps()
.approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(),
privateEndpointConnectionName,
new PrivateLinkConnectionApprovalRequestResource().withPrivateLinkServiceConnectionState(
new PrivateLinkConnectionState()
.withStatus(PrivateEndpointServiceConnectionStatus.APPROVED.toString())
))
.then();
}
@Override
public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) {
rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return this.manager().serviceClient().getWebApps()
.approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(),
privateEndpointConnectionName,
new PrivateLinkConnectionApprovalRequestResource().withPrivateLinkServiceConnectionState(
new PrivateLinkConnectionState()
.withStatus(PrivateEndpointServiceConnectionStatus.REJECTED.toString())
))
.then();
}
} | class AppServiceBaseImpl<
FluentT extends WebAppBase,
FluentImplT extends AppServiceBaseImpl<FluentT, FluentImplT, FluentWithCreateT, FluentUpdateT>,
FluentWithCreateT,
FluentUpdateT>
extends WebAppBaseImpl<FluentT, FluentImplT>
implements
SupportsListingPrivateLinkResource,
SupportsListingPrivateEndpointConnection,
SupportsUpdatingPrivateEndpointConnection {
private final ClientLogger logger = new ClientLogger(getClass());
AppServiceBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, siteConfig, logConfig, manager);
}
@Override
Mono<SiteInner> createOrUpdateInner(SiteInner site) {
return this.manager().serviceClient().getWebApps().createOrUpdateAsync(resourceGroupName(), name(), site);
}
@Override
Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate) {
return this.manager().serviceClient().getWebApps().updateAsync(resourceGroupName(), name(), siteUpdate);
}
@Override
Mono<SiteInner> getInner() {
return this.manager().serviceClient().getWebApps().getByResourceGroupAsync(resourceGroupName(), name());
}
@Override
Mono<SiteConfigResourceInner> getConfigInner() {
return this.manager().serviceClient().getWebApps().getConfigurationAsync(resourceGroupName(), name());
}
@Override
Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) {
return this
.manager()
.serviceClient()
.getWebApps()
.createOrUpdateConfigurationAsync(resourceGroupName(), name(), siteConfig);
}
@Override
Mono<Void> deleteHostnameBinding(String hostname) {
return this.manager().serviceClient().getWebApps()
.deleteHostnameBindingAsync(resourceGroupName(), name(), hostname);
}
@Override
Mono<StringDictionaryInner> listAppSettings() {
return this.manager().serviceClient().getWebApps().listApplicationSettingsAsync(resourceGroupName(), name());
}
@Override
Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner) {
return this.manager().serviceClient().getWebApps()
.updateApplicationSettingsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<ConnectionStringDictionaryInner> listConnectionStrings() {
return this.manager().serviceClient().getWebApps().listConnectionStringsAsync(resourceGroupName(), name());
}
@Override
Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner) {
return this.manager().serviceClient().getWebApps()
.updateConnectionStringsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SlotConfigNamesResourceInner> listSlotConfigurations() {
return this.manager().serviceClient().getWebApps().listSlotConfigurationNamesAsync(resourceGroupName(), name());
}
@Override
Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner) {
return this.manager().serviceClient().getWebApps()
.updateSlotConfigurationNamesAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner) {
return this.manager().serviceClient().getWebApps()
.createOrUpdateSourceControlAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<Void> deleteSourceControl() {
return this.manager().serviceClient().getWebApps().deleteSourceControlAsync(resourceGroupName(), name());
}
@Override
Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner) {
return manager().serviceClient().getWebApps().updateAuthSettingsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SiteAuthSettingsInner> getAuthentication() {
return manager().serviceClient().getWebApps().getAuthSettingsAsync(resourceGroupName(), name());
}
@Override
public Map<String, HostnameBinding> getHostnameBindings() {
return getHostnameBindingsAsync().block();
}
@Override
@SuppressWarnings("unchecked")
public Mono<Map<String, HostnameBinding>> getHostnameBindingsAsync() {
return PagedConverter.mapPage(this
.manager()
.serviceClient()
.getWebApps()
.listHostnameBindingsAsync(resourceGroupName(), name()),
hostNameBindingInner ->
new HostnameBindingImpl<>(hostNameBindingInner, (FluentImplT) AppServiceBaseImpl.this))
.collectList()
.map(
hostNameBindings ->
Collections
.<String, HostnameBinding>unmodifiableMap(
hostNameBindings
.stream()
.collect(
Collectors
.toMap(
binding -> binding.name().replace(name() + "/", ""),
Function.identity()))));
}
@Override
public PublishingProfile getPublishingProfile() {
return getPublishingProfileAsync().block();
}
@Override
public WebAppSourceControl getSourceControl() {
return getSourceControlAsync().block();
}
@Override
public Mono<WebAppSourceControl> getSourceControlAsync() {
return manager()
.serviceClient()
.getWebApps()
.getSourceControlAsync(resourceGroupName(), name())
.map(
siteSourceControlInner ->
new WebAppSourceControlImpl<>(siteSourceControlInner, AppServiceBaseImpl.this));
}
@Override
Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner) {
return manager().serviceClient().getWebApps()
.createMSDeployOperationAsync(resourceGroupName(), name(), msDeployInner);
}
@Override
public void verifyDomainOwnership(String certificateOrderName, String domainVerificationToken) {
verifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken).block();
}
@Override
public Mono<Void> verifyDomainOwnershipAsync(String certificateOrderName, String domainVerificationToken) {
IdentifierInner identifierInner = new IdentifierInner().withValue(domainVerificationToken);
return this
.manager()
.serviceClient()
.getWebApps()
.createOrUpdateDomainOwnershipIdentifierAsync(
resourceGroupName(), name(), certificateOrderName, identifierInner)
.then(Mono.empty());
}
@Override
public void start() {
startAsync().block();
}
@Override
public Mono<Void> startAsync() {
return manager()
.serviceClient()
.getWebApps()
.startAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void stop() {
stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return manager()
.serviceClient()
.getWebApps()
.stopAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void restart() {
restartAsync().block();
}
@Override
public Mono<Void> restartAsync() {
return manager()
.serviceClient()
.getWebApps()
.restartAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void swap(String slotName) {
swapAsync(slotName).block();
}
@Override
public Mono<Void> swapAsync(String slotName) {
return manager()
.serviceClient()
.getWebApps()
.swapSlotWithProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName))
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void applySlotConfigurations(String slotName) {
applySlotConfigurationsAsync(slotName).block();
}
@Override
public Mono<Void> applySlotConfigurationsAsync(String slotName) {
return manager()
.serviceClient()
.getWebApps()
.applySlotConfigToProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName))
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void resetSlotConfigurations() {
resetSlotConfigurationsAsync().block();
}
@Override
public Mono<Void> resetSlotConfigurationsAsync() {
return manager()
.serviceClient()
.getWebApps()
.resetProductionSlotConfigAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public byte[] getContainerLogs() {
return getContainerLogsAsync().block();
}
@Override
public Mono<byte[]> getContainerLogsAsync() {
return manager().serviceClient().getWebApps().getWebSiteContainerLogsAsync(resourceGroupName(), name())
.map(BinaryData::toBytes);
}
@Override
public byte[] getContainerLogsZip() {
return getContainerLogsZipAsync().block();
}
@Override
public Mono<byte[]> getContainerLogsZipAsync() {
return manager().serviceClient().getWebApps().getContainerLogsZipAsync(resourceGroupName(), name())
.map(BinaryData::toBytes);
}
@Override
Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner) {
return manager()
.serviceClient()
.getWebApps()
.updateDiagnosticLogsConfigAsync(resourceGroupName(), name(), siteLogsConfigInner);
}
private AppServicePlanImpl newDefaultAppServicePlan() {
String planName = this.manager().resourceManager().internalContext().randomResourceName(name() + "plan", 32);
return newDefaultAppServicePlan(planName);
}
private AppServicePlanImpl newDefaultAppServicePlan(String appServicePlanName) {
AppServicePlanImpl appServicePlan =
(AppServicePlanImpl) (this.manager().appServicePlans().define(appServicePlanName)).withRegion(regionName());
if (super.creatableGroup != null && isInCreateMode()) {
appServicePlan = appServicePlan.withNewResourceGroup(super.creatableGroup);
} else {
appServicePlan = appServicePlan.withExistingResourceGroup(resourceGroupName());
}
return appServicePlan;
}
public FluentImplT withNewFreeAppServicePlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, PricingTier.FREE_F1);
}
public FluentImplT withNewSharedAppServicePlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, PricingTier.SHARED_D1);
}
FluentImplT withNewAppServicePlan(OperatingSystem operatingSystem, PricingTier pricingTier) {
return withNewAppServicePlan(
newDefaultAppServicePlan().withOperatingSystem(operatingSystem).withPricingTier(pricingTier));
}
FluentImplT withNewAppServicePlan(
String appServicePlanName, OperatingSystem operatingSystem, PricingTier pricingTier) {
return withNewAppServicePlan(
newDefaultAppServicePlan(appServicePlanName)
.withOperatingSystem(operatingSystem)
.withPricingTier(pricingTier));
}
public FluentImplT withNewAppServicePlan(PricingTier pricingTier) {
return withNewAppServicePlan(operatingSystem(), pricingTier);
}
public FluentImplT withNewAppServicePlan(String appServicePlanName, PricingTier pricingTier) {
return withNewAppServicePlan(appServicePlanName, operatingSystem(), pricingTier);
}
public FluentImplT withNewAppServicePlan(Creatable<AppServicePlan> appServicePlanCreatable) {
this.addDependency(appServicePlanCreatable);
String id =
ResourceUtils
.constructResourceId(
this.manager().subscriptionId(),
resourceGroupName(),
"Microsoft.Web",
"serverFarms",
appServicePlanCreatable.name(),
"");
innerModel().withServerFarmId(id);
if (appServicePlanCreatable instanceof AppServicePlanImpl) {
return withOperatingSystem(((AppServicePlanImpl) appServicePlanCreatable).operatingSystem());
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Internal error, appServicePlanCreatable must be class AppServicePlanImpl"));
}
}
@SuppressWarnings("unchecked")
private FluentImplT withOperatingSystem(OperatingSystem os) {
if (os == OperatingSystem.LINUX) {
innerModel().withReserved(true);
innerModel().withKind(innerModel().kind() + ",linux");
}
return (FluentImplT) this;
}
public FluentImplT withExistingAppServicePlan(AppServicePlan appServicePlan) {
innerModel().withServerFarmId(appServicePlan.id());
this.withRegion(appServicePlan.regionName());
return withOperatingSystem(appServicePlanOperatingSystem(appServicePlan));
}
@SuppressWarnings("unchecked")
public FluentImplT withPublicDockerHubImage(String imageAndTag) {
cleanUpContainerSettings();
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag));
withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag);
return (FluentImplT) this;
}
public FluentImplT withPrivateDockerHubImage(String imageAndTag) {
return withPublicDockerHubImage(imageAndTag);
}
@SuppressWarnings("unchecked")
public FluentImplT withPrivateRegistryImage(String imageAndTag, String serverUrl) {
imageAndTag = Utils.smartCompletionPrivateRegistryImage(imageAndTag, serverUrl);
cleanUpContainerSettings();
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag));
withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag);
withAppSetting(SETTING_REGISTRY_SERVER, serverUrl);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withCredentials(String username, String password) {
withAppSetting(SETTING_REGISTRY_USERNAME, username);
withAppSetting(SETTING_REGISTRY_PASSWORD, password);
return (FluentImplT) this;
}
protected abstract void cleanUpContainerSettings();
protected void ensureLinuxPlan() {
if (OperatingSystem.WINDOWS.equals(operatingSystem())) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Docker container settings only apply to Linux app service plans."));
}
}
protected OperatingSystem appServicePlanOperatingSystem(AppServicePlan appServicePlan) {
return appServicePlan.operatingSystem();
}
@Override
public PagedIterable<PrivateLinkResource> listPrivateLinkResources() {
return new PagedIterable<>(listPrivateLinkResourcesAsync());
}
@Override
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() {
Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getWebApps()
.getPrivateLinkResourcesWithResponseAsync(this.resourceGroupName(), this.name())
.map(response -> new SimpleResponse<>(response, response.getValue().value().stream()
.map(PrivateLinkResourceImpl::new)
.collect(Collectors.toList())));
return PagedConverter.convertListToPagedFlux(retList);
}
@Override
public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() {
return new PagedIterable<>(listPrivateEndpointConnectionsAsync());
}
@Override
public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() {
return PagedConverter.mapPage(this.manager().serviceClient().getWebApps()
.getPrivateEndpointConnectionListAsync(this.resourceGroupName(), this.name()),
PrivateEndpointConnectionImpl::new);
}
@Override
public void approvePrivateEndpointConnection(String privateEndpointConnectionName) {
approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return this.manager().serviceClient().getWebApps()
.approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(),
privateEndpointConnectionName,
new PrivateLinkConnectionApprovalRequestResource().withPrivateLinkServiceConnectionState(
new PrivateLinkConnectionState()
.withStatus(PrivateEndpointServiceConnectionStatus.APPROVED.toString())
))
.then();
}
@Override
public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) {
rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return this.manager().serviceClient().getWebApps()
.approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(),
privateEndpointConnectionName,
new PrivateLinkConnectionApprovalRequestResource().withPrivateLinkServiceConnectionState(
new PrivateLinkConnectionState()
.withStatus(PrivateEndpointServiceConnectionStatus.REJECTED.toString())
))
.then();
}
} |
Yes. If for GA SDK there be breaking changes due to this, I believe there is a flag to revert to old behavior. | public Mono<PublishingProfile> getPublishingProfileAsync() {
return manager()
.serviceClient()
.getWebApps()
.listPublishingProfileXmlWithSecretsAsync(resourceGroupName(), name(), new CsmPublishingProfileOptions())
.map(binaryData -> new PublishingProfileImpl(binaryData.toString(), this));
} | .map(binaryData -> new PublishingProfileImpl(binaryData.toString(), this)); | public Mono<PublishingProfile> getPublishingProfileAsync() {
return manager()
.serviceClient()
.getWebApps()
.listPublishingProfileXmlWithSecretsAsync(resourceGroupName(), name(), new CsmPublishingProfileOptions())
.map(binaryData -> new PublishingProfileImpl(binaryData.toString(), this));
} | class AppServiceBaseImpl<
FluentT extends WebAppBase,
FluentImplT extends AppServiceBaseImpl<FluentT, FluentImplT, FluentWithCreateT, FluentUpdateT>,
FluentWithCreateT,
FluentUpdateT>
extends WebAppBaseImpl<FluentT, FluentImplT>
implements
SupportsListingPrivateLinkResource,
SupportsListingPrivateEndpointConnection,
SupportsUpdatingPrivateEndpointConnection {
private final ClientLogger logger = new ClientLogger(getClass());
AppServiceBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, siteConfig, logConfig, manager);
}
@Override
Mono<SiteInner> createOrUpdateInner(SiteInner site) {
return this.manager().serviceClient().getWebApps().createOrUpdateAsync(resourceGroupName(), name(), site);
}
@Override
Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate) {
return this.manager().serviceClient().getWebApps().updateAsync(resourceGroupName(), name(), siteUpdate);
}
@Override
Mono<SiteInner> getInner() {
return this.manager().serviceClient().getWebApps().getByResourceGroupAsync(resourceGroupName(), name());
}
@Override
Mono<SiteConfigResourceInner> getConfigInner() {
return this.manager().serviceClient().getWebApps().getConfigurationAsync(resourceGroupName(), name());
}
@Override
Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) {
return this
.manager()
.serviceClient()
.getWebApps()
.createOrUpdateConfigurationAsync(resourceGroupName(), name(), siteConfig);
}
@Override
Mono<Void> deleteHostnameBinding(String hostname) {
return this.manager().serviceClient().getWebApps()
.deleteHostnameBindingAsync(resourceGroupName(), name(), hostname);
}
@Override
Mono<StringDictionaryInner> listAppSettings() {
return this.manager().serviceClient().getWebApps().listApplicationSettingsAsync(resourceGroupName(), name());
}
@Override
Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner) {
return this.manager().serviceClient().getWebApps()
.updateApplicationSettingsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<ConnectionStringDictionaryInner> listConnectionStrings() {
return this.manager().serviceClient().getWebApps().listConnectionStringsAsync(resourceGroupName(), name());
}
@Override
Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner) {
return this.manager().serviceClient().getWebApps()
.updateConnectionStringsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SlotConfigNamesResourceInner> listSlotConfigurations() {
return this.manager().serviceClient().getWebApps().listSlotConfigurationNamesAsync(resourceGroupName(), name());
}
@Override
Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner) {
return this.manager().serviceClient().getWebApps()
.updateSlotConfigurationNamesAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner) {
return this.manager().serviceClient().getWebApps()
.createOrUpdateSourceControlAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<Void> deleteSourceControl() {
return this.manager().serviceClient().getWebApps().deleteSourceControlAsync(resourceGroupName(), name());
}
@Override
Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner) {
return manager().serviceClient().getWebApps().updateAuthSettingsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SiteAuthSettingsInner> getAuthentication() {
return manager().serviceClient().getWebApps().getAuthSettingsAsync(resourceGroupName(), name());
}
@Override
public Map<String, HostnameBinding> getHostnameBindings() {
return getHostnameBindingsAsync().block();
}
@Override
@SuppressWarnings("unchecked")
public Mono<Map<String, HostnameBinding>> getHostnameBindingsAsync() {
return PagedConverter.mapPage(this
.manager()
.serviceClient()
.getWebApps()
.listHostnameBindingsAsync(resourceGroupName(), name()),
hostNameBindingInner ->
new HostnameBindingImpl<>(hostNameBindingInner, (FluentImplT) AppServiceBaseImpl.this))
.collectList()
.map(
hostNameBindings ->
Collections
.<String, HostnameBinding>unmodifiableMap(
hostNameBindings
.stream()
.collect(
Collectors
.toMap(
binding -> binding.name().replace(name() + "/", ""),
Function.identity()))));
}
@Override
public PublishingProfile getPublishingProfile() {
return getPublishingProfileAsync().block();
}
@Override
public WebAppSourceControl getSourceControl() {
return getSourceControlAsync().block();
}
@Override
public Mono<WebAppSourceControl> getSourceControlAsync() {
return manager()
.serviceClient()
.getWebApps()
.getSourceControlAsync(resourceGroupName(), name())
.map(
siteSourceControlInner ->
new WebAppSourceControlImpl<>(siteSourceControlInner, AppServiceBaseImpl.this));
}
@Override
Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner) {
return manager().serviceClient().getWebApps()
.createMSDeployOperationAsync(resourceGroupName(), name(), msDeployInner);
}
@Override
public void verifyDomainOwnership(String certificateOrderName, String domainVerificationToken) {
verifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken).block();
}
@Override
public Mono<Void> verifyDomainOwnershipAsync(String certificateOrderName, String domainVerificationToken) {
IdentifierInner identifierInner = new IdentifierInner().withValue(domainVerificationToken);
return this
.manager()
.serviceClient()
.getWebApps()
.createOrUpdateDomainOwnershipIdentifierAsync(
resourceGroupName(), name(), certificateOrderName, identifierInner)
.then(Mono.empty());
}
@Override
public void start() {
startAsync().block();
}
@Override
public Mono<Void> startAsync() {
return manager()
.serviceClient()
.getWebApps()
.startAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void stop() {
stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return manager()
.serviceClient()
.getWebApps()
.stopAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void restart() {
restartAsync().block();
}
@Override
public Mono<Void> restartAsync() {
return manager()
.serviceClient()
.getWebApps()
.restartAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void swap(String slotName) {
swapAsync(slotName).block();
}
@Override
public Mono<Void> swapAsync(String slotName) {
return manager()
.serviceClient()
.getWebApps()
.swapSlotWithProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName))
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void applySlotConfigurations(String slotName) {
applySlotConfigurationsAsync(slotName).block();
}
@Override
public Mono<Void> applySlotConfigurationsAsync(String slotName) {
return manager()
.serviceClient()
.getWebApps()
.applySlotConfigToProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName))
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void resetSlotConfigurations() {
resetSlotConfigurationsAsync().block();
}
@Override
public Mono<Void> resetSlotConfigurationsAsync() {
return manager()
.serviceClient()
.getWebApps()
.resetProductionSlotConfigAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public byte[] getContainerLogs() {
return getContainerLogsAsync().block();
}
@Override
public Mono<byte[]> getContainerLogsAsync() {
return manager().serviceClient().getWebApps().getWebSiteContainerLogsAsync(resourceGroupName(), name())
.map(BinaryData::toBytes);
}
@Override
public byte[] getContainerLogsZip() {
return getContainerLogsZipAsync().block();
}
@Override
public Mono<byte[]> getContainerLogsZipAsync() {
return manager().serviceClient().getWebApps().getContainerLogsZipAsync(resourceGroupName(), name())
.map(BinaryData::toBytes);
}
@Override
Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner) {
return manager()
.serviceClient()
.getWebApps()
.updateDiagnosticLogsConfigAsync(resourceGroupName(), name(), siteLogsConfigInner);
}
private AppServicePlanImpl newDefaultAppServicePlan() {
String planName = this.manager().resourceManager().internalContext().randomResourceName(name() + "plan", 32);
return newDefaultAppServicePlan(planName);
}
private AppServicePlanImpl newDefaultAppServicePlan(String appServicePlanName) {
AppServicePlanImpl appServicePlan =
(AppServicePlanImpl) (this.manager().appServicePlans().define(appServicePlanName)).withRegion(regionName());
if (super.creatableGroup != null && isInCreateMode()) {
appServicePlan = appServicePlan.withNewResourceGroup(super.creatableGroup);
} else {
appServicePlan = appServicePlan.withExistingResourceGroup(resourceGroupName());
}
return appServicePlan;
}
public FluentImplT withNewFreeAppServicePlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, PricingTier.FREE_F1);
}
public FluentImplT withNewSharedAppServicePlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, PricingTier.SHARED_D1);
}
FluentImplT withNewAppServicePlan(OperatingSystem operatingSystem, PricingTier pricingTier) {
return withNewAppServicePlan(
newDefaultAppServicePlan().withOperatingSystem(operatingSystem).withPricingTier(pricingTier));
}
FluentImplT withNewAppServicePlan(
String appServicePlanName, OperatingSystem operatingSystem, PricingTier pricingTier) {
return withNewAppServicePlan(
newDefaultAppServicePlan(appServicePlanName)
.withOperatingSystem(operatingSystem)
.withPricingTier(pricingTier));
}
public FluentImplT withNewAppServicePlan(PricingTier pricingTier) {
return withNewAppServicePlan(operatingSystem(), pricingTier);
}
public FluentImplT withNewAppServicePlan(String appServicePlanName, PricingTier pricingTier) {
return withNewAppServicePlan(appServicePlanName, operatingSystem(), pricingTier);
}
public FluentImplT withNewAppServicePlan(Creatable<AppServicePlan> appServicePlanCreatable) {
this.addDependency(appServicePlanCreatable);
String id =
ResourceUtils
.constructResourceId(
this.manager().subscriptionId(),
resourceGroupName(),
"Microsoft.Web",
"serverFarms",
appServicePlanCreatable.name(),
"");
innerModel().withServerFarmId(id);
if (appServicePlanCreatable instanceof AppServicePlanImpl) {
return withOperatingSystem(((AppServicePlanImpl) appServicePlanCreatable).operatingSystem());
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Internal error, appServicePlanCreatable must be class AppServicePlanImpl"));
}
}
@SuppressWarnings("unchecked")
private FluentImplT withOperatingSystem(OperatingSystem os) {
if (os == OperatingSystem.LINUX) {
innerModel().withReserved(true);
innerModel().withKind(innerModel().kind() + ",linux");
}
return (FluentImplT) this;
}
public FluentImplT withExistingAppServicePlan(AppServicePlan appServicePlan) {
innerModel().withServerFarmId(appServicePlan.id());
this.withRegion(appServicePlan.regionName());
return withOperatingSystem(appServicePlanOperatingSystem(appServicePlan));
}
@SuppressWarnings("unchecked")
public FluentImplT withPublicDockerHubImage(String imageAndTag) {
cleanUpContainerSettings();
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag));
withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag);
return (FluentImplT) this;
}
public FluentImplT withPrivateDockerHubImage(String imageAndTag) {
return withPublicDockerHubImage(imageAndTag);
}
@SuppressWarnings("unchecked")
public FluentImplT withPrivateRegistryImage(String imageAndTag, String serverUrl) {
imageAndTag = Utils.smartCompletionPrivateRegistryImage(imageAndTag, serverUrl);
cleanUpContainerSettings();
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag));
withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag);
withAppSetting(SETTING_REGISTRY_SERVER, serverUrl);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withCredentials(String username, String password) {
withAppSetting(SETTING_REGISTRY_USERNAME, username);
withAppSetting(SETTING_REGISTRY_PASSWORD, password);
return (FluentImplT) this;
}
protected abstract void cleanUpContainerSettings();
protected void ensureLinuxPlan() {
if (OperatingSystem.WINDOWS.equals(operatingSystem())) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Docker container settings only apply to Linux app service plans."));
}
}
protected OperatingSystem appServicePlanOperatingSystem(AppServicePlan appServicePlan) {
return appServicePlan.operatingSystem();
}
@Override
public PagedIterable<PrivateLinkResource> listPrivateLinkResources() {
return new PagedIterable<>(listPrivateLinkResourcesAsync());
}
@Override
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() {
Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getWebApps()
.getPrivateLinkResourcesWithResponseAsync(this.resourceGroupName(), this.name())
.map(response -> new SimpleResponse<>(response, response.getValue().value().stream()
.map(PrivateLinkResourceImpl::new)
.collect(Collectors.toList())));
return PagedConverter.convertListToPagedFlux(retList);
}
@Override
public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() {
return new PagedIterable<>(listPrivateEndpointConnectionsAsync());
}
@Override
public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() {
return PagedConverter.mapPage(this.manager().serviceClient().getWebApps()
.getPrivateEndpointConnectionListAsync(this.resourceGroupName(), this.name()),
PrivateEndpointConnectionImpl::new);
}
@Override
public void approvePrivateEndpointConnection(String privateEndpointConnectionName) {
approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return this.manager().serviceClient().getWebApps()
.approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(),
privateEndpointConnectionName,
new PrivateLinkConnectionApprovalRequestResource().withPrivateLinkServiceConnectionState(
new PrivateLinkConnectionState()
.withStatus(PrivateEndpointServiceConnectionStatus.APPROVED.toString())
))
.then();
}
@Override
public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) {
rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return this.manager().serviceClient().getWebApps()
.approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(),
privateEndpointConnectionName,
new PrivateLinkConnectionApprovalRequestResource().withPrivateLinkServiceConnectionState(
new PrivateLinkConnectionState()
.withStatus(PrivateEndpointServiceConnectionStatus.REJECTED.toString())
))
.then();
}
} | class AppServiceBaseImpl<
FluentT extends WebAppBase,
FluentImplT extends AppServiceBaseImpl<FluentT, FluentImplT, FluentWithCreateT, FluentUpdateT>,
FluentWithCreateT,
FluentUpdateT>
extends WebAppBaseImpl<FluentT, FluentImplT>
implements
SupportsListingPrivateLinkResource,
SupportsListingPrivateEndpointConnection,
SupportsUpdatingPrivateEndpointConnection {
private final ClientLogger logger = new ClientLogger(getClass());
AppServiceBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, siteConfig, logConfig, manager);
}
@Override
Mono<SiteInner> createOrUpdateInner(SiteInner site) {
return this.manager().serviceClient().getWebApps().createOrUpdateAsync(resourceGroupName(), name(), site);
}
@Override
Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate) {
return this.manager().serviceClient().getWebApps().updateAsync(resourceGroupName(), name(), siteUpdate);
}
@Override
Mono<SiteInner> getInner() {
return this.manager().serviceClient().getWebApps().getByResourceGroupAsync(resourceGroupName(), name());
}
@Override
Mono<SiteConfigResourceInner> getConfigInner() {
return this.manager().serviceClient().getWebApps().getConfigurationAsync(resourceGroupName(), name());
}
@Override
Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) {
return this
.manager()
.serviceClient()
.getWebApps()
.createOrUpdateConfigurationAsync(resourceGroupName(), name(), siteConfig);
}
@Override
Mono<Void> deleteHostnameBinding(String hostname) {
return this.manager().serviceClient().getWebApps()
.deleteHostnameBindingAsync(resourceGroupName(), name(), hostname);
}
@Override
Mono<StringDictionaryInner> listAppSettings() {
return this.manager().serviceClient().getWebApps().listApplicationSettingsAsync(resourceGroupName(), name());
}
@Override
Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner) {
return this.manager().serviceClient().getWebApps()
.updateApplicationSettingsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<ConnectionStringDictionaryInner> listConnectionStrings() {
return this.manager().serviceClient().getWebApps().listConnectionStringsAsync(resourceGroupName(), name());
}
@Override
Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner) {
return this.manager().serviceClient().getWebApps()
.updateConnectionStringsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SlotConfigNamesResourceInner> listSlotConfigurations() {
return this.manager().serviceClient().getWebApps().listSlotConfigurationNamesAsync(resourceGroupName(), name());
}
@Override
Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner) {
return this.manager().serviceClient().getWebApps()
.updateSlotConfigurationNamesAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner) {
return this.manager().serviceClient().getWebApps()
.createOrUpdateSourceControlAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<Void> deleteSourceControl() {
return this.manager().serviceClient().getWebApps().deleteSourceControlAsync(resourceGroupName(), name());
}
@Override
Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner) {
return manager().serviceClient().getWebApps().updateAuthSettingsAsync(resourceGroupName(), name(), inner);
}
@Override
Mono<SiteAuthSettingsInner> getAuthentication() {
return manager().serviceClient().getWebApps().getAuthSettingsAsync(resourceGroupName(), name());
}
@Override
public Map<String, HostnameBinding> getHostnameBindings() {
return getHostnameBindingsAsync().block();
}
@Override
@SuppressWarnings("unchecked")
public Mono<Map<String, HostnameBinding>> getHostnameBindingsAsync() {
return PagedConverter.mapPage(this
.manager()
.serviceClient()
.getWebApps()
.listHostnameBindingsAsync(resourceGroupName(), name()),
hostNameBindingInner ->
new HostnameBindingImpl<>(hostNameBindingInner, (FluentImplT) AppServiceBaseImpl.this))
.collectList()
.map(
hostNameBindings ->
Collections
.<String, HostnameBinding>unmodifiableMap(
hostNameBindings
.stream()
.collect(
Collectors
.toMap(
binding -> binding.name().replace(name() + "/", ""),
Function.identity()))));
}
@Override
public PublishingProfile getPublishingProfile() {
return getPublishingProfileAsync().block();
}
@Override
public WebAppSourceControl getSourceControl() {
return getSourceControlAsync().block();
}
@Override
public Mono<WebAppSourceControl> getSourceControlAsync() {
return manager()
.serviceClient()
.getWebApps()
.getSourceControlAsync(resourceGroupName(), name())
.map(
siteSourceControlInner ->
new WebAppSourceControlImpl<>(siteSourceControlInner, AppServiceBaseImpl.this));
}
@Override
Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner) {
return manager().serviceClient().getWebApps()
.createMSDeployOperationAsync(resourceGroupName(), name(), msDeployInner);
}
@Override
public void verifyDomainOwnership(String certificateOrderName, String domainVerificationToken) {
verifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken).block();
}
@Override
public Mono<Void> verifyDomainOwnershipAsync(String certificateOrderName, String domainVerificationToken) {
IdentifierInner identifierInner = new IdentifierInner().withValue(domainVerificationToken);
return this
.manager()
.serviceClient()
.getWebApps()
.createOrUpdateDomainOwnershipIdentifierAsync(
resourceGroupName(), name(), certificateOrderName, identifierInner)
.then(Mono.empty());
}
@Override
public void start() {
startAsync().block();
}
@Override
public Mono<Void> startAsync() {
return manager()
.serviceClient()
.getWebApps()
.startAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void stop() {
stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return manager()
.serviceClient()
.getWebApps()
.stopAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void restart() {
restartAsync().block();
}
@Override
public Mono<Void> restartAsync() {
return manager()
.serviceClient()
.getWebApps()
.restartAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void swap(String slotName) {
swapAsync(slotName).block();
}
@Override
public Mono<Void> swapAsync(String slotName) {
return manager()
.serviceClient()
.getWebApps()
.swapSlotWithProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName))
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void applySlotConfigurations(String slotName) {
applySlotConfigurationsAsync(slotName).block();
}
@Override
public Mono<Void> applySlotConfigurationsAsync(String slotName) {
return manager()
.serviceClient()
.getWebApps()
.applySlotConfigToProductionAsync(resourceGroupName(), name(), new CsmSlotEntity().withTargetSlot(slotName))
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public void resetSlotConfigurations() {
resetSlotConfigurationsAsync().block();
}
@Override
public Mono<Void> resetSlotConfigurationsAsync() {
return manager()
.serviceClient()
.getWebApps()
.resetProductionSlotConfigAsync(resourceGroupName(), name())
.then(refreshAsync())
.then(Mono.empty());
}
@Override
public byte[] getContainerLogs() {
return getContainerLogsAsync().block();
}
@Override
public Mono<byte[]> getContainerLogsAsync() {
return manager().serviceClient().getWebApps().getWebSiteContainerLogsAsync(resourceGroupName(), name())
.map(BinaryData::toBytes);
}
@Override
public byte[] getContainerLogsZip() {
return getContainerLogsZipAsync().block();
}
@Override
public Mono<byte[]> getContainerLogsZipAsync() {
return manager().serviceClient().getWebApps().getContainerLogsZipAsync(resourceGroupName(), name())
.map(BinaryData::toBytes);
}
@Override
Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner) {
return manager()
.serviceClient()
.getWebApps()
.updateDiagnosticLogsConfigAsync(resourceGroupName(), name(), siteLogsConfigInner);
}
private AppServicePlanImpl newDefaultAppServicePlan() {
String planName = this.manager().resourceManager().internalContext().randomResourceName(name() + "plan", 32);
return newDefaultAppServicePlan(planName);
}
private AppServicePlanImpl newDefaultAppServicePlan(String appServicePlanName) {
AppServicePlanImpl appServicePlan =
(AppServicePlanImpl) (this.manager().appServicePlans().define(appServicePlanName)).withRegion(regionName());
if (super.creatableGroup != null && isInCreateMode()) {
appServicePlan = appServicePlan.withNewResourceGroup(super.creatableGroup);
} else {
appServicePlan = appServicePlan.withExistingResourceGroup(resourceGroupName());
}
return appServicePlan;
}
public FluentImplT withNewFreeAppServicePlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, PricingTier.FREE_F1);
}
public FluentImplT withNewSharedAppServicePlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, PricingTier.SHARED_D1);
}
FluentImplT withNewAppServicePlan(OperatingSystem operatingSystem, PricingTier pricingTier) {
return withNewAppServicePlan(
newDefaultAppServicePlan().withOperatingSystem(operatingSystem).withPricingTier(pricingTier));
}
FluentImplT withNewAppServicePlan(
String appServicePlanName, OperatingSystem operatingSystem, PricingTier pricingTier) {
return withNewAppServicePlan(
newDefaultAppServicePlan(appServicePlanName)
.withOperatingSystem(operatingSystem)
.withPricingTier(pricingTier));
}
public FluentImplT withNewAppServicePlan(PricingTier pricingTier) {
return withNewAppServicePlan(operatingSystem(), pricingTier);
}
public FluentImplT withNewAppServicePlan(String appServicePlanName, PricingTier pricingTier) {
return withNewAppServicePlan(appServicePlanName, operatingSystem(), pricingTier);
}
public FluentImplT withNewAppServicePlan(Creatable<AppServicePlan> appServicePlanCreatable) {
this.addDependency(appServicePlanCreatable);
String id =
ResourceUtils
.constructResourceId(
this.manager().subscriptionId(),
resourceGroupName(),
"Microsoft.Web",
"serverFarms",
appServicePlanCreatable.name(),
"");
innerModel().withServerFarmId(id);
if (appServicePlanCreatable instanceof AppServicePlanImpl) {
return withOperatingSystem(((AppServicePlanImpl) appServicePlanCreatable).operatingSystem());
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Internal error, appServicePlanCreatable must be class AppServicePlanImpl"));
}
}
@SuppressWarnings("unchecked")
private FluentImplT withOperatingSystem(OperatingSystem os) {
if (os == OperatingSystem.LINUX) {
innerModel().withReserved(true);
innerModel().withKind(innerModel().kind() + ",linux");
}
return (FluentImplT) this;
}
public FluentImplT withExistingAppServicePlan(AppServicePlan appServicePlan) {
innerModel().withServerFarmId(appServicePlan.id());
this.withRegion(appServicePlan.regionName());
return withOperatingSystem(appServicePlanOperatingSystem(appServicePlan));
}
@SuppressWarnings("unchecked")
public FluentImplT withPublicDockerHubImage(String imageAndTag) {
cleanUpContainerSettings();
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag));
withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag);
return (FluentImplT) this;
}
public FluentImplT withPrivateDockerHubImage(String imageAndTag) {
return withPublicDockerHubImage(imageAndTag);
}
@SuppressWarnings("unchecked")
public FluentImplT withPrivateRegistryImage(String imageAndTag, String serverUrl) {
imageAndTag = Utils.smartCompletionPrivateRegistryImage(imageAndTag, serverUrl);
cleanUpContainerSettings();
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag));
withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag);
withAppSetting(SETTING_REGISTRY_SERVER, serverUrl);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withCredentials(String username, String password) {
withAppSetting(SETTING_REGISTRY_USERNAME, username);
withAppSetting(SETTING_REGISTRY_PASSWORD, password);
return (FluentImplT) this;
}
protected abstract void cleanUpContainerSettings();
protected void ensureLinuxPlan() {
if (OperatingSystem.WINDOWS.equals(operatingSystem())) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Docker container settings only apply to Linux app service plans."));
}
}
protected OperatingSystem appServicePlanOperatingSystem(AppServicePlan appServicePlan) {
return appServicePlan.operatingSystem();
}
@Override
public PagedIterable<PrivateLinkResource> listPrivateLinkResources() {
return new PagedIterable<>(listPrivateLinkResourcesAsync());
}
@Override
public PagedFlux<PrivateLinkResource> listPrivateLinkResourcesAsync() {
Mono<Response<List<PrivateLinkResource>>> retList = this.manager().serviceClient().getWebApps()
.getPrivateLinkResourcesWithResponseAsync(this.resourceGroupName(), this.name())
.map(response -> new SimpleResponse<>(response, response.getValue().value().stream()
.map(PrivateLinkResourceImpl::new)
.collect(Collectors.toList())));
return PagedConverter.convertListToPagedFlux(retList);
}
@Override
public PagedIterable<PrivateEndpointConnection> listPrivateEndpointConnections() {
return new PagedIterable<>(listPrivateEndpointConnectionsAsync());
}
@Override
public PagedFlux<PrivateEndpointConnection> listPrivateEndpointConnectionsAsync() {
return PagedConverter.mapPage(this.manager().serviceClient().getWebApps()
.getPrivateEndpointConnectionListAsync(this.resourceGroupName(), this.name()),
PrivateEndpointConnectionImpl::new);
}
@Override
public void approvePrivateEndpointConnection(String privateEndpointConnectionName) {
approvePrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> approvePrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return this.manager().serviceClient().getWebApps()
.approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(),
privateEndpointConnectionName,
new PrivateLinkConnectionApprovalRequestResource().withPrivateLinkServiceConnectionState(
new PrivateLinkConnectionState()
.withStatus(PrivateEndpointServiceConnectionStatus.APPROVED.toString())
))
.then();
}
@Override
public void rejectPrivateEndpointConnection(String privateEndpointConnectionName) {
rejectPrivateEndpointConnectionAsync(privateEndpointConnectionName).block();
}
@Override
public Mono<Void> rejectPrivateEndpointConnectionAsync(String privateEndpointConnectionName) {
return this.manager().serviceClient().getWebApps()
.approveOrRejectPrivateEndpointConnectionAsync(this.resourceGroupName(), this.name(),
privateEndpointConnectionName,
new PrivateLinkConnectionApprovalRequestResource().withPrivateLinkServiceConnectionState(
new PrivateLinkConnectionState()
.withStatus(PrivateEndpointServiceConnectionStatus.REJECTED.toString())
))
.then();
}
} |
Renaming this doesn't work with the Autorest rename directive? ``` directive: - rename-model: from: KeyVauleFields to: SettingFields ``` | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
} | ClassCustomization settingFields = classCustomization.rename("SettingFields"); | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
These should be possible with Swagger transforms modifying the `description` of the enum. ``` directive: - from: swagger-document where: $.definitions.KeyVauleFields transform: > $.items["x-ms-enum"].values = [ { "value": "key", "name": "key", "description": "Populates the 'key' from the service. }, ... ]; ``` Where `value` is the value of the expandable string enum, in this case for `IS_READ_ONLY` below it would be `locked`, and `name` is the name of the constant. I would stick with using the JSON names of the configuration properties in case there is any issues with descriptions including link tags. | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
} | .setDescription("Populates the {@link ConfigurationSetting | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
If the renaming works, keep this constructor as it should be included. Same goes for keeping the `values` method as well. | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
} | classCustomization = classCustomization.customizeAst( | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
Let's also mark this method as deprecated as we shouldn't be using it anymore. It seems its purpose was to fix the fact we had the wrong casing for the enums. | private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
} | clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String") | private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
} | class name to SettingFields
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
I wouldn't add a constructor like this, this can cause problems with serialization as Autorest won't know about this and could/will generate assuming this class uses an empty constructor. | private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
} | "public SnapshotSettingFilter(String key) {", | private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
Why do we renamed `KeyValueFilter` to `SnapshotSettingFilter` instead of just `SettingFilter`? Couldn't it be possible in the future for this type to be used to filter non-snapshot settings? | private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
} | .rename("SnapshotSettingFilter"); | private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
Updated | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
} | ClassCustomization settingFields = classCustomization.rename("SettingFields"); | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
I thought we prefer to use the customized class instead of directive. I can change it | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
} | ClassCustomization settingFields = classCustomization.rename("SettingFields"); | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
KeyValueFilter is the swagger defined name, "KeyValue" is `ConfigurationSetting` in the public API. Currently, the proposed name for the filter in all language is `SnapshotSettingFilter` but it could change to another name in the future. I would keep a note of it. | private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
} | .rename("SnapshotSettingFilter"); | private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
Why do we need this constructor? Is key a required param in swagger? If so, autorest should generate this as a ctor arg. | private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
} | "public SnapshotSettingFilter(String key) {", | private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
If renaming through directive works, we should use that. Changing names of enums cannot be done through directive and that's when we should use customization. | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
classCustomization = classCustomization.removeMethod("values");
classCustomization.getConstant("KEY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LABEL")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("VALUE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("CONTENT_TYPE")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("LAST_MODIFIED")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("TAGS")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
classCustomization.getConstant("ETAG")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFields")
.get()
.getDefaultConstructor().get()
.remove());
classCustomization = classCustomization.renameEnumMember("LOCKED", "IS_READ_ONLY");
classCustomization.getConstant("IS_READ_ONLY")
.getJavadoc()
.setDescription("Populates the {@link ConfigurationSetting
ClassCustomization settingFields = classCustomization.rename("SettingFields");
settingFields.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(settingFields);
} | ClassCustomization settingFields = classCustomization.rename("SettingFields"); | private void customizeKeyValueFields(ClassCustomization classCustomization) {
classCustomization.addImports("java.util.Locale;");
classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;");
MethodCustomization fromString = classCustomization.getMethod("fromString");
fromString.getJavadoc()
.setDescription("Creates or finds a {@link SettingFields} from its string representation.")
.setReturn("the corresponding {@link SettingFields}");
fromString.removeAnnotation("JsonCreator");
classCustomization.getJavadoc()
.setDescription(joinWithNewline(
"",
"Fields in {@link ConfigurationSetting} that can be returned from GET queries.",
"",
"@see SettingSelector",
"@see ConfigurationAsyncClient",
""
));
addToStringMapper(classCustomization);
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("KeyValueFilter"));
customizeKeyValueFields(models.getClass("KeyValueFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
.setReturn("the {@link KeyValueFilter} object itself.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization = classCustomization.customizeAst(
ast -> ast.getClassByName("KeyValueFilter")
.get()
.getDefaultConstructor().get()
.remove())
.removeMethod("setKey")
.rename("SnapshotSettingFilter");
classCustomization.addConstructor(joinWithNewline(
"public SnapshotSettingFilter(String key) {",
" this.key = key;",
"}"))
.getJavadoc()
.setDescription("Constructor of {@link SnapshotSettingFilter}.")
.setParam("key", "The key value to set.");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
String className = classCustomization.getClassName();
ClassOrInterfaceDeclaration clazz = ast.getClassByName(className).get();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} | class AppConfigCustomization extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models");
customizeKeyValueFilter(models.getClass("SnapshotSettingFilter"));
customizeKeyValueFields(models.getClass("SettingFields"));
}
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
classCustomization.getMethod("setLabel")
.getJavadoc()
.setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getMethod("getKey")
.getJavadoc()
.setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
classCustomization.getMethod("getLabel")
.getJavadoc()
.setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
classCustomization.getConstructor("SnapshotSettingFilter")
.removeAnnotation("JsonCreator");
}
private ClassCustomization addToStringMapper(ClassCustomization classCustomization) {
return classCustomization.customizeAst(ast -> {
ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get();
clazz.removeJavaDocComment();
clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String")
.addParameter("SettingFields", "field")
.setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);"))))
.addAnnotation(Deprecated.class)
.setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline(
" * Converts the SettingFields to a string that is usable for HTTP requests and logging.",
" * @param field SettingFields to map.",
" * @return SettingFields as a lowercase string in the US locale.",
" * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests."
)));
});
}
private static String joinWithNewline(String... lines) {
return String.join("\n", lines);
}
} |
nit: ```java LOGGER.debug("Connecting to {} using Azure System Assigned Identity or Azure User Assigned Identity.", endpoint); ``` | List<AppConfigurationReplicaClient> buildClients(ConfigStore configStore) {
List<AppConfigurationReplicaClient> clients = new ArrayList<>();
int hasSingleConnectionString = StringUtils.hasText(configStore.getConnectionString()) ? 1 : 0;
int hasMultiEndpoints = configStore.getEndpoints().size() > 0 ? 1 : 0;
int hasMultiConnectionString = configStore.getConnectionStrings().size() > 0 ? 1 : 0;
if (hasSingleConnectionString + hasMultiEndpoints + hasMultiConnectionString > 1) {
throw new IllegalArgumentException("More than 1 Connection method was set for connecting to App Configuration.");
}
boolean connectionStringIsPresent = configStore.getConnectionString() != null || configStore.getConnectionStrings().size() > 0;
if (credentialConfigured && connectionStringIsPresent) {
throw new IllegalArgumentException("More than 1 Connection method was set for connecting to App Configuration.");
}
List<String> connectionStrings = configStore.getConnectionStrings();
List<String> endpoints = configStore.getEndpoints();
if (connectionStrings.size() == 0 && StringUtils.hasText(configStore.getConnectionString())) {
connectionStrings.add(configStore.getConnectionString());
}
if (endpoints.size() == 0 && StringUtils.hasText(configStore.getEndpoint())) {
endpoints.add(configStore.getEndpoint());
}
if (connectionStrings.size() > 0) {
for (String connectionString : connectionStrings) {
clientFactory.setConnectionStringProvider(new ConnectionStringConnector(connectionString));
String endpoint = getEndpointFromConnectionString(connectionString);
LOGGER.debug("Connecting to " + endpoint + " using Connecting String.");
ConfigurationClientBuilder builder = createBuilderInstance().connectionString(connectionString);
clients.add(modifyAndBuildClient(builder, endpoint, connectionStrings.size() - 1));
}
} else {
for (String endpoint : endpoints) {
ConfigurationClientBuilder builder = this.createBuilderInstance();
if (!credentialConfigured) {
LOGGER.debug("Connecting to " + endpoint + " using Azure System Assigned Identity or Azure User Assigned Identity.");
ManagedIdentityCredentialBuilder micBuilder = new ManagedIdentityCredentialBuilder();
builder.credential(micBuilder.build());
}
builder.endpoint(endpoint);
clients.add(modifyAndBuildClient(builder, endpoint, endpoints.size() - 1));
}
}
return clients;
} | LOGGER.debug("Connecting to " + endpoint + " using Azure System Assigned Identity or Azure User Assigned Identity."); | List<AppConfigurationReplicaClient> buildClients(ConfigStore configStore) {
List<AppConfigurationReplicaClient> clients = new ArrayList<>();
int hasSingleConnectionString = StringUtils.hasText(configStore.getConnectionString()) ? 1 : 0;
int hasMultiEndpoints = configStore.getEndpoints().size() > 0 ? 1 : 0;
int hasMultiConnectionString = configStore.getConnectionStrings().size() > 0 ? 1 : 0;
if (hasSingleConnectionString + hasMultiEndpoints + hasMultiConnectionString > 1) {
throw new IllegalArgumentException("More than 1 Connection method was set for connecting to App Configuration.");
}
boolean connectionStringIsPresent = configStore.getConnectionString() != null || configStore.getConnectionStrings().size() > 0;
if (credentialConfigured && connectionStringIsPresent) {
throw new IllegalArgumentException("More than 1 Connection method was set for connecting to App Configuration.");
}
List<String> connectionStrings = configStore.getConnectionStrings();
List<String> endpoints = configStore.getEndpoints();
if (connectionStrings.size() == 0 && StringUtils.hasText(configStore.getConnectionString())) {
connectionStrings.add(configStore.getConnectionString());
}
if (endpoints.size() == 0 && StringUtils.hasText(configStore.getEndpoint())) {
endpoints.add(configStore.getEndpoint());
}
if (connectionStrings.size() > 0) {
for (String connectionString : connectionStrings) {
clientFactory.setConnectionStringProvider(new ConnectionStringConnector(connectionString));
String endpoint = getEndpointFromConnectionString(connectionString);
LOGGER.debug("Connecting to " + endpoint + " using Connecting String.");
ConfigurationClientBuilder builder = createBuilderInstance().connectionString(connectionString);
clients.add(modifyAndBuildClient(builder, endpoint, connectionStrings.size() - 1));
}
} else {
for (String endpoint : endpoints) {
ConfigurationClientBuilder builder = this.createBuilderInstance();
if (!credentialConfigured) {
LOGGER.debug("Connecting to {} using Azure System Assigned Identity or Azure User Assigned Identity.", endpoint);
ManagedIdentityCredentialBuilder micBuilder = new ManagedIdentityCredentialBuilder();
builder.credential(micBuilder.build());
}
builder.endpoint(endpoint);
clients.add(modifyAndBuildClient(builder, endpoint, endpoints.size() - 1));
}
}
return clients;
} | class AppConfigurationReplicaClientsBuilder implements EnvironmentAware {
private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationReplicaClientsBuilder.class);
/**
* Invalid Connection String error message
*/
public static final String NON_EMPTY_MSG = "%s property should not be null or empty in the connection string of Azure Config Service.";
public static final String RETRY_MODE_PROPERTY_NAME = "retry.mode";
public static final String MAX_RETRIES_PROPERTY_NAME = "retry.exponential.max-retries";
public static final String BASE_DELAY_PROPERTY_NAME = "retry.exponential.base-delay";
public static final String MAX_DELAY_PROPERTY_NAME = "retry.exponential.max-delay";
private static final Duration DEFAULT_MIN_RETRY_POLICY = Duration.ofMillis(800);
private static final Duration DEFAULT_MAX_RETRY_POLICY = Duration.ofSeconds(8);
/**
* Connection String Regex format
*/
private static final String CONN_STRING_REGEXP = "Endpoint=([^;]+);Id=([^;]+);Secret=([^;]+)";
/**
* Invalid Formatted Connection String Error message
*/
public static final String ENDPOINT_ERR_MSG = String.format("Connection string does not follow format %s.", CONN_STRING_REGEXP);
private static final Pattern CONN_STRING_PATTERN = Pattern.compile(CONN_STRING_REGEXP);
private ConfigurationClientCustomizer clientProvider;
private final ConfigurationClientBuilderFactory clientFactory;
private Environment env;
private boolean isDev = false;
private boolean isKeyVaultConfigured = false;
private final boolean credentialConfigured;
private final int defaultMaxRetries;
public AppConfigurationReplicaClientsBuilder(int defaultMaxRetries, ConfigurationClientBuilderFactory clientFactory, boolean credentialConfigured) {
this.defaultMaxRetries = defaultMaxRetries;
this.clientFactory = clientFactory;
this.credentialConfigured = credentialConfigured;
}
/**
* Given a connection string, returns the endpoint inside of it.
*
* @param connectionString connection string to app configuration
* @return endpoint
* @throws IllegalStateException when connection string isn't valid.
*/
public static String getEndpointFromConnectionString(String connectionString) {
Assert.hasText(connectionString, "Connection string cannot be empty.");
Matcher matcher = CONN_STRING_PATTERN.matcher(connectionString);
if (!matcher.find()) {
throw new IllegalStateException(ENDPOINT_ERR_MSG);
}
String endpoint = matcher.group(1);
Assert.hasText(endpoint, String.format(NON_EMPTY_MSG, "Endpoint"));
return endpoint;
}
/**
* @param clientProvider the clientProvider to set
*/
public void setClientProvider(ConfigurationClientCustomizer clientProvider) {
this.clientProvider = clientProvider;
}
public void setIsKeyVaultConfigured(boolean isKeyVaultConfigured) {
this.isKeyVaultConfigured = isKeyVaultConfigured;
}
/**
* Builds all the clients for a connection.
*
* @throws IllegalArgumentException when more than 1 connection method is given.
*/
private AppConfigurationReplicaClient modifyAndBuildClient(ConfigurationClientBuilder builder, String endpoint, Integer replicaCount) {
TracingInfo tracingInfo = new TracingInfo(isDev, isKeyVaultConfigured, replicaCount, Configuration.getGlobalConfiguration());
builder.addPolicy(new BaseAppConfigurationPolicy(tracingInfo));
if (clientProvider != null) {
clientProvider.customize(builder, endpoint);
}
return new AppConfigurationReplicaClient(endpoint, builder.buildClient(), tracingInfo);
}
@Override
public void setEnvironment(Environment environment) {
for (String profile : environment.getActiveProfiles()) {
if ("dev".equalsIgnoreCase(profile)) {
this.isDev = true;
break;
}
}
this.env = environment;
}
protected ConfigurationClientBuilder createBuilderInstance() {
RetryStrategy retryStatagy = null;
String mode = env.getProperty(AzureGlobalProperties.PREFIX + "." + RETRY_MODE_PROPERTY_NAME);
String modeService = env.getProperty(AzureAppConfigurationProperties.PREFIX + "." + RETRY_MODE_PROPERTY_NAME);
if ("exponential".equals(mode) || "exponential".equals(modeService) || (mode == null && modeService == null)) {
Function<String, Integer> checkPropertyInt = parameter -> (Integer.parseInt(parameter));
Function<String, Duration> checkPropertyDuration = parameter -> (DurationStyle.detectAndParse(parameter));
int retries = checkProperty(MAX_RETRIES_PROPERTY_NAME, defaultMaxRetries, " isn't a valid integer, using default value.", checkPropertyInt);
Duration baseDelay = checkProperty(BASE_DELAY_PROPERTY_NAME, DEFAULT_MIN_RETRY_POLICY, " isn't a valid Duration, using default value.", checkPropertyDuration);
Duration maxDelay = checkProperty(MAX_DELAY_PROPERTY_NAME, DEFAULT_MAX_RETRY_POLICY, " isn't a valid Duration, using default value.", checkPropertyDuration);
retryStatagy = new ExponentialBackoff(retries, baseDelay, maxDelay);
}
ConfigurationClientBuilder builder = clientFactory.build();
if (retryStatagy != null) {
builder.retryPolicy(new RetryPolicy(retryStatagy));
}
return builder;
}
private <T> T checkProperty(String propertyName, T defaultValue, String errMsg, Function<String, T> fn) {
String envValue = System.getProperty(AzureGlobalProperties.PREFIX + "." + propertyName);
String envServiceValue = System.getProperty(AzureAppConfigurationProperties.PREFIX + "." + propertyName);
T value = defaultValue;
if (envServiceValue != null) {
try {
value = fn.apply(envServiceValue);
} catch (Exception e) {
LOGGER.warn("{}.{} {}", AzureAppConfigurationProperties.PREFIX, propertyName, errMsg);
}
} else if (envValue != null) {
try {
value = fn.apply(envValue);
} catch (Exception e) {
LOGGER.warn("{}.{} {}", AzureGlobalProperties.PREFIX, propertyName, errMsg);
}
}
return value;
}
private static class ConnectionStringConnector implements ServiceConnectionStringProvider<AzureServiceType.AppConfiguration> {
private final String connectionString;
ConnectionStringConnector(String connectionString) {
this.connectionString = connectionString;
}
@Override
public String getConnectionString() {
return connectionString;
}
@Override
public AppConfiguration getServiceType() {
return null;
}
}
} | class AppConfigurationReplicaClientsBuilder implements EnvironmentAware {
private static final Logger LOGGER = LoggerFactory.getLogger(AppConfigurationReplicaClientsBuilder.class);
/**
* Invalid Connection String error message
*/
public static final String NON_EMPTY_MSG = "%s property should not be null or empty in the connection string of Azure Config Service.";
public static final String RETRY_MODE_PROPERTY_NAME = "retry.mode";
public static final String MAX_RETRIES_PROPERTY_NAME = "retry.exponential.max-retries";
public static final String BASE_DELAY_PROPERTY_NAME = "retry.exponential.base-delay";
public static final String MAX_DELAY_PROPERTY_NAME = "retry.exponential.max-delay";
private static final Duration DEFAULT_MIN_RETRY_POLICY = Duration.ofMillis(800);
private static final Duration DEFAULT_MAX_RETRY_POLICY = Duration.ofSeconds(8);
/**
* Connection String Regex format
*/
private static final String CONN_STRING_REGEXP = "Endpoint=([^;]+);Id=([^;]+);Secret=([^;]+)";
/**
* Invalid Formatted Connection String Error message
*/
public static final String ENDPOINT_ERR_MSG = String.format("Connection string does not follow format %s.", CONN_STRING_REGEXP);
private static final Pattern CONN_STRING_PATTERN = Pattern.compile(CONN_STRING_REGEXP);
private ConfigurationClientCustomizer clientProvider;
private final ConfigurationClientBuilderFactory clientFactory;
private Environment env;
private boolean isDev = false;
private boolean isKeyVaultConfigured = false;
private final boolean credentialConfigured;
private final int defaultMaxRetries;
public AppConfigurationReplicaClientsBuilder(int defaultMaxRetries, ConfigurationClientBuilderFactory clientFactory, boolean credentialConfigured) {
this.defaultMaxRetries = defaultMaxRetries;
this.clientFactory = clientFactory;
this.credentialConfigured = credentialConfigured;
}
/**
* Given a connection string, returns the endpoint inside of it.
*
* @param connectionString connection string to app configuration
* @return endpoint
* @throws IllegalStateException when connection string isn't valid.
*/
public static String getEndpointFromConnectionString(String connectionString) {
Assert.hasText(connectionString, "Connection string cannot be empty.");
Matcher matcher = CONN_STRING_PATTERN.matcher(connectionString);
if (!matcher.find()) {
throw new IllegalStateException(ENDPOINT_ERR_MSG);
}
String endpoint = matcher.group(1);
Assert.hasText(endpoint, String.format(NON_EMPTY_MSG, "Endpoint"));
return endpoint;
}
/**
* @param clientProvider the clientProvider to set
*/
public void setClientProvider(ConfigurationClientCustomizer clientProvider) {
this.clientProvider = clientProvider;
}
public void setIsKeyVaultConfigured(boolean isKeyVaultConfigured) {
this.isKeyVaultConfigured = isKeyVaultConfigured;
}
/**
* Builds all the clients for a connection.
*
* @throws IllegalArgumentException when more than 1 connection method is given.
*/
private AppConfigurationReplicaClient modifyAndBuildClient(ConfigurationClientBuilder builder, String endpoint, Integer replicaCount) {
TracingInfo tracingInfo = new TracingInfo(isDev, isKeyVaultConfigured, replicaCount, Configuration.getGlobalConfiguration());
builder.addPolicy(new BaseAppConfigurationPolicy(tracingInfo));
if (clientProvider != null) {
clientProvider.customize(builder, endpoint);
}
return new AppConfigurationReplicaClient(endpoint, builder.buildClient(), tracingInfo);
}
@Override
public void setEnvironment(Environment environment) {
for (String profile : environment.getActiveProfiles()) {
if ("dev".equalsIgnoreCase(profile)) {
this.isDev = true;
break;
}
}
this.env = environment;
}
protected ConfigurationClientBuilder createBuilderInstance() {
RetryStrategy retryStatagy = null;
String mode = env.getProperty(AzureGlobalProperties.PREFIX + "." + RETRY_MODE_PROPERTY_NAME);
String modeService = env.getProperty(AzureAppConfigurationProperties.PREFIX + "." + RETRY_MODE_PROPERTY_NAME);
if ("exponential".equals(mode) || "exponential".equals(modeService) || (mode == null && modeService == null)) {
Function<String, Integer> checkPropertyInt = parameter -> (Integer.parseInt(parameter));
Function<String, Duration> checkPropertyDuration = parameter -> (DurationStyle.detectAndParse(parameter));
int retries = checkProperty(MAX_RETRIES_PROPERTY_NAME, defaultMaxRetries, " isn't a valid integer, using default value.", checkPropertyInt);
Duration baseDelay = checkProperty(BASE_DELAY_PROPERTY_NAME, DEFAULT_MIN_RETRY_POLICY, " isn't a valid Duration, using default value.", checkPropertyDuration);
Duration maxDelay = checkProperty(MAX_DELAY_PROPERTY_NAME, DEFAULT_MAX_RETRY_POLICY, " isn't a valid Duration, using default value.", checkPropertyDuration);
retryStatagy = new ExponentialBackoff(retries, baseDelay, maxDelay);
}
ConfigurationClientBuilder builder = clientFactory.build();
if (retryStatagy != null) {
builder.retryPolicy(new RetryPolicy(retryStatagy));
}
return builder;
}
private <T> T checkProperty(String propertyName, T defaultValue, String errMsg, Function<String, T> fn) {
String envValue = System.getProperty(AzureGlobalProperties.PREFIX + "." + propertyName);
String envServiceValue = System.getProperty(AzureAppConfigurationProperties.PREFIX + "." + propertyName);
T value = defaultValue;
if (envServiceValue != null) {
try {
value = fn.apply(envServiceValue);
} catch (Exception e) {
LOGGER.warn("{}.{} {}", AzureAppConfigurationProperties.PREFIX, propertyName, errMsg);
}
} else if (envValue != null) {
try {
value = fn.apply(envValue);
} catch (Exception e) {
LOGGER.warn("{}.{} {}", AzureGlobalProperties.PREFIX, propertyName, errMsg);
}
}
return value;
}
private static class ConnectionStringConnector implements ServiceConnectionStringProvider<AzureServiceType.AppConfiguration> {
private final String connectionString;
ConnectionStringConnector(String connectionString) {
this.connectionString = connectionString;
}
@Override
public String getConnectionString() {
return connectionString;
}
@Override
public AppConfiguration getServiceType() {
return null;
}
}
} |
This validation should happen in the build() method. User can set/reset this property but when they are attempting to build the client, there should be just one auth type. | public ConfigurationClientBuilder connectionString(String connectionString) {
if (this.tokenCredential != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Multiple forms of authentication found. TokenCredential should be null if using connection string."));
}
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
this.credential = new ConfigurationClientCredentials(connectionString);
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256"
+ " algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
this.connectionString = connectionString;
this.endpoint = credential.getBaseUri();
return this;
} | throw LOGGER.logExceptionAsError(new IllegalArgumentException( | public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
} | class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} | class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} |
How do you reset? Null isn’t allowed. | public ConfigurationClientBuilder connectionString(String connectionString) {
if (this.tokenCredential != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Multiple forms of authentication found. TokenCredential should be null if using connection string."));
}
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
this.credential = new ConfigurationClientCredentials(connectionString);
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256"
+ " algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
this.connectionString = connectionString;
this.endpoint = credential.getBaseUri();
return this;
} | throw LOGGER.logExceptionAsError(new IllegalArgumentException( | public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
} | class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} | class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} |
@srnagar We also create a ConfigurationClientCredentials object by giving the connectionString, which null is not allowed. And endpoint updates based on the ConfigurationClientCredentials. See https://github.com/Azure/azure-sdk-for-java/pull/34038/files#diff-e928333c4cc5354492953c97da447c61300a1d0f6fe45422bf021fd2db68e8c6R368 | public ConfigurationClientBuilder connectionString(String connectionString) {
if (this.tokenCredential != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Multiple forms of authentication found. TokenCredential should be null if using connection string."));
}
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
this.credential = new ConfigurationClientCredentials(connectionString);
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256"
+ " algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
this.connectionString = connectionString;
this.endpoint = credential.getBaseUri();
return this;
} | throw LOGGER.logExceptionAsError(new IllegalArgumentException( | public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
} | class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} | class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} |
I can move those eargerly null/empty connectionstring validation to the build() if needed. | public ConfigurationClientBuilder connectionString(String connectionString) {
if (this.tokenCredential != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"Multiple forms of authentication found. TokenCredential should be null if using connection string."));
}
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
this.credential = new ConfigurationClientCredentials(connectionString);
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException(
"The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256"
+ " algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
this.connectionString = connectionString;
this.endpoint = credential.getBaseUri();
return this;
} | throw LOGGER.logExceptionAsError(new IllegalArgumentException( | public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
} | class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} | class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} |
Do not update `this.credential` because if I use the same builder to create two clients, the second client will fail since both credential and connection string would be set then. | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
if (this.tokenCredential != null && this.connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (this.tokenCredential == null) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
this.credential = new ConfigurationClientCredentials(connectionString);
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
this.endpoint = credential.getBaseUri();
} else {
LOGGER.info("Authentication is " + this.tokenCredential.getClass());
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createHttpPipeline(syncTokenPolicy) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpoint)
.buildClient();
} | this.credential = new ConfigurationClientCredentials(connectionString); | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
String endpointLocal = null;
ConfigurationClientCredentials credentialsLocal = null;
TokenCredential tokenCredentialLocal = null;
if (tokenCredential == null && connectionString == null) {
throw LOGGER.logExceptionAsError(new NullPointerException("'tokenCredential' and 'connectionString' "
+ "both can not be null. Set one authentication before creating client."));
} else if (tokenCredential != null && connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (tokenCredential == null) {
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
credentialsLocal = new ConfigurationClientCredentials(connectionString);
endpointLocal = credentialsLocal.getBaseUri();
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
} else {
tokenCredentialLocal = this.tokenCredential;
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createDefaultHttpPipeline(
syncTokenPolicy, credentialsLocal, tokenCredentialLocal) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpointLocal)
.buildClient();
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createHttpPipeline(SyncTokenPolicy syncTokenPolicy) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (tokenCredential == null) {
buildEndpoint = getBuildEndpoint();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint)));
} else if (credential != null) {
policies.add(new ConfigurationCredentialsPolicy(credential));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code credential} is null.
* @throws IllegalArgumentException if {@code connectionString} is not null. App Configuration builder support
* single authentication per builder instance.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
private String getBuildEndpoint() {
if (endpoint != null) {
return endpoint;
} else if (credential != null) {
return credential.getBaseUri();
} else {
return null;
}
}
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createDefaultHttpPipeline(SyncTokenPolicy syncTokenPolicy,
ConfigurationClientCredentials credentials, TokenCredential tokenCredential) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (credentials != null) {
buildEndpoint = credentials.getBaseUri();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (credentials != null) {
policies.add(new ConfigurationCredentialsPolicy(credentials));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
} |
Same here, do not change the builder instance variables in the build method. Create a local variable instead. | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
if (this.tokenCredential != null && this.connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (this.tokenCredential == null) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
this.credential = new ConfigurationClientCredentials(connectionString);
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
this.endpoint = credential.getBaseUri();
} else {
LOGGER.info("Authentication is " + this.tokenCredential.getClass());
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createHttpPipeline(syncTokenPolicy) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpoint)
.buildClient();
} | this.endpoint = credential.getBaseUri(); | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
String endpointLocal = null;
ConfigurationClientCredentials credentialsLocal = null;
TokenCredential tokenCredentialLocal = null;
if (tokenCredential == null && connectionString == null) {
throw LOGGER.logExceptionAsError(new NullPointerException("'tokenCredential' and 'connectionString' "
+ "both can not be null. Set one authentication before creating client."));
} else if (tokenCredential != null && connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (tokenCredential == null) {
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
credentialsLocal = new ConfigurationClientCredentials(connectionString);
endpointLocal = credentialsLocal.getBaseUri();
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
} else {
tokenCredentialLocal = this.tokenCredential;
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createDefaultHttpPipeline(
syncTokenPolicy, credentialsLocal, tokenCredentialLocal) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpointLocal)
.buildClient();
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createHttpPipeline(SyncTokenPolicy syncTokenPolicy) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (tokenCredential == null) {
buildEndpoint = getBuildEndpoint();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint)));
} else if (credential != null) {
policies.add(new ConfigurationCredentialsPolicy(credential));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code credential} is null.
* @throws IllegalArgumentException if {@code connectionString} is not null. App Configuration builder support
* single authentication per builder instance.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
private String getBuildEndpoint() {
if (endpoint != null) {
return endpoint;
} else if (credential != null) {
return credential.getBaseUri();
} else {
return null;
}
}
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createDefaultHttpPipeline(SyncTokenPolicy syncTokenPolicy,
ConfigurationClientCredentials credentials, TokenCredential tokenCredential) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (credentials != null) {
buildEndpoint = credentials.getBaseUri();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (credentials != null) {
policies.add(new ConfigurationCredentialsPolicy(credentials));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
} |
This line can be removed. | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
if (this.tokenCredential != null && this.connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (this.tokenCredential == null) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
this.credential = new ConfigurationClientCredentials(connectionString);
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
this.endpoint = credential.getBaseUri();
} else {
LOGGER.info("Authentication is " + this.tokenCredential.getClass());
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createHttpPipeline(syncTokenPolicy) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpoint)
.buildClient();
} | LOGGER.info("Authentication is " + this.tokenCredential.getClass()); | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
String endpointLocal = null;
ConfigurationClientCredentials credentialsLocal = null;
TokenCredential tokenCredentialLocal = null;
if (tokenCredential == null && connectionString == null) {
throw LOGGER.logExceptionAsError(new NullPointerException("'tokenCredential' and 'connectionString' "
+ "both can not be null. Set one authentication before creating client."));
} else if (tokenCredential != null && connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (tokenCredential == null) {
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
credentialsLocal = new ConfigurationClientCredentials(connectionString);
endpointLocal = credentialsLocal.getBaseUri();
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
} else {
tokenCredentialLocal = this.tokenCredential;
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createDefaultHttpPipeline(
syncTokenPolicy, credentialsLocal, tokenCredentialLocal) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpointLocal)
.buildClient();
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createHttpPipeline(SyncTokenPolicy syncTokenPolicy) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (tokenCredential == null) {
buildEndpoint = getBuildEndpoint();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", buildEndpoint)));
} else if (credential != null) {
policies.add(new ConfigurationCredentialsPolicy(credential));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code credential} is null.
* @throws IllegalArgumentException if {@code connectionString} is not null. App Configuration builder support
* single authentication per builder instance.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
private String getBuildEndpoint() {
if (endpoint != null) {
return endpoint;
} else if (credential != null) {
return credential.getBaseUri();
} else {
return null;
}
}
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createDefaultHttpPipeline(SyncTokenPolicy syncTokenPolicy,
ConfigurationClientCredentials credentials, TokenCredential tokenCredential) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (credentials != null) {
buildEndpoint = credentials.getBaseUri();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (credentials != null) {
policies.add(new ConfigurationCredentialsPolicy(credentials));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
} |
This line is not needed. `connectionString` and `tokenCredential` both cannot be `null` if we get here. That condition is already handled above. | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
String endpointLocal = null;
ConfigurationClientCredentials credentialsLocal = null;
TokenCredential tokenCredentialLocal = null;
if (tokenCredential == null && connectionString == null) {
throw LOGGER.logExceptionAsError(new NullPointerException("'tokenCredential' and 'connectionString' "
+ "both can not be null. Set one authentication before creating client."));
} else if (tokenCredential != null && connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (tokenCredential == null) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
credentialsLocal = new ConfigurationClientCredentials(connectionString);
endpointLocal = credentialsLocal.getBaseUri();
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
} else {
tokenCredentialLocal = this.tokenCredential;
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createDefaultHttpPipeline(
syncTokenPolicy, credentialsLocal, tokenCredentialLocal) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpointLocal)
.buildClient();
} | Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
String endpointLocal = null;
ConfigurationClientCredentials credentialsLocal = null;
TokenCredential tokenCredentialLocal = null;
if (tokenCredential == null && connectionString == null) {
throw LOGGER.logExceptionAsError(new NullPointerException("'tokenCredential' and 'connectionString' "
+ "both can not be null. Set one authentication before creating client."));
} else if (tokenCredential != null && connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (tokenCredential == null) {
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
credentialsLocal = new ConfigurationClientCredentials(connectionString);
endpointLocal = credentialsLocal.getBaseUri();
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
} else {
tokenCredentialLocal = this.tokenCredential;
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createDefaultHttpPipeline(
syncTokenPolicy, credentialsLocal, tokenCredentialLocal) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpointLocal)
.buildClient();
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createDefaultHttpPipeline(SyncTokenPolicy syncTokenPolicy,
ConfigurationClientCredentials credentials, TokenCredential tokenCredential) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (credentials != null) {
buildEndpoint = credentials.getBaseUri();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (credentials != null) {
policies.add(new ConfigurationCredentialsPolicy(credentials));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createDefaultHttpPipeline(SyncTokenPolicy syncTokenPolicy,
ConfigurationClientCredentials credentials, TokenCredential tokenCredential) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (credentials != null) {
buildEndpoint = credentials.getBaseUri();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (credentials != null) {
policies.add(new ConfigurationCredentialsPolicy(credentials));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
} |
If `TokenCredential` is used `endpointLocal` will be null | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
String endpointLocal = null;
ConfigurationClientCredentials credentialsLocal = null;
TokenCredential tokenCredentialLocal = null;
if (tokenCredential == null && connectionString == null) {
throw LOGGER.logExceptionAsError(new NullPointerException("'tokenCredential' and 'connectionString' "
+ "both can not be null. Set one authentication before creating client."));
} else if (tokenCredential != null && connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (tokenCredential == null) {
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
credentialsLocal = new ConfigurationClientCredentials(connectionString);
endpointLocal = credentialsLocal.getBaseUri();
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
} else {
tokenCredentialLocal = this.tokenCredential;
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createDefaultHttpPipeline(
syncTokenPolicy, credentialsLocal, tokenCredentialLocal) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpointLocal)
.buildClient();
} | .endpoint(endpointLocal) | private AzureAppConfigurationImpl buildInnerClient(SyncTokenPolicy syncTokenPolicy) {
String endpointLocal = null;
ConfigurationClientCredentials credentialsLocal = null;
TokenCredential tokenCredentialLocal = null;
if (tokenCredential == null && connectionString == null) {
throw LOGGER.logExceptionAsError(new NullPointerException("'tokenCredential' and 'connectionString' "
+ "both can not be null. Set one authentication before creating client."));
} else if (tokenCredential != null && connectionString != null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("Multiple forms of authentication found. "
+ "TokenCredential should be null if using connection string, vice versa."));
} else if (tokenCredential == null) {
if (connectionString.isEmpty()) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("'connectionString' cannot be an empty string."));
}
try {
credentialsLocal = new ConfigurationClientCredentials(connectionString);
endpointLocal = credentialsLocal.getBaseUri();
} catch (InvalidKeyException err) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("The secret contained within the"
+ " connection string is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err));
} catch (NoSuchAlgorithmException err) {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err));
}
} else {
tokenCredentialLocal = this.tokenCredential;
}
ConfigurationServiceVersion serviceVersion = (version != null)
? version
: ConfigurationServiceVersion.getLatest();
return new AzureAppConfigurationImplBuilder()
.pipeline(pipeline == null ? createDefaultHttpPipeline(
syncTokenPolicy, credentialsLocal, tokenCredentialLocal) : pipeline)
.apiVersion(serviceVersion.getVersion())
.endpoint(endpointLocal)
.buildClient();
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createDefaultHttpPipeline(SyncTokenPolicy syncTokenPolicy,
ConfigurationClientCredentials credentials, TokenCredential tokenCredential) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (credentials != null) {
buildEndpoint = credentials.getBaseUri();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (credentials != null) {
policies.add(new ConfigurationCredentialsPolicy(credentials));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
} | class ConfigurationClientBuilder implements
TokenCredentialTrait<ConfigurationClientBuilder>,
ConnectionStringTrait<ConfigurationClientBuilder>,
HttpTrait<ConfigurationClientBuilder>,
ConfigurationTrait<ConfigurationClientBuilder>,
EndpointTrait<ConfigurationClientBuilder> {
private static final String CLIENT_NAME;
private static final String CLIENT_VERSION;
private static final HttpPipelinePolicy ADD_HEADERS_POLICY;
static {
Map<String, String> properties = CoreUtils.getProperties("azure-data-appconfiguration.properties");
CLIENT_NAME = properties.getOrDefault("name", "UnknownName");
CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion");
ADD_HEADERS_POLICY = new AddHeadersPolicy(new HttpHeaders()
.set("x-ms-return-client-request-id", "true")
.set("Content-Type", "application/json")
.set("Accept", "application/vnd.microsoft.azconfig.kv+json"));
}
private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private String connectionString;
private ConfigurationClientCredentials credential;
private TokenCredential tokenCredential;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private RetryOptions retryOptions;
private Configuration configuration;
private ConfigurationServiceVersion version;
/**
* Constructs a new builder used to configure and build {@link ConfigurationClient ConfigurationClients} and {@link
* ConfigurationAsyncClient ConfigurationAsyncClients}.
*/
public ConfigurationClientBuilder() {
httpLogOptions = new HttpLogOptions();
}
/**
* Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is
* called a new instance of {@link ConfigurationClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationClient client}. All other builder settings are ignored.</p>
*
* @return A ConfigurationClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationClient buildClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created.
* <p>
* If {@link
* endpoint} are used to create the {@link ConfigurationAsyncClient client}. All other builder settings are
* ignored.
*
* @return A ConfigurationAsyncClient with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
* @throws IllegalStateException If both {@link
* and {@link
*/
public ConfigurationAsyncClient buildAsyncClient() {
final SyncTokenPolicy syncTokenPolicy = new SyncTokenPolicy();
return new ConfigurationAsyncClient(buildInnerClient(syncTokenPolicy), syncTokenPolicy);
}
/**
* Builds an instance of ConfigurationClientImpl with the provided parameters.
*
* @return an instance of ConfigurationClientImpl.
* @throws NullPointerException If {@code connectionString} is null.
* @throws IllegalArgumentException If {@code connectionString} is an empty string, the {@code connectionString}
* secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated.
* @throws IllegalArgumentException if {@code tokenCredential} is not null. App Configuration builder support single
* authentication per builder instance.
*/
private HttpPipeline createDefaultHttpPipeline(SyncTokenPolicy syncTokenPolicy,
ConfigurationClientCredentials credentials, TokenCredential tokenCredential) {
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
String buildEndpoint = endpoint;
if (credentials != null) {
buildEndpoint = credentials.getBaseUri();
}
Objects.requireNonNull(buildEndpoint, "'Endpoint' is required and can not be null.");
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(
getApplicationId(clientOptions, httpLogOptions), CLIENT_NAME, CLIENT_VERSION, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
policies.add(ADD_HEADERS_POLICY);
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions,
new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS)));
policies.add(new AddDatePolicy());
if (tokenCredential != null) {
policies.add(
new BearerTokenAuthenticationPolicy(tokenCredential, String.format("%s/.default", endpoint)));
} else if (credentials != null) {
policies.add(new ConfigurationCredentialsPolicy(credentials));
} else {
throw LOGGER.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.add(syncTokenPolicy);
policies.addAll(perRetryPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(
header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.tracer(createTracer(clientOptions))
.build();
}
private static Tracer createTracer(ClientOptions clientOptions) {
TracingOptions tracingOptions = clientOptions == null ? null : clientOptions.getTracingOptions();
return TracerProvider.getDefaultProvider()
.createTracer(CLIENT_NAME, CLIENT_VERSION, APP_CONFIG_TRACING_NAMESPACE_VALUE, tracingOptions);
}
/**
* Sets the service endpoint for the Azure App Configuration instance.
*
* @param endpoint The URL of the Azure App Configuration instance.
* @return The updated ConfigurationClientBuilder object.
* @throws IllegalArgumentException If {@code endpoint} is null, or it cannot be parsed into a valid URL.
*/
@Override
public ConfigurationClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
* @see HttpClientOptions
* @return the updated ConfigurationClientBuilder object
*/
@Override
public ConfigurationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential to use when authenticating HTTP requests. Also, sets the {@link
* for this ConfigurationClientBuilder.
*
* @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};
* secret={secret_value}"
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder connectionString(String connectionString) {
this.connectionString = connectionString;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https:
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to
* and from the service.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ConfigurationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param client The {@link HttpClient} to use for requests.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
LOGGER.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* The {@link
*
* @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ConfigurationClientBuilder object.
*/
@Override
public ConfigurationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link ConfigurationClientBuilder
* build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}.
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
* @return The updated {@link ConfigurationClientBuilder} object.
*/
@Override
public ConfigurationClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the {@link ConfigurationServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link ConfigurationServiceVersion} of the service to be used when making requests.
* @return The updated ConfigurationClientBuilder object.
*/
public ConfigurationClientBuilder serviceVersion(ConfigurationServiceVersion version) {
this.version = version;
return this;
}
} |
we probably want comment warning on both tests, stating that HSM must be deleted and purged ASAP (one could stop the test and not gets to "finally"). | public void canCrudManagedHsms() {
String mhsmName = generateRandomResourceName("mhsm", 10);
ManagedHsm managedHsm = createManagedHsm(mhsmName);
try {
PagedIterable<ManagedHsm> hsms = keyVaultManager.managedHsms()
.listByResourceGroup(rgName);
Assertions.assertTrue(hsms.stream().anyMatch(mhsm -> mhsm.name().equals(mhsmName)));
ManagedHsm hsm = keyVaultManager.managedHsms()
.getByResourceGroup(rgName, managedHsm.name());
String tenantId = hsm.tenantId();
Assertions.assertNotNull(tenantId);
ManagedHsmSku sku = hsm.sku();
Assertions.assertNotNull(sku);
List<String> initialAdminObjectIds = hsm.initialAdminObjectIds();
Assertions.assertEquals(1, initialAdminObjectIds.size());
String hsmUri = hsm.hsmUri();
Assertions.assertNotNull(hsmUri);
boolean softDelete = hsm.isSoftDeleteEnabled();
Assertions.assertTrue(softDelete);
Integer softDeleteRetentionDays = hsm.softDeleteRetentionDays();
Assertions.assertEquals(7, softDeleteRetentionDays);
boolean purgeProtectionEnabled = hsm.isPurgeProtectionEnabled();
Assertions.assertFalse(purgeProtectionEnabled);
MhsmNetworkRuleSet ruleSet = hsm.networkRuleSet();
Assertions.assertNotNull(ruleSet);
PublicNetworkAccess publicNetworkAccess = hsm.publicNetworkAccess();
Assertions.assertEquals(PublicNetworkAccess.ENABLED, publicNetworkAccess);
OffsetDateTime scheduledPurgeDate = hsm.scheduledPurgeDate();
Assertions.assertNull(scheduledPurgeDate);
} finally {
keyVaultManager.managedHsms().deleteById(managedHsm.id());
keyVaultManager.serviceClient().getManagedHsms().purgeDeleted(managedHsm.name(), managedHsm.regionName());
}
} | String mhsmName = generateRandomResourceName("mhsm", 10); | public void canCrudManagedHsms() {
String mhsmName = generateRandomResourceName("mhsm", 10);
ManagedHsm managedHsm = createManagedHsm(mhsmName);
try {
PagedIterable<ManagedHsm> hsms = keyVaultManager.managedHsms()
.listByResourceGroup(rgName);
Assertions.assertTrue(hsms.stream().anyMatch(mhsm -> mhsm.name().equals(mhsmName)));
ManagedHsm hsm = keyVaultManager.managedHsms()
.getByResourceGroup(rgName, managedHsm.name());
String tenantId = hsm.tenantId();
Assertions.assertNotNull(tenantId);
ManagedHsmSku sku = hsm.sku();
Assertions.assertNotNull(sku);
List<String> initialAdminObjectIds = hsm.initialAdminObjectIds();
Assertions.assertEquals(1, initialAdminObjectIds.size());
String hsmUri = hsm.hsmUri();
Assertions.assertNotNull(hsmUri);
boolean softDelete = hsm.isSoftDeleteEnabled();
Assertions.assertTrue(softDelete);
Integer softDeleteRetentionDays = hsm.softDeleteRetentionInDays();
Assertions.assertEquals(7, softDeleteRetentionDays);
boolean purgeProtectionEnabled = hsm.isPurgeProtectionEnabled();
Assertions.assertFalse(purgeProtectionEnabled);
MhsmNetworkRuleSet ruleSet = hsm.networkRuleSet();
Assertions.assertNotNull(ruleSet);
PublicNetworkAccess publicNetworkAccess = hsm.publicNetworkAccess();
Assertions.assertEquals(PublicNetworkAccess.ENABLED, publicNetworkAccess);
OffsetDateTime scheduledPurgeDate = hsm.scheduledPurgeDate();
Assertions.assertNull(scheduledPurgeDate);
} finally {
keyVaultManager.managedHsms().deleteById(managedHsm.id());
keyVaultManager.serviceClient().getManagedHsms().purgeDeleted(managedHsm.name(), managedHsm.regionName());
}
} | class ManagedHsmTests extends KeyVaultManagementTest {
@Override
protected void cleanUpResources() {
if (rgName != null) {
keyVaultManager.resourceManager().resourceGroups().beginDeleteByName(rgName);
}
}
@BeforeAll
public static void setup() {
AzureEnvironment.AZURE.getEndpoints().put("managedHsm", ".managedhsm.azure.net");
}
@Test
/*
* create or get managed hsm instance
*/
private ManagedHsm createManagedHsm(String mhsmName) {
String objectId = authorizationManager
.servicePrincipals()
.getByNameAsync(clientIdFromFile())
.block()
.id();
keyVaultManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST2).create();
ManagedHsmInner inner = keyVaultManager.serviceClient()
.getManagedHsms()
.createOrUpdate(
rgName,
mhsmName,
new ManagedHsmInner()
.withLocation(Region.US_EAST2.name())
.withSku(
new ManagedHsmSku().withFamily(ManagedHsmSkuFamily.B).withName(ManagedHsmSkuName.STANDARD_B1))
.withProperties(
new ManagedHsmProperties()
.withTenantId(UUID.fromString(authorizationManager.tenantId()))
.withInitialAdminObjectIds(Arrays.asList(objectId))
.withEnableSoftDelete(true)
.withSoftDeleteRetentionInDays(7)
.withEnablePurgeProtection(false)),
Context.NONE);
keyVaultManager.serviceClient()
.getManagedHsms()
.createOrUpdate(rgName, inner.name(), inner);
return keyVaultManager.managedHsms().getByResourceGroup(rgName, inner.name());
}
} | class ManagedHsmTests extends KeyVaultManagementTest {
@Override
protected void cleanUpResources() {
if (rgName != null) {
keyVaultManager.resourceManager().resourceGroups().beginDeleteByName(rgName);
}
}
/**
* Note: Managed HSM instance is costly and it'll still cost you even if you delete the instance or the associated
* resource group, unless the instance is <string>purged</string>.
* <p>So, please be careful when running this test and always double check that the instance has been
* {@link com.azure.resourcemanager.keyvault.fluent.ManagedHsmsClient
* <p>You can use {@link com.azure.resourcemanager.keyvault.fluent.ManagedHsmsClient
* that's not purged after deletion.</p>
* @see <a href="https:
*/
@Test
/*
* create or get managed hsm instance
*/
private ManagedHsm createManagedHsm(String mhsmName) {
String objectId = authorizationManager
.servicePrincipals()
.getByNameAsync(clientIdFromFile())
.block()
.id();
keyVaultManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST2).create();
ManagedHsmInner inner = keyVaultManager.serviceClient()
.getManagedHsms()
.createOrUpdate(
rgName,
mhsmName,
new ManagedHsmInner()
.withLocation(Region.US_EAST2.name())
.withSku(
new ManagedHsmSku().withFamily(ManagedHsmSkuFamily.B).withName(ManagedHsmSkuName.STANDARD_B1))
.withProperties(
new ManagedHsmProperties()
.withTenantId(UUID.fromString(authorizationManager.tenantId()))
.withInitialAdminObjectIds(Arrays.asList(objectId))
.withEnableSoftDelete(true)
.withSoftDeleteRetentionInDays(7)
.withEnablePurgeProtection(false)),
Context.NONE);
keyVaultManager.serviceClient()
.getManagedHsms()
.createOrUpdate(rgName, inner.name(), inner);
return keyVaultManager.managedHsms().getByResourceGroup(rgName, inner.name());
}
} |
Sure, indeed. | public void canCrudManagedHsms() {
String mhsmName = generateRandomResourceName("mhsm", 10);
ManagedHsm managedHsm = createManagedHsm(mhsmName);
try {
PagedIterable<ManagedHsm> hsms = keyVaultManager.managedHsms()
.listByResourceGroup(rgName);
Assertions.assertTrue(hsms.stream().anyMatch(mhsm -> mhsm.name().equals(mhsmName)));
ManagedHsm hsm = keyVaultManager.managedHsms()
.getByResourceGroup(rgName, managedHsm.name());
String tenantId = hsm.tenantId();
Assertions.assertNotNull(tenantId);
ManagedHsmSku sku = hsm.sku();
Assertions.assertNotNull(sku);
List<String> initialAdminObjectIds = hsm.initialAdminObjectIds();
Assertions.assertEquals(1, initialAdminObjectIds.size());
String hsmUri = hsm.hsmUri();
Assertions.assertNotNull(hsmUri);
boolean softDelete = hsm.isSoftDeleteEnabled();
Assertions.assertTrue(softDelete);
Integer softDeleteRetentionDays = hsm.softDeleteRetentionDays();
Assertions.assertEquals(7, softDeleteRetentionDays);
boolean purgeProtectionEnabled = hsm.isPurgeProtectionEnabled();
Assertions.assertFalse(purgeProtectionEnabled);
MhsmNetworkRuleSet ruleSet = hsm.networkRuleSet();
Assertions.assertNotNull(ruleSet);
PublicNetworkAccess publicNetworkAccess = hsm.publicNetworkAccess();
Assertions.assertEquals(PublicNetworkAccess.ENABLED, publicNetworkAccess);
OffsetDateTime scheduledPurgeDate = hsm.scheduledPurgeDate();
Assertions.assertNull(scheduledPurgeDate);
} finally {
keyVaultManager.managedHsms().deleteById(managedHsm.id());
keyVaultManager.serviceClient().getManagedHsms().purgeDeleted(managedHsm.name(), managedHsm.regionName());
}
} | String mhsmName = generateRandomResourceName("mhsm", 10); | public void canCrudManagedHsms() {
String mhsmName = generateRandomResourceName("mhsm", 10);
ManagedHsm managedHsm = createManagedHsm(mhsmName);
try {
PagedIterable<ManagedHsm> hsms = keyVaultManager.managedHsms()
.listByResourceGroup(rgName);
Assertions.assertTrue(hsms.stream().anyMatch(mhsm -> mhsm.name().equals(mhsmName)));
ManagedHsm hsm = keyVaultManager.managedHsms()
.getByResourceGroup(rgName, managedHsm.name());
String tenantId = hsm.tenantId();
Assertions.assertNotNull(tenantId);
ManagedHsmSku sku = hsm.sku();
Assertions.assertNotNull(sku);
List<String> initialAdminObjectIds = hsm.initialAdminObjectIds();
Assertions.assertEquals(1, initialAdminObjectIds.size());
String hsmUri = hsm.hsmUri();
Assertions.assertNotNull(hsmUri);
boolean softDelete = hsm.isSoftDeleteEnabled();
Assertions.assertTrue(softDelete);
Integer softDeleteRetentionDays = hsm.softDeleteRetentionInDays();
Assertions.assertEquals(7, softDeleteRetentionDays);
boolean purgeProtectionEnabled = hsm.isPurgeProtectionEnabled();
Assertions.assertFalse(purgeProtectionEnabled);
MhsmNetworkRuleSet ruleSet = hsm.networkRuleSet();
Assertions.assertNotNull(ruleSet);
PublicNetworkAccess publicNetworkAccess = hsm.publicNetworkAccess();
Assertions.assertEquals(PublicNetworkAccess.ENABLED, publicNetworkAccess);
OffsetDateTime scheduledPurgeDate = hsm.scheduledPurgeDate();
Assertions.assertNull(scheduledPurgeDate);
} finally {
keyVaultManager.managedHsms().deleteById(managedHsm.id());
keyVaultManager.serviceClient().getManagedHsms().purgeDeleted(managedHsm.name(), managedHsm.regionName());
}
} | class ManagedHsmTests extends KeyVaultManagementTest {
@Override
protected void cleanUpResources() {
if (rgName != null) {
keyVaultManager.resourceManager().resourceGroups().beginDeleteByName(rgName);
}
}
@BeforeAll
public static void setup() {
AzureEnvironment.AZURE.getEndpoints().put("managedHsm", ".managedhsm.azure.net");
}
@Test
/*
* create or get managed hsm instance
*/
private ManagedHsm createManagedHsm(String mhsmName) {
String objectId = authorizationManager
.servicePrincipals()
.getByNameAsync(clientIdFromFile())
.block()
.id();
keyVaultManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST2).create();
ManagedHsmInner inner = keyVaultManager.serviceClient()
.getManagedHsms()
.createOrUpdate(
rgName,
mhsmName,
new ManagedHsmInner()
.withLocation(Region.US_EAST2.name())
.withSku(
new ManagedHsmSku().withFamily(ManagedHsmSkuFamily.B).withName(ManagedHsmSkuName.STANDARD_B1))
.withProperties(
new ManagedHsmProperties()
.withTenantId(UUID.fromString(authorizationManager.tenantId()))
.withInitialAdminObjectIds(Arrays.asList(objectId))
.withEnableSoftDelete(true)
.withSoftDeleteRetentionInDays(7)
.withEnablePurgeProtection(false)),
Context.NONE);
keyVaultManager.serviceClient()
.getManagedHsms()
.createOrUpdate(rgName, inner.name(), inner);
return keyVaultManager.managedHsms().getByResourceGroup(rgName, inner.name());
}
} | class ManagedHsmTests extends KeyVaultManagementTest {
@Override
protected void cleanUpResources() {
if (rgName != null) {
keyVaultManager.resourceManager().resourceGroups().beginDeleteByName(rgName);
}
}
/**
* Note: Managed HSM instance is costly and it'll still cost you even if you delete the instance or the associated
* resource group, unless the instance is <string>purged</string>.
* <p>So, please be careful when running this test and always double check that the instance has been
* {@link com.azure.resourcemanager.keyvault.fluent.ManagedHsmsClient
* <p>You can use {@link com.azure.resourcemanager.keyvault.fluent.ManagedHsmsClient
* that's not purged after deletion.</p>
* @see <a href="https:
*/
@Test
/*
* create or get managed hsm instance
*/
private ManagedHsm createManagedHsm(String mhsmName) {
String objectId = authorizationManager
.servicePrincipals()
.getByNameAsync(clientIdFromFile())
.block()
.id();
keyVaultManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST2).create();
ManagedHsmInner inner = keyVaultManager.serviceClient()
.getManagedHsms()
.createOrUpdate(
rgName,
mhsmName,
new ManagedHsmInner()
.withLocation(Region.US_EAST2.name())
.withSku(
new ManagedHsmSku().withFamily(ManagedHsmSkuFamily.B).withName(ManagedHsmSkuName.STANDARD_B1))
.withProperties(
new ManagedHsmProperties()
.withTenantId(UUID.fromString(authorizationManager.tenantId()))
.withInitialAdminObjectIds(Arrays.asList(objectId))
.withEnableSoftDelete(true)
.withSoftDeleteRetentionInDays(7)
.withEnablePurgeProtection(false)),
Context.NONE);
keyVaultManager.serviceClient()
.getManagedHsms()
.createOrUpdate(rgName, inner.name(), inner);
return keyVaultManager.managedHsms().getByResourceGroup(rgName, inner.name());
}
} |
question - what's this sequence number for? | private ParticipantsUpdated(@JsonProperty("participants") List<Map<String, Object>> participants) {
this.sequenceNumber = 0;
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
this.participants = participants
.stream()
.map(item -> mapper.convertValue(item, CallParticipantInternal.class))
.collect(Collectors.toList())
.stream()
.map(CallParticipantConverter::convert)
.collect(Collectors.toList());
} | this.sequenceNumber = 0; | private ParticipantsUpdated(@JsonProperty("participants") List<Map<String, Object>> participants) {
this.sequenceNumber = 0;
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
this.participants = participants
.stream()
.map(item -> mapper.convertValue(item, CallParticipantInternal.class))
.collect(Collectors.toList())
.stream()
.map(CallParticipantConverter::convert)
.collect(Collectors.toList());
} | class ParticipantsUpdated extends CallAutomationEventBase {
/*
* List of current participants in the call.
*/
@JsonIgnore
private final List<CallParticipant> participants;
@JsonProperty(value = "sequenceNumber")
private final int sequenceNumber;
@JsonCreator
/**
* Get the participants property: List of current participants in the call.
*
* @return the participants value.
*/
public List<CallParticipant> getParticipants() {
return this.participants;
}
} | class ParticipantsUpdated extends CallAutomationEventBase {
/*
* List of current participants in the call.
*/
@JsonIgnore
private final List<CallParticipant> participants;
@JsonProperty(value = "sequenceNumber")
private final int sequenceNumber;
@JsonCreator
/**
* Get the participants property: List of current participants in the call.
*
* @return the participants value.
*/
public List<CallParticipant> getParticipants() {
return this.participants;
}
} |
This is a new field which tells the order of events | private ParticipantsUpdated(@JsonProperty("participants") List<Map<String, Object>> participants) {
this.sequenceNumber = 0;
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
this.participants = participants
.stream()
.map(item -> mapper.convertValue(item, CallParticipantInternal.class))
.collect(Collectors.toList())
.stream()
.map(CallParticipantConverter::convert)
.collect(Collectors.toList());
} | this.sequenceNumber = 0; | private ParticipantsUpdated(@JsonProperty("participants") List<Map<String, Object>> participants) {
this.sequenceNumber = 0;
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
this.participants = participants
.stream()
.map(item -> mapper.convertValue(item, CallParticipantInternal.class))
.collect(Collectors.toList())
.stream()
.map(CallParticipantConverter::convert)
.collect(Collectors.toList());
} | class ParticipantsUpdated extends CallAutomationEventBase {
/*
* List of current participants in the call.
*/
@JsonIgnore
private final List<CallParticipant> participants;
@JsonProperty(value = "sequenceNumber")
private final int sequenceNumber;
@JsonCreator
/**
* Get the participants property: List of current participants in the call.
*
* @return the participants value.
*/
public List<CallParticipant> getParticipants() {
return this.participants;
}
} | class ParticipantsUpdated extends CallAutomationEventBase {
/*
* List of current participants in the call.
*/
@JsonIgnore
private final List<CallParticipant> participants;
@JsonProperty(value = "sequenceNumber")
private final int sequenceNumber;
@JsonCreator
/**
* Get the participants property: List of current participants in the call.
*
* @return the participants value.
*/
public List<CallParticipant> getParticipants() {
return this.participants;
}
} |
`contentClient` | public void run() {
blobClient.downloadStream(digest[0], Channels.newChannel(output));
} | blobClient.downloadStream(digest[0], Channels.newChannel(output)); | public void run() {
blobClient.downloadStream(digest[0], Channels.newChannel(output));
} | class DownloadBlobTests extends ServiceTest<PerfStressOptions> {
private final String[] digest = new String[1];
private final NullOutputStream output = new NullOutputStream();
public DownloadBlobTests(PerfStressOptions options) {
super(options);
}
@Override
public Mono<Void> globalSetupAsync() {
return importImageAsync(REPOSITORY_NAME, Arrays.asList("latest")).then();
}
@Override
public Mono<Void> setupAsync() {
return blobAsyncClient
.uploadBlob(generateAsyncStream(options.getSize()))
.doOnNext(result -> digest[0] = result.getDigest())
.then();
}
@Override
@Override
public Mono<Void> runAsync() {
return blobAsyncClient.downloadStream(digest[0])
.flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), output))
.then();
}
} | class DownloadBlobTests extends ServiceTest<PerfStressOptions> {
private final String[] digest = new String[1];
private final NullOutputStream output = new NullOutputStream();
public DownloadBlobTests(PerfStressOptions options) {
super(options);
}
@Override
public Mono<Void> globalSetupAsync() {
return importImageAsync(REPOSITORY_NAME, Arrays.asList("latest")).then();
}
@Override
public Mono<Void> setupAsync() {
return blobAsyncClient
.uploadBlob(generateAsyncStream(options.getSize()))
.doOnNext(result -> digest[0] = result.getDigest())
.then();
}
@Override
@Override
public Mono<Void> runAsync() {
return blobAsyncClient.downloadStream(digest[0])
.flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), output))
.then();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.