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
Shoundn't this already happen inside BlobInputStream ? If not would it be possible to push it down there instead of creating new type ?
public int read() throws IOException { try { return this.blobInputStream.read(); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } }
throw LoggingUtility.logError(logger, e);
public int read() throws IOException { try { return this.blobInputStream.read(); /* BlobInputStream only throws RuntimeException, and it doesn't preserve the cause, it only takes the message, so we can't do any better than re-wrapping it in an IOException. */ } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws RuntimeException when no available bytes to read. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws RuntimeException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException{ try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw logger.logExceptionAsError(new IndexOutOfBoundsException()); } try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws IOException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException { try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
BlobInputStream throws RuntimeExceptions, and the contract specifies that these methods are supposed to throw an IOException. I suspect that BlobInputStream was changed to throw RuntimeExceptions to work better with Reactor, but in an environment that isn't touched by async stuff, I think it's best to conform to the actual api conctract. I can look into skipping the double logging if you don't like that. It'll probably require a checkstyle suppression since CI doesn't usually let you use a raw throw statement without somehow passing it through a logger.
public int read() throws IOException { try { return this.blobInputStream.read(); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } }
throw LoggingUtility.logError(logger, e);
public int read() throws IOException { try { return this.blobInputStream.read(); /* BlobInputStream only throws RuntimeException, and it doesn't preserve the cause, it only takes the message, so we can't do any better than re-wrapping it in an IOException. */ } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws RuntimeException when no available bytes to read. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws RuntimeException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException{ try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw logger.logExceptionAsError(new IndexOutOfBoundsException()); } try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws IOException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException { try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
I'm not sure if BlobInputStream throwin RuntimeException is/was intentional. As you said the InputStream contract forces caller to handle IOException, so reactive code we have that's calling it should be handling/convering IOExceptions (otherwise compiler wouldn't be happy) - if that's the case I think we could safely make underlying stream confirming to the contract instead (e.g. throw IOException on certain response codes). If we keep error translation here then I think we have more to cover . I.e. underlying stream can throw `new RuntimeException(UNEXPECTED_STREAM_READ_ERROR)` . Then, if the list of messages indicating IOException grows then we'll have a challage of maintaining parity between this class and underlying infra (which would be another argument to push this responsibility to underlying stream).
public int read() throws IOException { try { return this.blobInputStream.read(); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } }
throw LoggingUtility.logError(logger, e);
public int read() throws IOException { try { return this.blobInputStream.read(); /* BlobInputStream only throws RuntimeException, and it doesn't preserve the cause, it only takes the message, so we can't do any better than re-wrapping it in an IOException. */ } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws RuntimeException when no available bytes to read. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws RuntimeException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException{ try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw logger.logExceptionAsError(new IndexOutOfBoundsException()); } try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws IOException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException { try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
I think changing the kinds of exceptions we throw is a breaking change, even if the customer theoretically should be handling it already, no?
public int read() throws IOException { try { return this.blobInputStream.read(); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } }
throw LoggingUtility.logError(logger, e);
public int read() throws IOException { try { return this.blobInputStream.read(); /* BlobInputStream only throws RuntimeException, and it doesn't preserve the cause, it only takes the message, so we can't do any better than re-wrapping it in an IOException. */ } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws RuntimeException when no available bytes to read. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws RuntimeException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException{ try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw logger.logExceptionAsError(new IndexOutOfBoundsException()); } try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws IOException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException { try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
Since we're talking about `RuntimeException` vs `IOException` I think it all boils down to how did we document `@throws` in existing streams. For example [here](https://github.com/Azure/azure-sdk-for-java/blob/895bf6f96ca5926e6071f5055e95101e2cb133dc/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/StorageInputStream.java#L228-L229) or [here](https://github.com/Azure/azure-sdk-for-java/blob/895bf6f96ca5926e6071f5055e95101e2cb133dc/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/StorageInputStream.java#L193) the described contract is quite open. Moreover I'd say that if we throw `RuntimeExceptions` there on something that's "I/O related" then that should be bug (since we don't conform to our own documentation).
public int read() throws IOException { try { return this.blobInputStream.read(); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } }
throw LoggingUtility.logError(logger, e);
public int read() throws IOException { try { return this.blobInputStream.read(); /* BlobInputStream only throws RuntimeException, and it doesn't preserve the cause, it only takes the message, so we can't do any better than re-wrapping it in an IOException. */ } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws RuntimeException when no available bytes to read. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws RuntimeException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException{ try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
class NioBlobInputStream extends InputStream { private final ClientLogger logger = new ClientLogger(NioBlobInputStream.class); private final BlobInputStream blobInputStream; NioBlobInputStream(BlobInputStream blobInputStream) { this.blobInputStream = blobInputStream; } /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. * * @return An <code>int</code> which represents an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking, or 0 when it reaches the end of the input stream. */ @Override public synchronized int available() { return this.blobInputStream.available(); } /** * Closes this input stream and releases any system resources associated with the stream. */ @Override public synchronized void close() { this.blobInputStream.close(); } /** * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * * @param readlimit An <code>int</code> which represents the maximum limit of bytes that can be read before the mark * position becomes invalid. */ @Override public synchronized void mark(final int readlimit) { this.blobInputStream.mark(readlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return Returns {@code true} */ @Override public boolean markSupported() { return this.blobInputStream.markSupported(); } /** * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks * until input data is available, the end of the stream is detected, or an exception is thrown. * * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If an I/O error occurs. */ @Override /** * Reads some number of bytes from the input stream and stores them into the buffer array <code>b</code>. The number * of bytes actually read is returned as an integer. This method blocks until input data is available, end of file * is detected, or an exception is thrown. If the length of <code>b</code> is zero, then no bytes are read and 0 is * returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is * at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into * <code>b</code>. * * The first byte read is stored into element <code>b[0]</code>, the next one into <code>b[1]</code>, and so on. The * number of bytes read is, at most, equal to the length of <code>b</code>. Let <code>k</code> be the number of * bytes actually read; these bytes will be stored in elements <code>b[0]</code> through <code>b[k-1]</code>, * leaving elements <code>b[k]</code> through * <code>b[b.length-1]</code> unaffected. * * The <code>read(b)</code> method for class {@link InputStream} has the same effect as: * * <code>read(b, 0, b.length)</code> * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @throws IOException If the first byte cannot be read for any reason other than the end of the file, if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. */ @Override public int read(final byte[] b) throws IOException { try { return this.blobInputStream.read(b); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to * read as many as <code>len</code> bytes, but a smaller number may be read. The number of bytes actually read is * returned as an integer. This method blocks until input data is available, end of file is detected, or an * exception is thrown. * * If <code>len</code> is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at * least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; * otherwise, at least one byte is read and stored into <code>b</code>. * * The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so * on. The number of bytes read is, at most, equal to <code>len</code>. Let <code>k</code> be the number of bytes * actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+k-1]</code>, * leaving elements <code>b[off+k]</code> through * <code>b[off+len-1]</code> unaffected. * * In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> * through <code>b[b.length-1]</code> are unaffected. * * @param b A <code>byte</code> array which represents the buffer into which the data is read. * @param off An <code>int</code> which represents the start offset in the <code>byte</code> array at which the data * is written. * @param len An <code>int</code> which represents the maximum number of bytes to read. * @return An <code>int</code> which represents the total number of bytes read into the buffer, or -1 if there is no * more data because the end of the stream has been reached. * @throws IOException If the first byte cannot be read for any reason other than end of file, or if the input * stream has been closed, or if some other I/O error occurs. * @throws NullPointerException If the <code>byte</code> array <code>b</code> is null. * @throws IndexOutOfBoundsException If <code>off</code> is negative, <code>len</code> is negative, or * <code>len</code> is greater than * <code>b.length - off</code>. */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw logger.logExceptionAsError(new IndexOutOfBoundsException()); } try { return this.blobInputStream.read(b, off, len); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } } /** * Repositions this stream to the position at the time the mark method was last called on this input stream. Note * repositioning the blob read stream will disable blob MD5 checking. * * @throws IOException If this stream has not been marked or if the mark has been invalidated. */ @Override public synchronized void reset() throws IOException { try { this.blobInputStream.reset(); } catch (RuntimeException e) { if (e.getMessage().equals("Stream mark expired.")) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } } /** * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of * bytes skipped is returned. If n is negative, no bytes are skipped. * * Note repositioning the blob read stream will disable blob MD5 checking. * * @param n A <code>long</code> which represents the number of bytes to skip. */ @Override public synchronized long skip(final long n) { return this.blobInputStream.skip(n); } }
These two methods can simplify to be one generic method. ``` private String getSasUri(String sasUrl) {} ```
private String getTestingSasUri() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); }
: Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL);
private String getTestingSasUri() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); }
class FormTrainingClientTestBase extends TestBase { static final String FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL"; static final String FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"; static final String AZURE_FORM_RECOGNIZER_API_KEY = "AZURE_FORM_RECOGNIZER_API_KEY"; static final String NAME = "name"; static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; static final String VERSION = "version"; static final String AZURE_FORM_RECOGNIZER_ENDPOINT = "AZURE_FORM_RECOGNIZER_ENDPOINT"; private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateTrainingDocumentsData(List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> expectedTrainingDocuments, List<TrainingDocumentInfo> actualTrainingDocuments) { assertEquals(expectedTrainingDocuments.size(), actualTrainingDocuments.size()); for (int i = 0; i < actualTrainingDocuments.size(); i++) { com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo expectedTrainingDocument = expectedTrainingDocuments.get(i); TrainingDocumentInfo actualTrainingDocument = actualTrainingDocuments.get(i); assertEquals(expectedTrainingDocument.getDocumentName(), actualTrainingDocument.getName()); assertEquals(expectedTrainingDocument.getPages(), actualTrainingDocument.getPageCount()); assertEquals(expectedTrainingDocument.getStatus().toString(), actualTrainingDocument.getTrainingStatus().toString()); validateErrorData(expectedTrainingDocument.getErrors(), actualTrainingDocument.getDocumentErrors()); } } private static void validateErrorData(List<ErrorInformation> expectedErrors, List<FormRecognizerError> actualErrors) { if (expectedErrors != null && actualErrors != null) { assertEquals(expectedErrors.size(), actualErrors.size()); for (int i = 0; i < actualErrors.size(); i++) { ErrorInformation expectedError = expectedErrors.get(i); FormRecognizerError actualError = actualErrors.get(i); assertEquals(expectedError.getCode(), actualError.getCode()); assertEquals(expectedError.getMessage(), actualError.getMessage()); } } } static void validateAccountProperties(AccountProperties expectedAccountProperties, AccountProperties actualAccountProperties) { assertEquals(expectedAccountProperties.getLimit(), actualAccountProperties.getLimit()); assertNotNull(actualAccountProperties.getCount()); } /** * Deserialize test data from service. * * @return the deserialized raw response test data */ static <T> T deserializeRawResponse(SerializerAdapter serializerAdapter, NetworkCallRecord record, Class<T> clazz) { try { return serializerAdapter.deserialize(record.getResponse().get("Body"), clazz, SerializerEncoding.JSON); } catch (IOException e) { throw new RuntimeException("Failed to deserialize service response."); } } void validateCustomModelData(CustomFormModel actualCustomModel, boolean isLabeled) { Model modelRawResponse = getRawModelResponse(); assertEquals(modelRawResponse.getModelInfo().getStatus().toString(), actualCustomModel.getModelStatus().toString()); validateErrorData(modelRawResponse.getTrainResult().getErrors(), actualCustomModel.getModelError()); assertNotNull(actualCustomModel.getCreatedOn()); assertNotNull(actualCustomModel.getLastUpdatedOn()); validateTrainingDocumentsData(modelRawResponse.getTrainResult().getTrainingDocuments(), actualCustomModel.getTrainingDocuments()); final List<CustomFormSubModel> subModelList = actualCustomModel.getSubModels().stream().collect(Collectors.toList()); if (isLabeled) { final List<FormFieldsReport> fields = modelRawResponse.getTrainResult().getFields(); for (final FormFieldsReport expectedField : fields) { final CustomFormModelField actualFormField = subModelList.get(0).getFieldMap().get(expectedField.getFieldName()); assertEquals(expectedField.getFieldName(), actualFormField.getName()); assertEquals(expectedField.getAccuracy(), actualFormField.getAccuracy()); } assertTrue(subModelList.get(0).getFormType().startsWith("form-")); assertEquals(modelRawResponse.getTrainResult().getAverageModelAccuracy(), subModelList.get(0).getAccuracy()); } else { modelRawResponse.getKeys().getClusters().forEach((clusterId, fields) -> { assertTrue(subModelList.get(Integer.parseInt(clusterId)).getFormType().endsWith(clusterId)); subModelList.get(Integer.parseInt(clusterId)).getFieldMap().values().forEach(customFormModelField -> assertTrue(fields.contains(customFormModelField.getLabel()))); }); } } /** * Prepare the expected test data from service raw response. * * @return the {@link Model} test data */ private Model getRawModelResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { Model rawModelResponse = deserializeRawResponse(serializerAdapter, record, Model.class); return rawModelResponse != null && rawModelResponse.getModelInfo().getStatus() == READY; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, Model.class); } @Test abstract void getCustomModelNullModelId(); @Test abstract void getCustomModelLabeled(); @Test abstract void getCustomModelUnlabeled(); @Test abstract void getCustomModelInvalidModelId(); @Test abstract void getCustomModelWithResponse(); @Test abstract void validGetAccountProperties(); @Test abstract void validGetAccountPropertiesWithResponse(); @Test abstract void deleteModelInvalidModelId(); @Test abstract void deleteModelValidModelIdWithResponse(); @Test abstract void getModelInfos(); @Test abstract void getModelInfosWithContext(); @Test abstract void beginTrainingNullInput(); @Test abstract void beginTrainingLabeledResult(); @Test abstract void beginTrainingUnlabeledResult(); void getCustomModelInvalidModelIdRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_MODEL_ID); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } <T> T clientSetup(Function<HttpPipeline, T> clientBuilder) { AzureKeyCredential credential = null; if (!interceptorManager.isPlaybackMode()) { credential = new AzureKeyCredential(getApiKey()); } HttpClient httpClient; Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddDatePolicy()); HttpPolicyProviders.addBeforeRetryPolicies(policies); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isPlaybackMode()) { httpClient = interceptorManager.getPlaybackClient(); } else { httpClient = new NettyAsyncHttpClientBuilder().wiretap(true).build(); } policies.add(interceptorManager.getRecordPolicy()); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); T client; client = clientBuilder.apply(pipeline); return Objects.requireNonNull(client); } /** * Get the string of API key value based on what running mode is on. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } private String getTrainingSasUri() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } }
class FormTrainingClientTestBase extends TestBase { static final String FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL"; static final String FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"; static final String AZURE_FORM_RECOGNIZER_API_KEY = "AZURE_FORM_RECOGNIZER_API_KEY"; static final String NAME = "name"; static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; static final String VERSION = "version"; static final String AZURE_FORM_RECOGNIZER_ENDPOINT = "AZURE_FORM_RECOGNIZER_ENDPOINT"; private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateTrainingDocumentsData(List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> expectedTrainingDocuments, List<TrainingDocumentInfo> actualTrainingDocuments) { assertEquals(expectedTrainingDocuments.size(), actualTrainingDocuments.size()); for (int i = 0; i < actualTrainingDocuments.size(); i++) { com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo expectedTrainingDocument = expectedTrainingDocuments.get(i); TrainingDocumentInfo actualTrainingDocument = actualTrainingDocuments.get(i); assertEquals(expectedTrainingDocument.getDocumentName(), actualTrainingDocument.getName()); assertEquals(expectedTrainingDocument.getPages(), actualTrainingDocument.getPageCount()); assertEquals(expectedTrainingDocument.getStatus().toString(), actualTrainingDocument.getTrainingStatus().toString()); validateErrorData(expectedTrainingDocument.getErrors(), actualTrainingDocument.getDocumentErrors()); } } private static void validateErrorData(List<ErrorInformation> expectedErrors, List<FormRecognizerError> actualErrors) { if (expectedErrors != null && actualErrors != null) { assertEquals(expectedErrors.size(), actualErrors.size()); for (int i = 0; i < actualErrors.size(); i++) { ErrorInformation expectedError = expectedErrors.get(i); FormRecognizerError actualError = actualErrors.get(i); assertEquals(expectedError.getCode(), actualError.getCode()); assertEquals(expectedError.getMessage(), actualError.getMessage()); } } } static void validateAccountProperties(AccountProperties expectedAccountProperties, AccountProperties actualAccountProperties) { assertEquals(expectedAccountProperties.getLimit(), actualAccountProperties.getLimit()); assertNotNull(actualAccountProperties.getCount()); } /** * Deserialize test data from service. * * @return the deserialized raw response test data */ static <T> T deserializeRawResponse(SerializerAdapter serializerAdapter, NetworkCallRecord record, Class<T> clazz) { try { return serializerAdapter.deserialize(record.getResponse().get("Body"), clazz, SerializerEncoding.JSON); } catch (IOException e) { throw new RuntimeException("Failed to deserialize service response."); } } void validateCustomModelData(CustomFormModel actualCustomModel, boolean isLabeled) { Model modelRawResponse = getRawModelResponse(); assertEquals(modelRawResponse.getModelInfo().getStatus().toString(), actualCustomModel.getModelStatus().toString()); validateErrorData(modelRawResponse.getTrainResult().getErrors(), actualCustomModel.getModelError()); assertNotNull(actualCustomModel.getCreatedOn()); assertNotNull(actualCustomModel.getLastUpdatedOn()); validateTrainingDocumentsData(modelRawResponse.getTrainResult().getTrainingDocuments(), actualCustomModel.getTrainingDocuments()); final List<CustomFormSubModel> subModelList = actualCustomModel.getSubModels().stream().collect(Collectors.toList()); if (isLabeled) { final List<FormFieldsReport> fields = modelRawResponse.getTrainResult().getFields(); for (final FormFieldsReport expectedField : fields) { final CustomFormModelField actualFormField = subModelList.get(0).getFieldMap().get(expectedField.getFieldName()); assertEquals(expectedField.getFieldName(), actualFormField.getName()); assertEquals(expectedField.getAccuracy(), actualFormField.getAccuracy()); } assertTrue(subModelList.get(0).getFormType().startsWith("form-")); assertEquals(modelRawResponse.getTrainResult().getAverageModelAccuracy(), subModelList.get(0).getAccuracy()); } else { modelRawResponse.getKeys().getClusters().forEach((clusterId, fields) -> { assertTrue(subModelList.get(Integer.parseInt(clusterId)).getFormType().endsWith(clusterId)); subModelList.get(Integer.parseInt(clusterId)).getFieldMap().values().forEach(customFormModelField -> assertTrue(fields.contains(customFormModelField.getLabel()))); }); } } /** * Prepare the expected test data from service raw response. * * @return the {@link Model} test data */ private Model getRawModelResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { Model rawModelResponse = deserializeRawResponse(serializerAdapter, record, Model.class); return rawModelResponse != null && rawModelResponse.getModelInfo().getStatus() == READY; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, Model.class); } @Test abstract void getCustomModelNullModelId(); @Test abstract void getCustomModelLabeled(); @Test abstract void getCustomModelUnlabeled(); @Test abstract void getCustomModelInvalidModelId(); @Test abstract void getCustomModelWithResponse(); @Test abstract void validGetAccountProperties(); @Test abstract void validGetAccountPropertiesWithResponse(); @Test abstract void deleteModelInvalidModelId(); @Test abstract void deleteModelValidModelIdWithResponse(); @Test abstract void getModelInfos(); @Test abstract void getModelInfosWithContext(); @Test abstract void beginTrainingNullInput(); @Test abstract void beginTrainingLabeledResult(); @Test abstract void beginTrainingUnlabeledResult(); void getCustomModelInvalidModelIdRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_MODEL_ID); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } <T> T clientSetup(Function<HttpPipeline, T> clientBuilder) { AzureKeyCredential credential = null; if (!interceptorManager.isPlaybackMode()) { credential = new AzureKeyCredential(getApiKey()); } HttpClient httpClient; Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddDatePolicy()); HttpPolicyProviders.addBeforeRetryPolicies(policies); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isPlaybackMode()) { httpClient = interceptorManager.getPlaybackClient(); } else { httpClient = new NettyAsyncHttpClientBuilder().wiretap(true).build(); } policies.add(interceptorManager.getRecordPolicy()); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); T client; client = clientBuilder.apply(pipeline); return Objects.requireNonNull(client); } /** * Get the string of API key value based on what running mode is on. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } private String getTrainingSasUri() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } }
they are returning different configurations
private String getTestingSasUri() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); }
: Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL);
private String getTestingSasUri() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); }
class FormTrainingClientTestBase extends TestBase { static final String FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL"; static final String FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"; static final String AZURE_FORM_RECOGNIZER_API_KEY = "AZURE_FORM_RECOGNIZER_API_KEY"; static final String NAME = "name"; static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; static final String VERSION = "version"; static final String AZURE_FORM_RECOGNIZER_ENDPOINT = "AZURE_FORM_RECOGNIZER_ENDPOINT"; private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateTrainingDocumentsData(List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> expectedTrainingDocuments, List<TrainingDocumentInfo> actualTrainingDocuments) { assertEquals(expectedTrainingDocuments.size(), actualTrainingDocuments.size()); for (int i = 0; i < actualTrainingDocuments.size(); i++) { com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo expectedTrainingDocument = expectedTrainingDocuments.get(i); TrainingDocumentInfo actualTrainingDocument = actualTrainingDocuments.get(i); assertEquals(expectedTrainingDocument.getDocumentName(), actualTrainingDocument.getName()); assertEquals(expectedTrainingDocument.getPages(), actualTrainingDocument.getPageCount()); assertEquals(expectedTrainingDocument.getStatus().toString(), actualTrainingDocument.getTrainingStatus().toString()); validateErrorData(expectedTrainingDocument.getErrors(), actualTrainingDocument.getDocumentErrors()); } } private static void validateErrorData(List<ErrorInformation> expectedErrors, List<FormRecognizerError> actualErrors) { if (expectedErrors != null && actualErrors != null) { assertEquals(expectedErrors.size(), actualErrors.size()); for (int i = 0; i < actualErrors.size(); i++) { ErrorInformation expectedError = expectedErrors.get(i); FormRecognizerError actualError = actualErrors.get(i); assertEquals(expectedError.getCode(), actualError.getCode()); assertEquals(expectedError.getMessage(), actualError.getMessage()); } } } static void validateAccountProperties(AccountProperties expectedAccountProperties, AccountProperties actualAccountProperties) { assertEquals(expectedAccountProperties.getLimit(), actualAccountProperties.getLimit()); assertNotNull(actualAccountProperties.getCount()); } /** * Deserialize test data from service. * * @return the deserialized raw response test data */ static <T> T deserializeRawResponse(SerializerAdapter serializerAdapter, NetworkCallRecord record, Class<T> clazz) { try { return serializerAdapter.deserialize(record.getResponse().get("Body"), clazz, SerializerEncoding.JSON); } catch (IOException e) { throw new RuntimeException("Failed to deserialize service response."); } } void validateCustomModelData(CustomFormModel actualCustomModel, boolean isLabeled) { Model modelRawResponse = getRawModelResponse(); assertEquals(modelRawResponse.getModelInfo().getStatus().toString(), actualCustomModel.getModelStatus().toString()); validateErrorData(modelRawResponse.getTrainResult().getErrors(), actualCustomModel.getModelError()); assertNotNull(actualCustomModel.getCreatedOn()); assertNotNull(actualCustomModel.getLastUpdatedOn()); validateTrainingDocumentsData(modelRawResponse.getTrainResult().getTrainingDocuments(), actualCustomModel.getTrainingDocuments()); final List<CustomFormSubModel> subModelList = actualCustomModel.getSubModels().stream().collect(Collectors.toList()); if (isLabeled) { final List<FormFieldsReport> fields = modelRawResponse.getTrainResult().getFields(); for (final FormFieldsReport expectedField : fields) { final CustomFormModelField actualFormField = subModelList.get(0).getFieldMap().get(expectedField.getFieldName()); assertEquals(expectedField.getFieldName(), actualFormField.getName()); assertEquals(expectedField.getAccuracy(), actualFormField.getAccuracy()); } assertTrue(subModelList.get(0).getFormType().startsWith("form-")); assertEquals(modelRawResponse.getTrainResult().getAverageModelAccuracy(), subModelList.get(0).getAccuracy()); } else { modelRawResponse.getKeys().getClusters().forEach((clusterId, fields) -> { assertTrue(subModelList.get(Integer.parseInt(clusterId)).getFormType().endsWith(clusterId)); subModelList.get(Integer.parseInt(clusterId)).getFieldMap().values().forEach(customFormModelField -> assertTrue(fields.contains(customFormModelField.getLabel()))); }); } } /** * Prepare the expected test data from service raw response. * * @return the {@link Model} test data */ private Model getRawModelResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { Model rawModelResponse = deserializeRawResponse(serializerAdapter, record, Model.class); return rawModelResponse != null && rawModelResponse.getModelInfo().getStatus() == READY; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, Model.class); } @Test abstract void getCustomModelNullModelId(); @Test abstract void getCustomModelLabeled(); @Test abstract void getCustomModelUnlabeled(); @Test abstract void getCustomModelInvalidModelId(); @Test abstract void getCustomModelWithResponse(); @Test abstract void validGetAccountProperties(); @Test abstract void validGetAccountPropertiesWithResponse(); @Test abstract void deleteModelInvalidModelId(); @Test abstract void deleteModelValidModelIdWithResponse(); @Test abstract void getModelInfos(); @Test abstract void getModelInfosWithContext(); @Test abstract void beginTrainingNullInput(); @Test abstract void beginTrainingLabeledResult(); @Test abstract void beginTrainingUnlabeledResult(); void getCustomModelInvalidModelIdRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_MODEL_ID); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } <T> T clientSetup(Function<HttpPipeline, T> clientBuilder) { AzureKeyCredential credential = null; if (!interceptorManager.isPlaybackMode()) { credential = new AzureKeyCredential(getApiKey()); } HttpClient httpClient; Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddDatePolicy()); HttpPolicyProviders.addBeforeRetryPolicies(policies); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isPlaybackMode()) { httpClient = interceptorManager.getPlaybackClient(); } else { httpClient = new NettyAsyncHttpClientBuilder().wiretap(true).build(); } policies.add(interceptorManager.getRecordPolicy()); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); T client; client = clientBuilder.apply(pipeline); return Objects.requireNonNull(client); } /** * Get the string of API key value based on what running mode is on. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } private String getTrainingSasUri() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } }
class FormTrainingClientTestBase extends TestBase { static final String FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL"; static final String FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"; static final String AZURE_FORM_RECOGNIZER_API_KEY = "AZURE_FORM_RECOGNIZER_API_KEY"; static final String NAME = "name"; static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; static final String VERSION = "version"; static final String AZURE_FORM_RECOGNIZER_ENDPOINT = "AZURE_FORM_RECOGNIZER_ENDPOINT"; private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateTrainingDocumentsData(List<com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo> expectedTrainingDocuments, List<TrainingDocumentInfo> actualTrainingDocuments) { assertEquals(expectedTrainingDocuments.size(), actualTrainingDocuments.size()); for (int i = 0; i < actualTrainingDocuments.size(); i++) { com.azure.ai.formrecognizer.implementation.models.TrainingDocumentInfo expectedTrainingDocument = expectedTrainingDocuments.get(i); TrainingDocumentInfo actualTrainingDocument = actualTrainingDocuments.get(i); assertEquals(expectedTrainingDocument.getDocumentName(), actualTrainingDocument.getName()); assertEquals(expectedTrainingDocument.getPages(), actualTrainingDocument.getPageCount()); assertEquals(expectedTrainingDocument.getStatus().toString(), actualTrainingDocument.getTrainingStatus().toString()); validateErrorData(expectedTrainingDocument.getErrors(), actualTrainingDocument.getDocumentErrors()); } } private static void validateErrorData(List<ErrorInformation> expectedErrors, List<FormRecognizerError> actualErrors) { if (expectedErrors != null && actualErrors != null) { assertEquals(expectedErrors.size(), actualErrors.size()); for (int i = 0; i < actualErrors.size(); i++) { ErrorInformation expectedError = expectedErrors.get(i); FormRecognizerError actualError = actualErrors.get(i); assertEquals(expectedError.getCode(), actualError.getCode()); assertEquals(expectedError.getMessage(), actualError.getMessage()); } } } static void validateAccountProperties(AccountProperties expectedAccountProperties, AccountProperties actualAccountProperties) { assertEquals(expectedAccountProperties.getLimit(), actualAccountProperties.getLimit()); assertNotNull(actualAccountProperties.getCount()); } /** * Deserialize test data from service. * * @return the deserialized raw response test data */ static <T> T deserializeRawResponse(SerializerAdapter serializerAdapter, NetworkCallRecord record, Class<T> clazz) { try { return serializerAdapter.deserialize(record.getResponse().get("Body"), clazz, SerializerEncoding.JSON); } catch (IOException e) { throw new RuntimeException("Failed to deserialize service response."); } } void validateCustomModelData(CustomFormModel actualCustomModel, boolean isLabeled) { Model modelRawResponse = getRawModelResponse(); assertEquals(modelRawResponse.getModelInfo().getStatus().toString(), actualCustomModel.getModelStatus().toString()); validateErrorData(modelRawResponse.getTrainResult().getErrors(), actualCustomModel.getModelError()); assertNotNull(actualCustomModel.getCreatedOn()); assertNotNull(actualCustomModel.getLastUpdatedOn()); validateTrainingDocumentsData(modelRawResponse.getTrainResult().getTrainingDocuments(), actualCustomModel.getTrainingDocuments()); final List<CustomFormSubModel> subModelList = actualCustomModel.getSubModels().stream().collect(Collectors.toList()); if (isLabeled) { final List<FormFieldsReport> fields = modelRawResponse.getTrainResult().getFields(); for (final FormFieldsReport expectedField : fields) { final CustomFormModelField actualFormField = subModelList.get(0).getFieldMap().get(expectedField.getFieldName()); assertEquals(expectedField.getFieldName(), actualFormField.getName()); assertEquals(expectedField.getAccuracy(), actualFormField.getAccuracy()); } assertTrue(subModelList.get(0).getFormType().startsWith("form-")); assertEquals(modelRawResponse.getTrainResult().getAverageModelAccuracy(), subModelList.get(0).getAccuracy()); } else { modelRawResponse.getKeys().getClusters().forEach((clusterId, fields) -> { assertTrue(subModelList.get(Integer.parseInt(clusterId)).getFormType().endsWith(clusterId)); subModelList.get(Integer.parseInt(clusterId)).getFieldMap().values().forEach(customFormModelField -> assertTrue(fields.contains(customFormModelField.getLabel()))); }); } } /** * Prepare the expected test data from service raw response. * * @return the {@link Model} test data */ private Model getRawModelResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { Model rawModelResponse = deserializeRawResponse(serializerAdapter, record, Model.class); return rawModelResponse != null && rawModelResponse.getModelInfo().getStatus() == READY; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, Model.class); } @Test abstract void getCustomModelNullModelId(); @Test abstract void getCustomModelLabeled(); @Test abstract void getCustomModelUnlabeled(); @Test abstract void getCustomModelInvalidModelId(); @Test abstract void getCustomModelWithResponse(); @Test abstract void validGetAccountProperties(); @Test abstract void validGetAccountPropertiesWithResponse(); @Test abstract void deleteModelInvalidModelId(); @Test abstract void deleteModelValidModelIdWithResponse(); @Test abstract void getModelInfos(); @Test abstract void getModelInfosWithContext(); @Test abstract void beginTrainingNullInput(); @Test abstract void beginTrainingLabeledResult(); @Test abstract void beginTrainingUnlabeledResult(); void getCustomModelInvalidModelIdRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_MODEL_ID); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } <T> T clientSetup(Function<HttpPipeline, T> clientBuilder) { AzureKeyCredential credential = null; if (!interceptorManager.isPlaybackMode()) { credential = new AzureKeyCredential(getApiKey()); } HttpClient httpClient; Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddDatePolicy()); HttpPolicyProviders.addBeforeRetryPolicies(policies); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isPlaybackMode()) { httpClient = interceptorManager.getPlaybackClient(); } else { httpClient = new NettyAsyncHttpClientBuilder().wiretap(true).build(); } policies.add(interceptorManager.getRecordPolicy()); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); T client; client = clientBuilder.apply(pipeline); return Objects.requireNonNull(client); } /** * Get the string of API key value based on what running mode is on. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } private String getTrainingSasUri() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } }
I would use parametrized SqlQuerySpec instead of concating strings
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + response.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
.getResourceId()
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
Changed to use querySpec
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + response.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
.getResourceId()
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
it might worth to include the name of database and container in the sdk generated error message.
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
"resource"));
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
it is worth including the name of the database and container in the sdk generated error message.
public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return this.database.getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
"No offers found for the resource"));
public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource " + this.getId())); } return this.database.getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
it is worth including the name of the database in the sdk generated error message.
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
"resource"));
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ /** * Gets the throughput of the database * * @return the mono containing throughput response */ public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ /** * Gets the throughput of the database * * @return the mono containing throughput response */ public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
ditto
public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
"resource"));
public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } /** * Gets the throughput of the database * * @return the mono containing throughput response */ SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } /** * Gets the throughput of the database * * @return the mono containing throughput response */ SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
@j82w lets please track it part of diagnostics improvement.
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
"resource"));
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ /** * Gets the throughput of the database * * @return the mono containing throughput response */ public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ /** * Gets the throughput of the database * * @return the mono containing throughput response */ public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
Is the indentation right? It looks very nested and deep. @moderakh ?
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
.flatMap(response -> this.database.getDocClientWrapper()
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
In practice its only possible if name is invalid right? How about reflecting the same in the exception message.
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
"No offers found for the " +
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
Added resource name
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
"resource"));
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
Added resource name
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
"resource"));
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ /** * Gets the throughput of the database * * @return the mono containing throughput response */ public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ /** * Gets the throughput of the database * * @return the mono containing throughput response */ public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
Added resource name
public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
"resource"));
public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } /** * Gets the throughput of the database * * @return the mono containing throughput response */ SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
class CosmosAsyncDatabase { private final CosmosAsyncClient client; private final String id; private final String link; CosmosAsyncDatabase(String id, CosmosAsyncClient client) { this.id = id; this.client = client; this.link = getParentLink() + "/" + getURIPathSegment() + "/" + getId(); } /** * Get the id of the CosmosAsyncDatabase * * @return the id of the CosmosAsyncDatabase */ public String getId() { return id; } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a single cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database respone with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos cosmos database respone with the * read database. In case of failure the {@link Mono} will error. * * @param options the request options. * @return an {@link Mono} containing the single cosmos database response with * the read database or an error. */ public Mono<CosmosAsyncDatabaseResponse> read(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().readDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete() { return delete(new CosmosDatabaseRequestOptions()); } /** * Deletes a database. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos database response with the * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono<CosmosAsyncDatabaseResponse> delete(CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } return getDocClientWrapper().deleteDatabase(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncDatabaseResponse(response, getClient())).single(); } /* CosmosAsyncContainer operations */ /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer(CosmosContainerProperties containerProperties) { return createContainer(containerProperties, new CosmosContainerRequestOptions()); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the container properties. * @param throughput the throughput for the container * @return a {@link Mono} containing the single cosmos container response with * the created container or an error. * @throws IllegalArgumentException thown if containerProerties are null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a container. * * @param containerProperties the container properties * @param throughputProperties the throughput properties * @param options the request options * @return the mono */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, ThroughputProperties throughputProperties, CosmosContainerRequestOptions options){ ModelBridgeInternal.setOfferProperties(options, throughputProperties); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties can not be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options) { if (containerProperties == null) { throw new IllegalArgumentException("containerProperties"); } ModelBridgeInternal.validateResource(containerProperties); if (options == null) { options = new CosmosContainerRequestOptions(); } return getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosAsyncContainerResponse(response, this)).single(); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param containerProperties the containerProperties. * @param throughput the throughput for the container * @param options the cosmos container request options * @return a {@link Mono} containing the cosmos container response with the * created container or an error. * @throws IllegalArgumentException containerProperties cannot be null */ public Mono<CosmosAsyncContainerResponse> createContainer( CosmosContainerProperties containerProperties, int throughput, CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(containerProperties, options); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** * Creates a document container. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainer(String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties) { CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created or existing container. In case of failure the {@link Mono} will * error. * * @param containerProperties the container properties * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( CosmosContainerProperties containerProperties, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(containerProperties.getId()); return createContainerIfNotExistsInternal(containerProperties, container, options); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists(String id, String partitionKeyPath) { CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); } /** * Creates a document container if it does not exist on the service. * <p> * After subscription the operation will be performed. The {@link Mono} upon * successful completion will contain a cosmos container response with the * created container. In case of failure the {@link Mono} will error. * * @param id the cosmos container id * @param partitionKeyPath the partition key path * @param throughput the throughput for the container * @return a {@link Mono} containing the cosmos container response with the * created container or an error. */ public Mono<CosmosAsyncContainerResponse> createContainerIfNotExists( String id, String partitionKeyPath, int throughput) { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); ModelBridgeInternal.setOfferThroughput(options, throughput); CosmosAsyncContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono<CosmosAsyncContainerResponse> createContainerIfNotExistsInternal( CosmosContainerProperties containerProperties, CosmosAsyncContainer container, CosmosContainerRequestOptions options) { return container.read(options).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosClientException) { final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedException; if (cosmosClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerProperties, options); } } return Mono.error(unwrappedException); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options {@link FeedOptions} * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Reads all cosmos containers. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of read * containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> readAllContainers() { return readAllContainers(new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query the query * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query) { return queryContainers(new SqlQuerySpec(query)); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec) { return queryContainers(querySpec, new FeedOptions()); } /** * Query for cosmos containers in a cosmos database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained containers. 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 the * obtained containers or an error. */ public CosmosPagedFlux<CosmosContainerProperties> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosContainerPropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } /** * Gets a CosmosAsyncContainer object without making a service call * * @param id id of the container * @return Cosmos Container */ public CosmosAsyncContainer getContainer(String id) { return new CosmosAsyncContainer(id, this); } /** User operations **/ /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ public Mono<CosmosAsyncUserResponse> createUser(CosmosUserProperties userProperties) { return getDocClientWrapper().createUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be * performed. The {@link Mono} upon successful completion will contain a single * resource response with the created user. In case of failure the {@link Mono} * will error. * * @param userProperties the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono<CosmosAsyncUserResponse> upsertUser(CosmosUserProperties userProperties) { return getDocClientWrapper().upsertUser(this.getLink(), ModelBridgeInternal.getV2User(userProperties), null) .map(response -> ModelBridgeInternal.createCosmosAsyncUserResponse(response, this)).single(); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers() { return readAllUsers(new FeedOptions()); } /** * Reads all cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the read cosmos users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param options the feed options. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * read cosmos users or an error. */ public CosmosPagedFlux<CosmosUserProperties> readAllUsers(FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readUsers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response .getResponseHeaders())); }); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query) { return queryUsers(query, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param query query as string * @param options the feed options * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. In case of * failure the {@link CosmosPagedFlux} will error. * * @param querySpec the SQL query specification. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec) { return queryUsers(querySpec, new FeedOptions()); } /** * Query for cosmos users in a database. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will * contain one or several feed response of the obtained users. 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 the * obtained users or an error. */ public CosmosPagedFlux<CosmosUserProperties> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().queryUsers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( ModelBridgeInternal.getCosmosUserPropertiesFromV2Results(response.getResults()), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response))); }); } /** * Gets user. * * @param id the id * @return the user */ public CosmosAsyncUser getUser(String id) { return new CosmosAsyncUser(id, this); } /** * Gets the throughput of the database * * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> readProvisionedThroughput() { return this.read() .flatMap(cosmosDatabaseResponse -> getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse .getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }).map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param requestUnitsPerSecond the cosmos container throughput, expressed in * Request Units per second * @return a {@link Mono} containing throughput or an error. */ public Mono<Integer> replaceProvisionedThroughput(int requestUnitsPerSecond) { return this.read() .flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.getProperties() .getResourceId() + "'", new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.getResults().get(0); offer.setThroughput(requestUnitsPerSecond); return this.getDocClientWrapper().replaceOffer(offer) .single(); }).map(offerResourceResponse -> offerResourceResponse .getResource() .getThroughput())); } /** * Sets throughput provisioned for a container in measurement of * Requests-per-Unit in the Azure Cosmos service. * * @param throughputProperties the throughput properties * @return the mono */ public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); } /** * Gets the throughput of the database * * @return the mono containing throughput response */ SqlQuerySpec getOfferQuerySpecFromResourceId(String resourceId) { String queryText = "select * from c where c.offerResourceId = @resourceId"; SqlQuerySpec querySpec = new SqlQuerySpec(queryText); List<SqlParameter> parameters = Collections .singletonList(new SqlParameter("@resourceId", resourceId)); querySpec.setParameters(parameters); return querySpec; } CosmosAsyncClient getClient() { return client; } AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } String getURIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } String getParentLink() { return StringUtils.EMPTY; } String getLink() { return this.link; } }
Added resource id in the error message which should help.
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
"No offers found for the " +
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
It looks a bit weird, but this is correct. Also this is the best intellij could do :)
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
.flatMap(response -> this.database.getDocClientWrapper()
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
The indentation is correct. The nesting is the result of reactive-stream chaining and lambdas
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource")); } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
.flatMap(response -> this.database.getDocClientWrapper()
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.database.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }).map(ModelBridgeInternal::createThroughputRespose)); }
class type * @return a {@link CosmosPagedFlux}
class type * @return a {@link CosmosPagedFlux}
It might be better to add "avro/binary" as a constant in [ContentType.java](https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/http/ContentType.java)
private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) { final String incomingUrl = applyReplacementRule(request.getUrl().toString()); final String incomingMethod = request.getHttpMethod().toString(); final String matchingUrl = removeHost(incomingUrl); NetworkCallRecord networkCallRecord = recordedData.findFirstAndRemoveNetworkCall(record -> record.getMethod().equalsIgnoreCase(incomingMethod) && removeHost(record.getUri()).equalsIgnoreCase(matchingUrl)); count.incrementAndGet(); if (networkCallRecord == null) { logger.warning("NOT FOUND - Method: {} URL: {}", incomingMethod, incomingUrl); logger.warning("Records requested: {}.", count); return Mono.error(new IllegalStateException("==> Unexpected request: " + incomingMethod + " " + incomingUrl)); } if (networkCallRecord.getException() != null) { throw logger.logExceptionAsWarning(Exceptions.propagate(networkCallRecord.getException().get())); } if (networkCallRecord.getHeaders().containsKey(X_MS_CLIENT_REQUEST_ID)) { request.setHeader(X_MS_CLIENT_REQUEST_ID, networkCallRecord.getHeaders().get(X_MS_CLIENT_REQUEST_ID)); } if (request.getHeaders().getValue(X_MS_ENCRYPTION_KEY_SHA256) != null) { networkCallRecord.getResponse().put(X_MS_ENCRYPTION_KEY_SHA256, request.getHeaders().getValue(X_MS_ENCRYPTION_KEY_SHA256)); } int recordStatusCode = Integer.parseInt(networkCallRecord.getResponse().get("StatusCode")); HttpHeaders headers = new HttpHeaders(); for (Map.Entry<String, String> pair : networkCallRecord.getResponse().entrySet()) { if (!pair.getKey().equals("StatusCode") && !pair.getKey().equals("Body")) { String rawHeader = pair.getValue(); for (Map.Entry<String, String> rule : textReplacementRules.entrySet()) { if (rule.getValue() != null) { rawHeader = rawHeader.replaceAll(rule.getKey(), rule.getValue()); } } headers.put(pair.getKey(), rawHeader); } } String rawBody = networkCallRecord.getResponse().get("Body"); byte[] bytes = null; if (rawBody != null) { for (Map.Entry<String, String> rule : textReplacementRules.entrySet()) { if (rule.getValue() != null) { rawBody = rawBody.replaceAll(rule.getKey(), rule.getValue()); } } String contentType = networkCallRecord.getResponse().get("Content-Type"); /* * application/octet-stream and avro/binary are written to disk using Arrays.toString() which creates an * output such as "[12, -1]". */ if (contentType != null && (contentType.equalsIgnoreCase(ContentType.APPLICATION_OCTET_STREAM) || contentType.equalsIgnoreCase("avro/binary"))) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (String piece : rawBody.substring(1, rawBody.length() - 1).split(", ")) { outputStream.write(Byte.parseByte(piece)); } bytes = outputStream.toByteArray(); } else { bytes = rawBody.getBytes(StandardCharsets.UTF_8); } if (bytes.length > 0) { headers.put("Content-Length", String.valueOf(bytes.length)); } } HttpResponse response = new MockHttpResponse(request, recordStatusCode, headers, bytes); return Mono.just(response); }
|| contentType.equalsIgnoreCase("avro/binary"))) {
private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) { final String incomingUrl = applyReplacementRule(request.getUrl().toString()); final String incomingMethod = request.getHttpMethod().toString(); final String matchingUrl = removeHost(incomingUrl); NetworkCallRecord networkCallRecord = recordedData.findFirstAndRemoveNetworkCall(record -> record.getMethod().equalsIgnoreCase(incomingMethod) && removeHost(record.getUri()).equalsIgnoreCase(matchingUrl)); count.incrementAndGet(); if (networkCallRecord == null) { logger.warning("NOT FOUND - Method: {} URL: {}", incomingMethod, incomingUrl); logger.warning("Records requested: {}.", count); return Mono.error(new IllegalStateException("==> Unexpected request: " + incomingMethod + " " + incomingUrl)); } if (networkCallRecord.getException() != null) { throw logger.logExceptionAsWarning(Exceptions.propagate(networkCallRecord.getException().get())); } if (networkCallRecord.getHeaders().containsKey(X_MS_CLIENT_REQUEST_ID)) { request.setHeader(X_MS_CLIENT_REQUEST_ID, networkCallRecord.getHeaders().get(X_MS_CLIENT_REQUEST_ID)); } if (request.getHeaders().getValue(X_MS_ENCRYPTION_KEY_SHA256) != null) { networkCallRecord.getResponse().put(X_MS_ENCRYPTION_KEY_SHA256, request.getHeaders().getValue(X_MS_ENCRYPTION_KEY_SHA256)); } int recordStatusCode = Integer.parseInt(networkCallRecord.getResponse().get("StatusCode")); HttpHeaders headers = new HttpHeaders(); for (Map.Entry<String, String> pair : networkCallRecord.getResponse().entrySet()) { if (!pair.getKey().equals("StatusCode") && !pair.getKey().equals("Body")) { String rawHeader = pair.getValue(); for (Map.Entry<String, String> rule : textReplacementRules.entrySet()) { if (rule.getValue() != null) { rawHeader = rawHeader.replaceAll(rule.getKey(), rule.getValue()); } } headers.put(pair.getKey(), rawHeader); } } String rawBody = networkCallRecord.getResponse().get("Body"); byte[] bytes = null; if (rawBody != null) { for (Map.Entry<String, String> rule : textReplacementRules.entrySet()) { if (rule.getValue() != null) { rawBody = rawBody.replaceAll(rule.getKey(), rule.getValue()); } } String contentType = networkCallRecord.getResponse().get("Content-Type"); /* * application/octet-stream and avro/binary are written to disk using Arrays.toString() which creates an * output such as "[12, -1]". */ if (contentType != null && (contentType.equalsIgnoreCase(ContentType.APPLICATION_OCTET_STREAM) || contentType.equalsIgnoreCase("avro/binary"))) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (String piece : rawBody.substring(1, rawBody.length() - 1).split(", ")) { outputStream.write(Byte.parseByte(piece)); } bytes = outputStream.toByteArray(); } else { bytes = rawBody.getBytes(StandardCharsets.UTF_8); } if (bytes.length > 0) { headers.put("Content-Length", String.valueOf(bytes.length)); } } HttpResponse response = new MockHttpResponse(request, recordStatusCode, headers, bytes); return Mono.just(response); }
class PlaybackClient implements HttpClient { private static final String X_MS_CLIENT_REQUEST_ID = "x-ms-client-request-id"; private static final String X_MS_ENCRYPTION_KEY_SHA256 = "x-ms-encryption-key-sha256"; private final ClientLogger logger = new ClientLogger(PlaybackClient.class); private final AtomicInteger count = new AtomicInteger(0); private final Map<String, String> textReplacementRules; private final RecordedData recordedData; /** * Creates a PlaybackClient that replays network calls from {@code recordedData} and replaces {@link * NetworkCallRecord * * @param recordedData The data to playback. * @param textReplacementRules A set of rules to replace text in network call responses. */ public PlaybackClient(RecordedData recordedData, Map<String, String> textReplacementRules) { Objects.requireNonNull(recordedData, "'recordedData' cannot be null."); this.recordedData = recordedData; this.textReplacementRules = textReplacementRules == null ? new HashMap<>() : textReplacementRules; } /** * {@inheritDoc} */ @Override public Mono<HttpResponse> send(final HttpRequest request) { return Mono.defer(() -> playbackHttpResponse(request)); } private String applyReplacementRule(String text) { for (Map.Entry<String, String> rule : textReplacementRules.entrySet()) { if (rule.getValue() != null) { text = text.replaceAll(rule.getKey(), rule.getValue()); } } return text; } private static String removeHost(String url) { UrlBuilder urlBuilder = UrlBuilder.parse(url); if (urlBuilder.getQuery().containsKey("sig")) { urlBuilder.setQueryParameter("sig", "REDACTED"); } return String.format("%s%s", urlBuilder.getPath(), urlBuilder.getQueryString()); } }
class PlaybackClient implements HttpClient { private static final String X_MS_CLIENT_REQUEST_ID = "x-ms-client-request-id"; private static final String X_MS_ENCRYPTION_KEY_SHA256 = "x-ms-encryption-key-sha256"; private final ClientLogger logger = new ClientLogger(PlaybackClient.class); private final AtomicInteger count = new AtomicInteger(0); private final Map<String, String> textReplacementRules; private final RecordedData recordedData; /** * Creates a PlaybackClient that replays network calls from {@code recordedData} and replaces {@link * NetworkCallRecord * * @param recordedData The data to playback. * @param textReplacementRules A set of rules to replace text in network call responses. */ public PlaybackClient(RecordedData recordedData, Map<String, String> textReplacementRules) { Objects.requireNonNull(recordedData, "'recordedData' cannot be null."); this.recordedData = recordedData; this.textReplacementRules = textReplacementRules == null ? new HashMap<>() : textReplacementRules; } /** * {@inheritDoc} */ @Override public Mono<HttpResponse> send(final HttpRequest request) { return Mono.defer(() -> playbackHttpResponse(request)); } private String applyReplacementRule(String text) { for (Map.Entry<String, String> rule : textReplacementRules.entrySet()) { if (rule.getValue() != null) { text = text.replaceAll(rule.getKey(), rule.getValue()); } } return text; } private static String removeHost(String url) { UrlBuilder urlBuilder = UrlBuilder.parse(url); if (urlBuilder.getQuery().containsKey("sig")) { urlBuilder.setQueryParameter("sig", "REDACTED"); } return String.format("%s%s", urlBuilder.getPath(), urlBuilder.getQueryString()); } }
Will it throw if you call dispose twice?
public void close() { asyncClient.close(); if (messageProcessor.get() != null) { messageProcessor.get().dispose(); } Disposable activeSubscription = messageProcessorSubscription.get(); if (activeSubscription != null) { activeSubscription.dispose(); } }
if (messageProcessor.get() != null) {
public void close() { asyncClient.close(); EmitterProcessor<ServiceBusReceivedMessageContext> processor = messageProcessor.getAndSet(null); if (processor != null) { processor.onComplete(); } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); private final AtomicReference<Disposable> messageProcessorSubscription = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, String sessionId) { asyncClient.abandon(lockToken, sessionId).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link EmitterProcessor} to receive messages from Service Bus. If the * message processor has not been created, will initialise it. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { if (messageProcessor.get() != null && messageProcessor.get().isDisposed()) { logger.error("[{}]: Can not receive messaged because client is closed.", asyncClient.getEntityPath()); return; } if (messageProcessor.get() == null) { EmitterProcessor<ServiceBusReceivedMessageContext> processor = asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(false)); if (!messageProcessor.compareAndSet(null, processor)) { processor.dispose(); } logger.info("[{}]: Started ContinuesMessageSubscriber message subscriber for entity.", asyncClient.getEntityPath()); } Disposable newSubscription = messageProcessor.get() .take(maximumMessageCount) .timeout(maxWaitTime) .doOnNext(messageContext -> { emitter.next(messageContext); }) .doOnError(throwable -> { emitter.error(throwable); }) .doOnComplete(emitter::complete) .subscribe(); Disposable oldSubscription = messageProcessorSubscription.getAndSet(newSubscription); if (oldSubscription != null) { oldSubscription.dispose(); } } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private final Object lock = new Object(); private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus * entity. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } } }
Search is validating `apiKeyCredential.getKey` empty or null case.
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
commented code should be removed.
public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); }
public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); private final AtomicReference<Disposable> messageProcessorSubscription = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, String sessionId) { asyncClient.abandon(lockToken, sessionId).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override public void close() { asyncClient.close(); if (messageProcessor.get() != null && !messageProcessor.get().isDisposed()) { messageProcessor.get().dispose(); } Disposable activeSubscription = messageProcessorSubscription.get(); if (activeSubscription != null && !activeSubscription.isDisposed()) { activeSubscription.dispose(); } } /** * Given an {@code emitter}, creates a {@link EmitterProcessor} to receive messages from Service Bus. If the * message processor has not been created, will initialise it. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { if (messageProcessor.get() != null && messageProcessor.get().isDisposed()) { logger.error("[{}]: Can not receive messaged because client is closed.", asyncClient.getEntityPath()); return; } if (messageProcessor.get() == null) { logger.info("[{}]: Creating EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); EmitterProcessor<ServiceBusReceivedMessageContext> newProcessor = asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(false)); if (!messageProcessor.compareAndSet(null, newProcessor)) { newProcessor.dispose(); } logger.info("[{}]: Started EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); } logger.info("[{}]: Subscribing EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); Disposable newSubscription = messageProcessor.get() .take(maximumMessageCount) .timeout(maxWaitTime) .map(messageContext -> { emitter.next(messageContext); return messageContext; }) .doOnError(throwable -> { emitter.error(throwable); }) .doOnComplete(emitter::complete) .subscribe(); Disposable oldSubscription = messageProcessorSubscription.getAndSet(newSubscription); if (oldSubscription != null) { oldSubscription.dispose(); } } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private final Object lock = new Object(); private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override public void close() { asyncClient.close(); EmitterProcessor<ServiceBusReceivedMessageContext> processor = messageProcessor.getAndSet(null); if (processor != null) { processor.onComplete(); } } /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus * entity. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } } }
Between `isDisposed()` check and `dispose()` the processor might have changed state. This is not an atomic operation, if that's what you were trying to achieve using the AtomicReference.
public void close() { asyncClient.close(); if (messageProcessor.get() != null && !messageProcessor.get().isDisposed()) { messageProcessor.get().dispose(); } Disposable activeSubscription = messageProcessorSubscription.get(); if (activeSubscription != null && !activeSubscription.isDisposed()) { activeSubscription.dispose(); } }
}
public void close() { asyncClient.close(); EmitterProcessor<ServiceBusReceivedMessageContext> processor = messageProcessor.getAndSet(null); if (processor != null) { processor.onComplete(); } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); private final AtomicReference<Disposable> messageProcessorSubscription = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, String sessionId) { asyncClient.abandon(lockToken, sessionId).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link EmitterProcessor} to receive messages from Service Bus. If the * message processor has not been created, will initialise it. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { if (messageProcessor.get() != null && messageProcessor.get().isDisposed()) { logger.error("[{}]: Can not receive messaged because client is closed.", asyncClient.getEntityPath()); return; } if (messageProcessor.get() == null) { logger.info("[{}]: Creating EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); EmitterProcessor<ServiceBusReceivedMessageContext> newProcessor = asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(false)); if (!messageProcessor.compareAndSet(null, newProcessor)) { newProcessor.dispose(); } logger.info("[{}]: Started EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); } logger.info("[{}]: Subscribing EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); Disposable newSubscription = messageProcessor.get() .take(maximumMessageCount) .timeout(maxWaitTime) .map(messageContext -> { emitter.next(messageContext); return messageContext; }) .doOnError(throwable -> { emitter.error(throwable); }) .doOnComplete(emitter::complete) .subscribe(); Disposable oldSubscription = messageProcessorSubscription.getAndSet(newSubscription); if (oldSubscription != null) { oldSubscription.dispose(); } } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private final Object lock = new Object(); private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus * entity. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } } }
Same here, this is not an atomic operation.
public void close() { asyncClient.close(); if (messageProcessor.get() != null && !messageProcessor.get().isDisposed()) { messageProcessor.get().dispose(); } Disposable activeSubscription = messageProcessorSubscription.get(); if (activeSubscription != null && !activeSubscription.isDisposed()) { activeSubscription.dispose(); } }
}
public void close() { asyncClient.close(); EmitterProcessor<ServiceBusReceivedMessageContext> processor = messageProcessor.getAndSet(null); if (processor != null) { processor.onComplete(); } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); private final AtomicReference<Disposable> messageProcessorSubscription = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, String sessionId) { asyncClient.abandon(lockToken, sessionId).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link EmitterProcessor} to receive messages from Service Bus. If the * message processor has not been created, will initialise it. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { if (messageProcessor.get() != null && messageProcessor.get().isDisposed()) { logger.error("[{}]: Can not receive messaged because client is closed.", asyncClient.getEntityPath()); return; } if (messageProcessor.get() == null) { logger.info("[{}]: Creating EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); EmitterProcessor<ServiceBusReceivedMessageContext> newProcessor = asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(false)); if (!messageProcessor.compareAndSet(null, newProcessor)) { newProcessor.dispose(); } logger.info("[{}]: Started EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); } logger.info("[{}]: Subscribing EmitterProcessor message processor for entity.", asyncClient.getEntityPath()); Disposable newSubscription = messageProcessor.get() .take(maximumMessageCount) .timeout(maxWaitTime) .map(messageContext -> { emitter.next(messageContext); return messageContext; }) .doOnError(throwable -> { emitter.error(throwable); }) .doOnComplete(emitter::complete) .subscribe(); Disposable oldSubscription = messageProcessorSubscription.getAndSet(newSubscription); if (oldSubscription != null) { oldSubscription.dispose(); } } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private final Object lock = new Object(); private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus * entity. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } } }
The operation should be `cancel()`, not `onComplete()`. onComplete and methods like that should be done through a sink. ```java var processor = messageProcessor.getAndSet(null); if (processor != null) { processor.cancel() } ```
public void close() { asyncClient.close(); if (messageProcessor.get() != null) { messageProcessor.get().onComplete(); } }
if (messageProcessor.get() != null) {
public void close() { asyncClient.close(); EmitterProcessor<ServiceBusReceivedMessageContext> processor = messageProcessor.getAndSet(null); if (processor != null) { processor.onComplete(); } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus. */ private synchronized void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { final long id = idGenerator.getAndIncrement(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (messageProcessor.get() == null) { messageProcessor.set(this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(false))); } messageProcessor.get().subscribe(syncSubscriber); } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private final Object lock = new Object(); private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus * entity. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } } }
Moreover, if the credential is required, we can move the validation up to buildClient()
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
discussed on teams and decided to not change it.
public void close() { asyncClient.close(); if (messageProcessor.get() != null) { messageProcessor.get().onComplete(); } }
if (messageProcessor.get() != null) {
public void close() { asyncClient.close(); EmitterProcessor<ServiceBusReceivedMessageContext> processor = messageProcessor.getAndSet(null); if (processor != null) { processor.onComplete(); } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus. */ private synchronized void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { final long id = idGenerator.getAndIncrement(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (messageProcessor.get() == null) { messageProcessor.set(this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(false))); } messageProcessor.get().subscribe(syncSubscriber); } }
class ServiceBusReceiverClient implements AutoCloseable { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClient.class); private final AtomicInteger idGenerator = new AtomicInteger(); private final ServiceBusReceiverAsyncClient asyncClient; private final Duration operationTimeout; private final Object lock = new Object(); private static final ReceiveAsyncOptions DEFAULT_RECEIVE_OPTIONS = new ReceiveAsyncOptions() .setIsAutoCompleteEnabled(false) .setMaxAutoLockRenewalDuration(Duration.ZERO); private final AtomicReference<EmitterProcessor<ServiceBusReceivedMessageContext>> messageProcessor = new AtomicReference<>(); /** * Creates a synchronous receiver given its asynchronous counterpart. * * @param asyncClient Asynchronous receiver. */ ServiceBusReceiverClient(ServiceBusReceiverAsyncClient asyncClient, Duration operationTimeout) { this.asyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return asyncClient.getFullyQualifiedNamespace(); } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return asyncClient.getEntityPath(); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available * again for processing. Abandoning a message will increase the delivery count on the message. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken) { asyncClient.abandon(lockToken).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.abandon(lockToken, propertiesToModify).block(operationTimeout); } /** * Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties. * This will make the message available again for processing. Abandoning a message will increase the delivery count * on the message. * * @param lockToken Lock token of the message. * @param propertiesToModify Properties to modify on the message. * @param sessionId Session id of the message to abandon. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void abandon(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.abandon(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken) { asyncClient.complete(lockToken).block(operationTimeout); } /** * Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the * service. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to complete. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void complete(MessageLockToken lockToken, String sessionId) { asyncClient.complete(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken) { asyncClient.defer(lockToken).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred * subqueue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, String sessionId) { asyncClient.defer(lockToken, sessionId).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify) { asyncClient.defer(lockToken, propertiesToModify).block(operationTimeout); } /** * Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will * move message into the deferred subqueue. * * @param lockToken Lock token of the message. * @param propertiesToModify Message properties to modify. * @param sessionId Session id of the message to defer. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: */ public void defer(MessageLockToken lockToken, Map<String, Object> propertiesToModify, String sessionId) { asyncClient.defer(lockToken, propertiesToModify, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken) { asyncClient.deadLetter(lockToken).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue. * * @param lockToken Lock token of the message. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @see <a href="https: * queues</a> */ public void deadLetter(MessageLockToken lockToken, String sessionId) { asyncClient.deadLetter(lockToken, sessionId).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions) { asyncClient.deadLetter(lockToken, deadLetterOptions).block(operationTimeout); } /** * Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error * description, and/or modified properties. * * @param lockToken Lock token of the message. * @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue. * @param sessionId Session id of the message to deadletter. {@code null} if there is no session. * * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken */ public void deadLetter(MessageLockToken lockToken, DeadLetterOptions deadLetterOptions, String sessionId) { asyncClient.deadLetter(lockToken, deadLetterOptions, sessionId).block(operationTimeout); } /** * Gets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * * @return The session state or null if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver. */ public byte[] getSessionState(String sessionId) { return asyncClient.getSessionState(sessionId).block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek() { return asyncClient.peek().block(operationTimeout); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peek(String sessionId) { return asyncClient.peek(sessionId).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber) { return asyncClient.peekAt(sequenceNumber).block(operationTimeout); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @see <a href="https: */ public ServiceBusReceivedMessage peekAt(long sequenceNumber, String sessionId) { return asyncClient.peekAt(sequenceNumber, sessionId).block(operationTimeout); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatch(int maxMessages, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatch(maxMessages, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @see <a href="https: */ public IterableStream<ServiceBusReceivedMessage> peekBatchAt(int maxMessages, long sequenceNumber, String sessionId) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = asyncClient.peekBatchAt(maxMessages, sequenceNumber, sessionId) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * The receive operation will wait for a default 1 minute for receiving a message before it times out. You can it * override by using {@link * * @param maxMessages The maximum number of messages to receive. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages) { return receive(maxMessages, operationTimeout); } /** * Receives an iterable stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * * @param maxMessages The maximum number of messages to receive. * @param maxWaitTime The time the client waits for receiving a message before it times out. * @return An {@link IterableStream} of at most {@code maxMessages} messages from the Service Bus entity. * * @throws IllegalArgumentException if {@code maxMessages} or {@code maxWaitTime} is zero or a negative value. */ public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber) { return asyncClient.receiveDeferredMessage(sequenceNumber).block(operationTimeout); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. * * @return A deferred message with the matching {@code sequenceNumber}. */ public ServiceBusReceivedMessage receiveDeferredMessage(long sequenceNumber, String sessionId) { return asyncClient.receiveDeferredMessage(sequenceNumber, sessionId).block(operationTimeout); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers) .timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. */ public IterableStream<ServiceBusReceivedMessage> receiveDeferredMessageBatch(Iterable<Long> sequenceNumbers, String sessionId) { final Flux<ServiceBusReceivedMessage> messages = asyncClient.receiveDeferredMessageBatch(sequenceNumbers, sessionId).timeout(operationTimeout); messages.subscribe(); return new IterableStream<>(messages); } /** * Renews the lock on the specified message. The lock will be renewed based on the setting specified on the entity. * When a message is received in {@link ReceiveMode * receiver instance for a duration as specified during the Queue creation (LockDuration). If processing of the * message requires longer than this duration, the lock needs to be renewed. For each renewal, the lock is reset to * the entity's LockDuration value. * * @param lockToken Lock token of the message to renew. * * @return The new expiration time for the message. * @throws NullPointerException if {@code lockToken} is null. * @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode * mode. * @throws IllegalArgumentException if {@link MessageLockToken * @throws IllegalStateException if the receiver is a session receiver. */ public Instant renewMessageLock(MessageLockToken lockToken) { return asyncClient.renewMessageLock(lockToken).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @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. */ public Instant renewSessionLock(String sessionId) { return asyncClient.renewSessionLock(sessionId).block(operationTimeout); } /** * Sets the state of a session given its identifier. * * @param sessionId Identifier of session to get. * @param sessionState State to set on the session. * * @throws IllegalStateException if the receiver is a non-session receiver. */ public void setSessionState(String sessionId, byte[] sessionState) { asyncClient.setSessionState(sessionId, sessionState).block(operationTimeout); } /** * {@inheritDoc} */ @Override /** * Given an {@code emitter}, creates a {@link SynchronousMessageSubscriber} to receive messages from Service Bus * entity. */ private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } } }
It does have that here - https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/formrecognizer/azure-ai-formrecognizer/src/main/java/com/azure/ai/formrecognizer/FormRecognizerClientBuilder.java#L181
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
``` public SearchServiceClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { throw logger.logExceptionAsError( new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); } this.keyCredential = keyCredential; return this; } ``` Here is how search do validation for your reference.
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
@sima-zhu Could this > if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } be replaced with > this.credential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); And also for the rest of the code, I see that we are already doing the empty checks [here](https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureKeyCredential.java#L27) and [here](https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureKeyCredential.java#L53). It would be redundant?
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null.");
public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
ChangeFeedProcessor is a read-only, how minimal response impacts it?
public static CosmosAsyncClient getCosmosClient() { return new CosmosClientBuilder() .endpoint(SampleConfigurations.HOST) .key(SampleConfigurations.MASTER_KEY) .connectionPolicy(ConnectionPolicy.getDefaultPolicy()) .consistencyLevel(ConsistencyLevel.EVENTUAL) .returnMinimalResponse(false) .buildAsyncClient(); }
.returnMinimalResponse(false)
public static CosmosAsyncClient getCosmosClient() { return new CosmosClientBuilder() .endpoint(SampleConfigurations.HOST) .key(SampleConfigurations.MASTER_KEY) .connectionPolicy(ConnectionPolicy.getDefaultPolicy()) .consistencyLevel(ConsistencyLevel.EVENTUAL) .contentResponseOnWriteEnabled(true) .buildAsyncClient(); }
class SampleChangeFeedProcessor { public static int WAIT_FOR_WORK = 60; public static final String DATABASE_NAME = "db_" + RandomStringUtils.randomAlphabetic(7); public static final String COLLECTION_NAME = "coll_" + RandomStringUtils.randomAlphabetic(7); private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); private static ChangeFeedProcessor changeFeedProcessorInstance; private static boolean isWorkCompleted = false; public static void main (String[]args) { System.out.println("BEGIN Sample"); try { System.out.println("-->CREATE DocumentClient"); CosmosAsyncClient client = getCosmosClient(); System.out.println("-->CREATE sample's database: " + DATABASE_NAME); CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); System.out.println("-->CREATE container for documents: " + COLLECTION_NAME); CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); changeFeedProcessorInstance.start().subscribe(aVoid -> { createNewDocuments(feedContainer, 10, Duration.ofSeconds(3)); isWorkCompleted = true; }); long remainingWork = WAIT_FOR_WORK; while (!isWorkCompleted && remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } if (isWorkCompleted) { if (changeFeedProcessorInstance != null) { changeFeedProcessorInstance.stop().subscribe().wait(10000); } } else { throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); } System.out.println("-->DELETE sample's database: " + DATABASE_NAME); deleteDatabase(cosmosDatabase); Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } System.out.println("END Sample"); System.exit(0); } public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosAsyncContainer feedContainer, CosmosAsyncContainer leaseContainer) { return ChangeFeedProcessor.changeFeedProcessorBuilder() .hostName(hostName) .feedContainer(feedContainer) .leaseContainer(leaseContainer) .handleChanges((List<JsonNode> docs) -> { System.out.println("--->setHandleChanges() START"); for (JsonNode document : docs) { try { System.out.println("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() .writeValueAsString(document)); } catch (JsonProcessingException e) { e.printStackTrace(); } } System.out.println("--->handleChanges() END"); }) .build(); } public static CosmosAsyncDatabase createNewDatabase(CosmosAsyncClient client, String databaseName) { return client.createDatabaseIfNotExists(databaseName).block().getDatabase(); } public static void deleteDatabase(CosmosAsyncDatabase cosmosDatabase) { cosmosDatabase.delete().block(); } public static CosmosAsyncContainer createNewCollection(CosmosAsyncClient client, String databaseName, String collectionName) { CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); CosmosAsyncContainer collectionLink = databaseLink.getContainer(collectionName); CosmosAsyncContainerResponse containerResponse = null; try { containerResponse = collectionLink.read().block(); if (containerResponse != null) { throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName)); } } catch (RuntimeException ex) { if (ex instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) ex; if (cosmosClientException.getStatusCode() != 404) { throw ex; } } else { throw ex; } } CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); containerResponse = databaseLink.createContainer(containerSettings, 10000, requestOptions).block(); if (containerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); } return containerResponse.getContainer(); } public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient client, String databaseName, String leaseCollectionName) { CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); CosmosAsyncContainer leaseCollectionLink = databaseLink.getContainer(leaseCollectionName); CosmosAsyncContainerResponse leaseContainerResponse = null; try { leaseContainerResponse = leaseCollectionLink.read().block(); if (leaseContainerResponse != null) { leaseCollectionLink.delete().block(); try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } catch (RuntimeException ex) { if (ex instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) ex; if (cosmosClientException.getStatusCode() != 404) { throw ex; } } else { throw ex; } } CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block(); if (leaseContainerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); } return leaseContainerResponse.getContainer(); } public static void createNewDocuments(CosmosAsyncContainer containerClient, int count, Duration delay) { String suffix = RandomStringUtils.randomAlphabetic(10); for (int i = 0; i <= count; i++) { CosmosItemProperties document = new CosmosItemProperties(); document.setId(String.format("0%d-%s", i, suffix)); containerClient.createItem(document).subscribe(doc -> { try { System.out.println("---->DOCUMENT WRITE: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() .writeValueAsString(doc)); } catch (JsonProcessingException e) { logger.error("Failure in processing json [{}]", e.getMessage(), e); } }); long remainingWork = delay.toMillis(); try { while (remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } } catch (InterruptedException iex) { break; } } } public static boolean ensureWorkIsDone(Duration delay) { long remainingWork = delay.toMillis(); try { while (!isWorkCompleted && remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } } catch (InterruptedException iex) { return false; } return remainingWork > 0; } }
class SampleChangeFeedProcessor { public static int WAIT_FOR_WORK = 60; public static final String DATABASE_NAME = "db_" + RandomStringUtils.randomAlphabetic(7); public static final String COLLECTION_NAME = "coll_" + RandomStringUtils.randomAlphabetic(7); private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); private static ChangeFeedProcessor changeFeedProcessorInstance; private static boolean isWorkCompleted = false; public static void main (String[]args) { System.out.println("BEGIN Sample"); try { System.out.println("-->CREATE DocumentClient"); CosmosAsyncClient client = getCosmosClient(); System.out.println("-->CREATE sample's database: " + DATABASE_NAME); CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); System.out.println("-->CREATE container for documents: " + COLLECTION_NAME); CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); changeFeedProcessorInstance.start().subscribe(aVoid -> { createNewDocuments(feedContainer, 10, Duration.ofSeconds(3)); isWorkCompleted = true; }); long remainingWork = WAIT_FOR_WORK; while (!isWorkCompleted && remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } if (isWorkCompleted) { if (changeFeedProcessorInstance != null) { changeFeedProcessorInstance.stop().subscribe().wait(10000); } } else { throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); } System.out.println("-->DELETE sample's database: " + DATABASE_NAME); deleteDatabase(cosmosDatabase); Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } System.out.println("END Sample"); System.exit(0); } public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosAsyncContainer feedContainer, CosmosAsyncContainer leaseContainer) { return ChangeFeedProcessor.changeFeedProcessorBuilder() .hostName(hostName) .feedContainer(feedContainer) .leaseContainer(leaseContainer) .handleChanges((List<JsonNode> docs) -> { System.out.println("--->setHandleChanges() START"); for (JsonNode document : docs) { try { System.out.println("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() .writeValueAsString(document)); } catch (JsonProcessingException e) { e.printStackTrace(); } } System.out.println("--->handleChanges() END"); }) .build(); } public static CosmosAsyncDatabase createNewDatabase(CosmosAsyncClient client, String databaseName) { return client.createDatabaseIfNotExists(databaseName).block().getDatabase(); } public static void deleteDatabase(CosmosAsyncDatabase cosmosDatabase) { cosmosDatabase.delete().block(); } public static CosmosAsyncContainer createNewCollection(CosmosAsyncClient client, String databaseName, String collectionName) { CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); CosmosAsyncContainer collectionLink = databaseLink.getContainer(collectionName); CosmosAsyncContainerResponse containerResponse = null; try { containerResponse = collectionLink.read().block(); if (containerResponse != null) { throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName)); } } catch (RuntimeException ex) { if (ex instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) ex; if (cosmosClientException.getStatusCode() != 404) { throw ex; } } else { throw ex; } } CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); containerResponse = databaseLink.createContainer(containerSettings, 10000, requestOptions).block(); if (containerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); } return containerResponse.getContainer(); } public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient client, String databaseName, String leaseCollectionName) { CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); CosmosAsyncContainer leaseCollectionLink = databaseLink.getContainer(leaseCollectionName); CosmosAsyncContainerResponse leaseContainerResponse = null; try { leaseContainerResponse = leaseCollectionLink.read().block(); if (leaseContainerResponse != null) { leaseCollectionLink.delete().block(); try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } catch (RuntimeException ex) { if (ex instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) ex; if (cosmosClientException.getStatusCode() != 404) { throw ex; } } else { throw ex; } } CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block(); if (leaseContainerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); } return leaseContainerResponse.getContainer(); } public static void createNewDocuments(CosmosAsyncContainer containerClient, int count, Duration delay) { String suffix = RandomStringUtils.randomAlphabetic(10); for (int i = 0; i <= count; i++) { CosmosItemProperties document = new CosmosItemProperties(); document.setId(String.format("0%d-%s", i, suffix)); containerClient.createItem(document).subscribe(doc -> { try { System.out.println("---->DOCUMENT WRITE: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() .writeValueAsString(doc)); } catch (JsonProcessingException e) { logger.error("Failure in processing json [{}]", e.getMessage(), e); } }); long remainingWork = delay.toMillis(); try { while (remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } } catch (InterruptedException iex) { break; } } } public static boolean ensureWorkIsDone(Duration delay) { long remainingWork = delay.toMillis(); try { while (!isWorkCompleted && remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } } catch (InterruptedException iex) { return false; } return remainingWork > 0; } }
good catch.
public HttpTransportClient(Configs configs, Duration requestTimeout, UserAgentContainer userAgent) { this.configs = configs; this.httpClient = createHttpClient(requestTimeout); this.defaultHeaders = new HashMap<>(); this.defaultHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.defaultHeaders.put(HttpConstants.HttpHeaders.CACHE_CONTROL, HttpConstants.HeaderValues.NO_CACHE); if (userAgent == null) { userAgent = new UserAgentContainer(); } this.defaultHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); this.defaultHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); }
this.defaultHeaders.put(HttpConstants.HttpHeaders.CACHE_CONTROL, HttpConstants.HeaderValues.NO_CACHE);
public HttpTransportClient(Configs configs, Duration requestTimeout, UserAgentContainer userAgent) { this.configs = configs; this.httpClient = createHttpClient(requestTimeout); this.defaultHeaders = new HashMap<>(); this.defaultHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.defaultHeaders.put(HttpConstants.HttpHeaders.CACHE_CONTROL, HttpConstants.HeaderValues.NO_CACHE); if (userAgent == null) { userAgent = new UserAgentContainer(); } this.defaultHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); this.defaultHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); }
class HttpTransportClient extends TransportClient { private final Logger logger = LoggerFactory.getLogger(HttpTransportClient.class); private final HttpClient httpClient; private final Map<String, String> defaultHeaders; private final Configs configs; HttpClient createHttpClient(Duration requestTimeout) { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs); httpClientConfig.withRequestTimeout(requestTimeout); httpClientConfig.withPoolSize(configs.getDirectHttpsMaxConnectionLimit()); return HttpClient.createFixed(httpClientConfig); } @Override public void close() { httpClient.shutdown(); } public Mono<StoreResponse> invokeStoreAsync( Uri physicalAddressUri, RxDocumentServiceRequest request) { try { URI physicalAddress = physicalAddressUri.getURI(); ResourceOperation resourceOperation = new ResourceOperation(request.getOperationType(), request.getResourceType()); String activityId = request.getActivityId().toString(); if (resourceOperation.operationType == OperationType.Recreate) { Map<String, String> errorResponseHeaders = new HashMap<>(); errorResponseHeaders.put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); logger.error("Received Recreate request on Http client"); throw new InternalServerErrorException(RMResources.InternalServerError, null, errorResponseHeaders, null); } HttpRequest httpRequest = prepareHttpMessage(activityId, physicalAddressUri, resourceOperation, request); MutableVolatile<Instant> sendTimeUtc = new MutableVolatile<>(); Mono<HttpResponse> httpResponseMono = this.httpClient .send(httpRequest) .doOnSubscribe(subscription -> { sendTimeUtc.v = Instant.now(); this.beforeRequest( activityId, httpRequest.uri(), request.getResourceType(), httpRequest.headers()); }) .onErrorResume(t -> { Exception exception = Utils.as(t, Exception.class); if (exception == null) { logger.error("critical failure", t); t.printStackTrace(); assert false : "critical failure"; return Mono.error(t); } if (WebExceptionUtility.isWebExceptionRetriable(exception)) { logger.debug("Received retriable exception {} " + "sending the request to {}, will re-resolve the address " + "send time UTC: {}", exception, physicalAddress, sendTimeUtc); GoneException goneException = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), exception, null, physicalAddress); return Mono.error(goneException); } else if (request.isReadOnlyRequest()) { logger.trace("Received exception {} on readonly request" + "sending the request to {}, will reresolve the address " + "send time UTC: {}", exception, physicalAddress, sendTimeUtc); GoneException goneException = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), exception, null, physicalAddress); return Mono.error(goneException); } else { ServiceUnavailableException serviceUnavailableException = new ServiceUnavailableException( String.format( RMResources.ExceptionMessage, RMResources.ServiceUnavailable), exception, null, physicalAddress.toString()); serviceUnavailableException.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); serviceUnavailableException.getResponseHeaders().put(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH, "1"); return Mono.error(serviceUnavailableException); }}) .doOnSuccess(httpClientResponse -> { Instant receivedTimeUtc = Instant.now(); double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); this.afterRequest( activityId, httpClientResponse.statusCode(), durationInMilliSeconds, httpClientResponse.headers()); }) .doOnError(e -> { Instant receivedTimeUtc = Instant.now(); double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); this.afterRequest( activityId, 0, durationInMilliSeconds, null); }); return httpResponseMono.flatMap(rsp -> processHttpResponse(request.getResourceAddress(), httpRequest, activityId, rsp, physicalAddress)); } catch (Exception e) { return Mono.error(e); } } private void beforeRequest(String activityId, URI uri, ResourceType resourceType, HttpHeaders requestHeaders) { } private void afterRequest(String activityId, int statusCode, double durationInMilliSeconds, HttpHeaders responseHeaders) { } private static void addHeader(HttpHeaders requestHeaders, String headerName, RxDocumentServiceRequest request) { String headerValue = request.getHeaders().get(headerName); if (!Strings.isNullOrEmpty(headerValue)) { requestHeaders.set(headerName, headerValue); } } private static void addHeader(HttpHeaders requestHeaders, String headerName, String headerValue) { if (!Strings.isNullOrEmpty(headerValue)) { requestHeaders.set(headerName, headerValue); } } private String getMatch(RxDocumentServiceRequest request, ResourceOperation resourceOperation) { switch (resourceOperation.operationType) { case Delete: case ExecuteJavaScript: case Replace: case Update: case Upsert: return request.getHeaders().get(HttpConstants.HttpHeaders.IF_MATCH); case Read: case ReadFeed: return request.getHeaders().get(HttpConstants.HttpHeaders.IF_NONE_MATCH); default: return null; } } private HttpRequest prepareHttpMessage( String activityId, Uri physicalAddress, ResourceOperation resourceOperation, RxDocumentServiceRequest request) throws Exception { HttpRequest httpRequestMessage; String requestUri; HttpMethod method; switch (resourceOperation.operationType) { case Create: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case ExecuteJavaScript: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case Delete: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.DELETE; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; case Read: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.GET; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; case ReadFeed: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.GET; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; case Replace: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.PUT; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case Update: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = new HttpMethod("PATCH"); assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case Query: case SqlQuery: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); HttpTransportClient.addHeader(httpRequestMessage.headers(), HttpConstants.HttpHeaders.CONTENT_TYPE, request); break; case Upsert: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case Head: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.HEAD; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; case HeadFeed: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.HEAD; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; default: assert false : "Unsupported operation type"; throw new IllegalStateException(); } Map<String, String> documentServiceRequestHeaders = request.getHeaders(); HttpHeaders httpRequestHeaders = httpRequestMessage.headers(); for(Map.Entry<String, String> entry: defaultHeaders.entrySet()) { HttpTransportClient.addHeader(httpRequestHeaders, entry.getKey(), entry.getValue()); } HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.VERSION, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.USER_AGENT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PAGE_SIZE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PRE_TRIGGER_EXCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POST_TRIGGER_EXCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.AUTHORIZATION, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.SESSION_TOKEN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PREFER, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_SCAN_IN_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_CHARGE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_THROTTLE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_LOGGING, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_READ_ONLY_SCRIPT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONTENT_SERIALIZATION_FORMAT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONTINUATION, request.getContinuation()); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PARTITION_KEY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID, request); String dateHeader = HttpUtils.getDateHeader(documentServiceRequestHeaders); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.X_DATE, dateHeader); HttpTransportClient.addHeader(httpRequestHeaders, "Match", this.getMatch(request, resourceOperation)); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.A_IM, request); if (!request.getIsNameBased()) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.RESOURCE_ID, request.getResourceId()); } HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.ENTITY_ID, request.entityId); String fanoutRequestHeader = request.getHeaders().get(WFConstants.BackendHeaders.IS_FANOUT_REQUEST); HttpTransportClient.addHeader(httpRequestMessage.headers(), WFConstants.BackendHeaders.IS_FANOUT_REQUEST, fanoutRequestHeader); if (request.getResourceType() == ResourceType.DocumentCollection) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_PARTITION_INDEX, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.COLLECTION_PARTITION_INDEX)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_SERVICE_INDEX, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.COLLECTION_SERVICE_INDEX)); } if (documentServiceRequestHeaders.get(WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE) != null) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PRIMARY_MASTER_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.PRIMARY_MASTER_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SECONDARY_MASTER_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.SECONDARY_MASTER_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PRIMARY_READONLY_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.PRIMARY_READONLY_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SECONDARY_READONLY_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.SECONDARY_READONLY_KEY)); } if (documentServiceRequestHeaders.get(HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE) != null) { HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE, documentServiceRequestHeaders.get(HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE)); } HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_UPSERT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PARTITION_COUNT, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_RID, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.FILTER_BY_SCHEMA_RESOURCE_ID, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.GATEWAY_SIGNATURE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_QUERY_METRICS, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.FORCE_QUERY_SCAN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.REMOTE_STORAGE_TYPE, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SHARE_THROUGHPUT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_PARTITION_STATISTICS, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CLIENT_RETRY_ATTEMPT_COUNT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.TARGET_LSN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.FEDERATION_ID_FOR_AUTH, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.FANOUT_OPERATION_STATE, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.ALLOW_TENTATIVE_WRITES, request); HttpTransportClient.addHeader(httpRequestHeaders, CustomHeaders.HttpHeaders.EXCLUDE_SYSTEM_PROPERTIES, request); return httpRequestMessage; } static String getResourceFeedUri(ResourceType resourceType, String physicalAddress, RxDocumentServiceRequest request) throws Exception { switch (resourceType) { case Attachment: return getAttachmentFeedUri(physicalAddress, request); case DocumentCollection: return getCollectionFeedUri(physicalAddress, request); case Conflict: return getConflictFeedUri(physicalAddress, request); case Database: return getDatabaseFeedUri(physicalAddress); case Document: return getDocumentFeedUri(physicalAddress, request); case Permission: return getPermissionFeedUri(physicalAddress, request); case StoredProcedure: return getStoredProcedureFeedUri(physicalAddress, request); case Trigger: return getTriggerFeedUri(physicalAddress, request); case User: return getUserFeedUri(physicalAddress, request); case UserDefinedFunction: return getUserDefinedFunctionFeedUri(physicalAddress, request); case Schema: return getSchemaFeedUri(physicalAddress, request); case Offer: return getOfferFeedUri(physicalAddress, request); default: assert false : "Unexpected resource type: " + resourceType; throw new NotFoundException(); } } private static String getResourceEntryUri(ResourceType resourceType, String physicalAddress, RxDocumentServiceRequest request) throws Exception { switch (resourceType) { case Attachment: return getAttachmentEntryUri(physicalAddress, request); case DocumentCollection: return getCollectionEntryUri(physicalAddress, request); case Conflict: return getConflictEntryUri(physicalAddress, request); case Database: return getDatabaseEntryUri(physicalAddress, request); case Document: return getDocumentEntryUri(physicalAddress, request); case Permission: return getPermissionEntryUri(physicalAddress, request); case StoredProcedure: return getStoredProcedureEntryUri(physicalAddress, request); case Trigger: return getTriggerEntryUri(physicalAddress, request); case User: return getUserEntryUri(physicalAddress, request); case UserDefinedFunction: return getUserDefinedFunctionEntryUri(physicalAddress, request); case Schema: return getSchemaEntryUri(physicalAddress, request); case Offer: return getOfferEntryUri(physicalAddress, request); default: assert false: "Unexpected resource type: " + resourceType; throw new IllegalStateException(); } } static String createURI(String baseAddress, String resourcePath) { if (baseAddress.charAt(baseAddress.length() - 1) == '/') { return baseAddress + HttpUtils.urlEncode(trimBeginningAndEndingSlashes(resourcePath)); } else { return baseAddress + '/' + HttpUtils.urlEncode(trimBeginningAndEndingSlashes(resourcePath)); } } static String getRootFeedUri(String baseAddress) { return baseAddress; } private static String getDatabaseFeedUri(String baseAddress) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Database, StringUtils.EMPTY, true)); } private static String getDatabaseEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Database, request, false)); } private static String getCollectionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.DocumentCollection, request, true)); } private static String getStoredProcedureFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.StoredProcedure, request, true)); } private static String getTriggerFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Trigger, request, true)); } private static String getUserDefinedFunctionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.UserDefinedFunction, request, true)); } private static String getCollectionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.DocumentCollection, request, false)); } private static String getStoredProcedureEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.StoredProcedure, request, false)); } private static String getTriggerEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Trigger, request, false)); } private static String getUserDefinedFunctionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.UserDefinedFunction, request, false)); } private static String getDocumentFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Document, request, true)); } private static String getDocumentEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Document, request, false)); } private static String getConflictFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Conflict, request, true)); } private static String getConflictEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Conflict, request, false)); } private static String getAttachmentFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Attachment, request, true)); } private static String getAttachmentEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Attachment, request, false)); } private static String getUserFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.User, request, true)); } private static String getUserEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.User, request, false)); } private static String getPermissionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Permission, request, true)); } private static String getPermissionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Permission, request, false)); } private static String getOfferFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Offer, request, true)); } private static String getSchemaFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Schema, request, true)); } private static String getSchemaEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Schema, request, false)); } private static String getOfferEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Offer, request, false)); } static String getHeader(String[] names, String[] values, String name) { for (int idx = 0; idx < names.length; idx++) { if (Strings.areEqual(names[idx], name)) { return values[idx]; } } return null; } private Mono<StoreResponse> processHttpResponse(String resourceAddress, HttpRequest httpRequest, String activityId, HttpResponse response, URI physicalAddress) { if (response == null) { InternalServerErrorException exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), null, physicalAddress); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); return Mono.error(exception); } if (response.statusCode() < HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY || response.statusCode() == HttpConstants.StatusCodes.NOT_MODIFIED) { return ResponseUtils.toStoreResponse(response, httpRequest); } else { return this.createErrorResponseFromHttpResponse(resourceAddress, activityId, httpRequest, response); } } private Mono<StoreResponse> createErrorResponseFromHttpResponse(String resourceAddress, String activityId, HttpRequest request, HttpResponse response) { int statusCode = response.statusCode(); Mono<String> errorMessageObs = ErrorUtils.getErrorResponseAsync(response, request); return errorMessageObs.flatMap( errorMessage -> { long responseLSN = -1; List<String> lsnValues = null; String[] headerValues = response.headers().values(WFConstants.BackendHeaders.LSN); if (headerValues != null) { lsnValues = com.azure.cosmos.implementation.guava25.collect.Lists.newArrayList(headerValues); } if (lsnValues != null) { String temp = lsnValues.isEmpty() ? null : lsnValues.get(0); responseLSN = Longs.tryParse(temp, responseLSN); } String responsePartitionKeyRangeId = null; List<String> partitionKeyRangeIdValues = null; headerValues = response.headers().values(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID); if (headerValues != null) { partitionKeyRangeIdValues = com.azure.cosmos.implementation.guava25.collect.Lists.newArrayList(headerValues); } if (partitionKeyRangeIdValues != null) { responsePartitionKeyRangeId = Lists.firstOrDefault(partitionKeyRangeIdValues, null); } CosmosClientException exception; switch (statusCode) { case HttpConstants.StatusCodes.UNAUTHORIZED: exception = new UnauthorizedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Unauthorized : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.FORBIDDEN: exception = new ForbiddenException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Forbidden : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.NOTFOUND: if (response.body() != null && response.headers() != null && response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE) != null && !Strings.isNullOrEmpty(response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE)) && Strings.containsIgnoreCase(response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE), RuntimeConstants.MediaTypes.TEXT_HTML)) { exception = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), request.uri().toString()); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); break; } else { exception = new NotFoundException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.NotFound : errorMessage), response.headers(), request.uri()); break; } case HttpConstants.StatusCodes.BADREQUEST: exception = new BadRequestException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.BadRequest : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.METHOD_NOT_ALLOWED: exception = new MethodNotAllowedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.MethodNotAllowed : errorMessage), null, response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.GONE: { ErrorUtils.logGoneException(request.uri(), activityId); Integer nSubStatus = 0; String valueSubStatus = response.headers().value(WFConstants.BackendHeaders.SUB_STATUS); if (!Strings.isNullOrEmpty(valueSubStatus)) { if ((nSubStatus = Integers.tryParse(valueSubStatus)) == null) { exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), response.headers(), request.uri()); break; } } if (nSubStatus == HttpConstants.SubStatusCodes.NAME_CACHE_IS_STALE) { exception = new InvalidPartitionException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE) { exception = new PartitionKeyRangeGoneException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.COMPLETING_SPLIT) { exception = new PartitionKeyRangeIsSplittingException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION) { exception = new PartitionIsMigratingException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else { exception = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), response.headers(), request.uri()); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); break; } } case HttpConstants.StatusCodes.CONFLICT: exception = new ConflictException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.EntityAlreadyExists : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.PRECONDITION_FAILED: exception = new PreconditionFailedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.PreconditionFailed : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE: exception = new RequestEntityTooLargeException( String.format( RMResources.ExceptionMessage, String.format( RMResources.RequestEntityTooLarge, HttpConstants.HttpHeaders.PAGE_SIZE)), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.LOCKED: exception = new LockedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Locked : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.SERVICE_UNAVAILABLE: exception = new ServiceUnavailableException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.ServiceUnavailable : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.REQUEST_TIMEOUT: exception = new RequestTimeoutException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.RequestTimeout : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.RETRY_WITH: exception = new RetryWithException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.RetryWith : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.TOO_MANY_REQUESTS: exception = new RequestRateTooLargeException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.TooManyRequests : errorMessage), response.headers(), request.uri()); List<String> values = null; headerValues = response.headers().values(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (headerValues != null) { values = com.azure.cosmos.implementation.guava25.collect.Lists.newArrayList(headerValues); } if (values == null || values.isEmpty()) { logger.warn("RequestRateTooLargeException being thrown without RetryAfter."); } else { exception.getResponseHeaders().put(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS, values.get(0)); } break; case HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR: exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.InternalServerError : errorMessage), response.headers(), request.uri()); break; default: logger.error("Unrecognized status code {} returned by backend. ActivityId {}", statusCode, activityId); ErrorUtils.logException(request.uri(), activityId); exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), response.headers(), request.uri()); break; } BridgeInternal.setLSN(exception, responseLSN); BridgeInternal.setPartitionKeyRangeId(exception, responsePartitionKeyRangeId); BridgeInternal.setResourceAddress(exception, resourceAddress); BridgeInternal.setRequestHeaders(exception, HttpUtils.asMap(request.headers())); return Mono.error(exception); } ); } }
class HttpTransportClient extends TransportClient { private final Logger logger = LoggerFactory.getLogger(HttpTransportClient.class); private final HttpClient httpClient; private final Map<String, String> defaultHeaders; private final Configs configs; HttpClient createHttpClient(Duration requestTimeout) { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs); httpClientConfig.withRequestTimeout(requestTimeout); httpClientConfig.withPoolSize(configs.getDirectHttpsMaxConnectionLimit()); return HttpClient.createFixed(httpClientConfig); } @Override public void close() { httpClient.shutdown(); } public Mono<StoreResponse> invokeStoreAsync( Uri physicalAddressUri, RxDocumentServiceRequest request) { try { URI physicalAddress = physicalAddressUri.getURI(); ResourceOperation resourceOperation = new ResourceOperation(request.getOperationType(), request.getResourceType()); String activityId = request.getActivityId().toString(); if (resourceOperation.operationType == OperationType.Recreate) { Map<String, String> errorResponseHeaders = new HashMap<>(); errorResponseHeaders.put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); logger.error("Received Recreate request on Http client"); throw new InternalServerErrorException(RMResources.InternalServerError, null, errorResponseHeaders, null); } HttpRequest httpRequest = prepareHttpMessage(activityId, physicalAddressUri, resourceOperation, request); MutableVolatile<Instant> sendTimeUtc = new MutableVolatile<>(); Mono<HttpResponse> httpResponseMono = this.httpClient .send(httpRequest) .doOnSubscribe(subscription -> { sendTimeUtc.v = Instant.now(); this.beforeRequest( activityId, httpRequest.uri(), request.getResourceType(), httpRequest.headers()); }) .onErrorResume(t -> { Exception exception = Utils.as(t, Exception.class); if (exception == null) { logger.error("critical failure", t); t.printStackTrace(); assert false : "critical failure"; return Mono.error(t); } if (WebExceptionUtility.isWebExceptionRetriable(exception)) { logger.debug("Received retriable exception {} " + "sending the request to {}, will re-resolve the address " + "send time UTC: {}", exception, physicalAddress, sendTimeUtc); GoneException goneException = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), exception, null, physicalAddress); return Mono.error(goneException); } else if (request.isReadOnlyRequest()) { logger.trace("Received exception {} on readonly request" + "sending the request to {}, will reresolve the address " + "send time UTC: {}", exception, physicalAddress, sendTimeUtc); GoneException goneException = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), exception, null, physicalAddress); return Mono.error(goneException); } else { ServiceUnavailableException serviceUnavailableException = new ServiceUnavailableException( String.format( RMResources.ExceptionMessage, RMResources.ServiceUnavailable), exception, null, physicalAddress.toString()); serviceUnavailableException.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); serviceUnavailableException.getResponseHeaders().put(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH, "1"); return Mono.error(serviceUnavailableException); }}) .doOnSuccess(httpClientResponse -> { Instant receivedTimeUtc = Instant.now(); double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); this.afterRequest( activityId, httpClientResponse.statusCode(), durationInMilliSeconds, httpClientResponse.headers()); }) .doOnError(e -> { Instant receivedTimeUtc = Instant.now(); double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); this.afterRequest( activityId, 0, durationInMilliSeconds, null); }); return httpResponseMono.flatMap(rsp -> processHttpResponse(request.getResourceAddress(), httpRequest, activityId, rsp, physicalAddress)); } catch (Exception e) { return Mono.error(e); } } private void beforeRequest(String activityId, URI uri, ResourceType resourceType, HttpHeaders requestHeaders) { } private void afterRequest(String activityId, int statusCode, double durationInMilliSeconds, HttpHeaders responseHeaders) { } private static void addHeader(HttpHeaders requestHeaders, String headerName, RxDocumentServiceRequest request) { String headerValue = request.getHeaders().get(headerName); if (!Strings.isNullOrEmpty(headerValue)) { requestHeaders.set(headerName, headerValue); } } private static void addHeader(HttpHeaders requestHeaders, String headerName, String headerValue) { if (!Strings.isNullOrEmpty(headerValue)) { requestHeaders.set(headerName, headerValue); } } private String getMatch(RxDocumentServiceRequest request, ResourceOperation resourceOperation) { switch (resourceOperation.operationType) { case Delete: case ExecuteJavaScript: case Replace: case Update: case Upsert: return request.getHeaders().get(HttpConstants.HttpHeaders.IF_MATCH); case Read: case ReadFeed: return request.getHeaders().get(HttpConstants.HttpHeaders.IF_NONE_MATCH); default: return null; } } private HttpRequest prepareHttpMessage( String activityId, Uri physicalAddress, ResourceOperation resourceOperation, RxDocumentServiceRequest request) throws Exception { HttpRequest httpRequestMessage; String requestUri; HttpMethod method; switch (resourceOperation.operationType) { case Create: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case ExecuteJavaScript: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case Delete: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.DELETE; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; case Read: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.GET; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; case ReadFeed: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.GET; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; case Replace: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.PUT; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case Update: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = new HttpMethod("PATCH"); assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case Query: case SqlQuery: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); HttpTransportClient.addHeader(httpRequestMessage.headers(), HttpConstants.HttpHeaders.CONTENT_TYPE, request); break; case Upsert: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContentAsByteBufFlux() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContentAsByteBufFlux()); break; case Head: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.HEAD; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; case HeadFeed: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.HEAD; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); break; default: assert false : "Unsupported operation type"; throw new IllegalStateException(); } Map<String, String> documentServiceRequestHeaders = request.getHeaders(); HttpHeaders httpRequestHeaders = httpRequestMessage.headers(); for(Map.Entry<String, String> entry: defaultHeaders.entrySet()) { HttpTransportClient.addHeader(httpRequestHeaders, entry.getKey(), entry.getValue()); } HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.VERSION, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.USER_AGENT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PAGE_SIZE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PRE_TRIGGER_EXCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POST_TRIGGER_EXCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.AUTHORIZATION, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.SESSION_TOKEN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PREFER, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_SCAN_IN_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_CHARGE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_THROTTLE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_LOGGING, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_READ_ONLY_SCRIPT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONTENT_SERIALIZATION_FORMAT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONTINUATION, request.getContinuation()); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PARTITION_KEY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID, request); String dateHeader = HttpUtils.getDateHeader(documentServiceRequestHeaders); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.X_DATE, dateHeader); HttpTransportClient.addHeader(httpRequestHeaders, "Match", this.getMatch(request, resourceOperation)); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.A_IM, request); if (!request.getIsNameBased()) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.RESOURCE_ID, request.getResourceId()); } HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.ENTITY_ID, request.entityId); String fanoutRequestHeader = request.getHeaders().get(WFConstants.BackendHeaders.IS_FANOUT_REQUEST); HttpTransportClient.addHeader(httpRequestMessage.headers(), WFConstants.BackendHeaders.IS_FANOUT_REQUEST, fanoutRequestHeader); if (request.getResourceType() == ResourceType.DocumentCollection) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_PARTITION_INDEX, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.COLLECTION_PARTITION_INDEX)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_SERVICE_INDEX, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.COLLECTION_SERVICE_INDEX)); } if (documentServiceRequestHeaders.get(WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE) != null) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PRIMARY_MASTER_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.PRIMARY_MASTER_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SECONDARY_MASTER_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.SECONDARY_MASTER_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PRIMARY_READONLY_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.PRIMARY_READONLY_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SECONDARY_READONLY_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.SECONDARY_READONLY_KEY)); } if (documentServiceRequestHeaders.get(HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE) != null) { HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE, documentServiceRequestHeaders.get(HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE)); } HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_UPSERT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PARTITION_COUNT, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_RID, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.FILTER_BY_SCHEMA_RESOURCE_ID, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.GATEWAY_SIGNATURE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_QUERY_METRICS, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.FORCE_QUERY_SCAN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.REMOTE_STORAGE_TYPE, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SHARE_THROUGHPUT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_PARTITION_STATISTICS, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CLIENT_RETRY_ATTEMPT_COUNT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.TARGET_LSN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.FEDERATION_ID_FOR_AUTH, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.FANOUT_OPERATION_STATE, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.ALLOW_TENTATIVE_WRITES, request); HttpTransportClient.addHeader(httpRequestHeaders, CustomHeaders.HttpHeaders.EXCLUDE_SYSTEM_PROPERTIES, request); return httpRequestMessage; } static String getResourceFeedUri(ResourceType resourceType, String physicalAddress, RxDocumentServiceRequest request) throws Exception { switch (resourceType) { case Attachment: return getAttachmentFeedUri(physicalAddress, request); case DocumentCollection: return getCollectionFeedUri(physicalAddress, request); case Conflict: return getConflictFeedUri(physicalAddress, request); case Database: return getDatabaseFeedUri(physicalAddress); case Document: return getDocumentFeedUri(physicalAddress, request); case Permission: return getPermissionFeedUri(physicalAddress, request); case StoredProcedure: return getStoredProcedureFeedUri(physicalAddress, request); case Trigger: return getTriggerFeedUri(physicalAddress, request); case User: return getUserFeedUri(physicalAddress, request); case UserDefinedFunction: return getUserDefinedFunctionFeedUri(physicalAddress, request); case Schema: return getSchemaFeedUri(physicalAddress, request); case Offer: return getOfferFeedUri(physicalAddress, request); default: assert false : "Unexpected resource type: " + resourceType; throw new NotFoundException(); } } private static String getResourceEntryUri(ResourceType resourceType, String physicalAddress, RxDocumentServiceRequest request) throws Exception { switch (resourceType) { case Attachment: return getAttachmentEntryUri(physicalAddress, request); case DocumentCollection: return getCollectionEntryUri(physicalAddress, request); case Conflict: return getConflictEntryUri(physicalAddress, request); case Database: return getDatabaseEntryUri(physicalAddress, request); case Document: return getDocumentEntryUri(physicalAddress, request); case Permission: return getPermissionEntryUri(physicalAddress, request); case StoredProcedure: return getStoredProcedureEntryUri(physicalAddress, request); case Trigger: return getTriggerEntryUri(physicalAddress, request); case User: return getUserEntryUri(physicalAddress, request); case UserDefinedFunction: return getUserDefinedFunctionEntryUri(physicalAddress, request); case Schema: return getSchemaEntryUri(physicalAddress, request); case Offer: return getOfferEntryUri(physicalAddress, request); default: assert false: "Unexpected resource type: " + resourceType; throw new IllegalStateException(); } } static String createURI(String baseAddress, String resourcePath) { if (baseAddress.charAt(baseAddress.length() - 1) == '/') { return baseAddress + HttpUtils.urlEncode(trimBeginningAndEndingSlashes(resourcePath)); } else { return baseAddress + '/' + HttpUtils.urlEncode(trimBeginningAndEndingSlashes(resourcePath)); } } static String getRootFeedUri(String baseAddress) { return baseAddress; } private static String getDatabaseFeedUri(String baseAddress) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Database, StringUtils.EMPTY, true)); } private static String getDatabaseEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Database, request, false)); } private static String getCollectionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.DocumentCollection, request, true)); } private static String getStoredProcedureFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.StoredProcedure, request, true)); } private static String getTriggerFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Trigger, request, true)); } private static String getUserDefinedFunctionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.UserDefinedFunction, request, true)); } private static String getCollectionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.DocumentCollection, request, false)); } private static String getStoredProcedureEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.StoredProcedure, request, false)); } private static String getTriggerEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Trigger, request, false)); } private static String getUserDefinedFunctionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.UserDefinedFunction, request, false)); } private static String getDocumentFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Document, request, true)); } private static String getDocumentEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Document, request, false)); } private static String getConflictFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Conflict, request, true)); } private static String getConflictEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Conflict, request, false)); } private static String getAttachmentFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Attachment, request, true)); } private static String getAttachmentEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Attachment, request, false)); } private static String getUserFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.User, request, true)); } private static String getUserEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.User, request, false)); } private static String getPermissionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Permission, request, true)); } private static String getPermissionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Permission, request, false)); } private static String getOfferFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Offer, request, true)); } private static String getSchemaFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Schema, request, true)); } private static String getSchemaEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Schema, request, false)); } private static String getOfferEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Offer, request, false)); } static String getHeader(String[] names, String[] values, String name) { for (int idx = 0; idx < names.length; idx++) { if (Strings.areEqual(names[idx], name)) { return values[idx]; } } return null; } private Mono<StoreResponse> processHttpResponse(String resourceAddress, HttpRequest httpRequest, String activityId, HttpResponse response, URI physicalAddress) { if (response == null) { InternalServerErrorException exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), null, physicalAddress); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); return Mono.error(exception); } if (response.statusCode() < HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY || response.statusCode() == HttpConstants.StatusCodes.NOT_MODIFIED) { return ResponseUtils.toStoreResponse(response, httpRequest); } else { return this.createErrorResponseFromHttpResponse(resourceAddress, activityId, httpRequest, response); } } private Mono<StoreResponse> createErrorResponseFromHttpResponse(String resourceAddress, String activityId, HttpRequest request, HttpResponse response) { int statusCode = response.statusCode(); Mono<String> errorMessageObs = ErrorUtils.getErrorResponseAsync(response, request); return errorMessageObs.flatMap( errorMessage -> { long responseLSN = -1; List<String> lsnValues = null; String[] headerValues = response.headers().values(WFConstants.BackendHeaders.LSN); if (headerValues != null) { lsnValues = com.azure.cosmos.implementation.guava25.collect.Lists.newArrayList(headerValues); } if (lsnValues != null) { String temp = lsnValues.isEmpty() ? null : lsnValues.get(0); responseLSN = Longs.tryParse(temp, responseLSN); } String responsePartitionKeyRangeId = null; List<String> partitionKeyRangeIdValues = null; headerValues = response.headers().values(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID); if (headerValues != null) { partitionKeyRangeIdValues = com.azure.cosmos.implementation.guava25.collect.Lists.newArrayList(headerValues); } if (partitionKeyRangeIdValues != null) { responsePartitionKeyRangeId = Lists.firstOrDefault(partitionKeyRangeIdValues, null); } CosmosClientException exception; switch (statusCode) { case HttpConstants.StatusCodes.UNAUTHORIZED: exception = new UnauthorizedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Unauthorized : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.FORBIDDEN: exception = new ForbiddenException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Forbidden : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.NOTFOUND: if (response.body() != null && response.headers() != null && response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE) != null && !Strings.isNullOrEmpty(response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE)) && Strings.containsIgnoreCase(response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE), RuntimeConstants.MediaTypes.TEXT_HTML)) { exception = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), request.uri().toString()); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); break; } else { exception = new NotFoundException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.NotFound : errorMessage), response.headers(), request.uri()); break; } case HttpConstants.StatusCodes.BADREQUEST: exception = new BadRequestException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.BadRequest : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.METHOD_NOT_ALLOWED: exception = new MethodNotAllowedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.MethodNotAllowed : errorMessage), null, response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.GONE: { ErrorUtils.logGoneException(request.uri(), activityId); Integer nSubStatus = 0; String valueSubStatus = response.headers().value(WFConstants.BackendHeaders.SUB_STATUS); if (!Strings.isNullOrEmpty(valueSubStatus)) { if ((nSubStatus = Integers.tryParse(valueSubStatus)) == null) { exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), response.headers(), request.uri()); break; } } if (nSubStatus == HttpConstants.SubStatusCodes.NAME_CACHE_IS_STALE) { exception = new InvalidPartitionException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE) { exception = new PartitionKeyRangeGoneException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.COMPLETING_SPLIT) { exception = new PartitionKeyRangeIsSplittingException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION) { exception = new PartitionIsMigratingException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else { exception = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), response.headers(), request.uri()); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); break; } } case HttpConstants.StatusCodes.CONFLICT: exception = new ConflictException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.EntityAlreadyExists : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.PRECONDITION_FAILED: exception = new PreconditionFailedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.PreconditionFailed : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE: exception = new RequestEntityTooLargeException( String.format( RMResources.ExceptionMessage, String.format( RMResources.RequestEntityTooLarge, HttpConstants.HttpHeaders.PAGE_SIZE)), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.LOCKED: exception = new LockedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Locked : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.SERVICE_UNAVAILABLE: exception = new ServiceUnavailableException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.ServiceUnavailable : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.REQUEST_TIMEOUT: exception = new RequestTimeoutException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.RequestTimeout : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.RETRY_WITH: exception = new RetryWithException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.RetryWith : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.TOO_MANY_REQUESTS: exception = new RequestRateTooLargeException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.TooManyRequests : errorMessage), response.headers(), request.uri()); List<String> values = null; headerValues = response.headers().values(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (headerValues != null) { values = com.azure.cosmos.implementation.guava25.collect.Lists.newArrayList(headerValues); } if (values == null || values.isEmpty()) { logger.warn("RequestRateTooLargeException being thrown without RetryAfter."); } else { exception.getResponseHeaders().put(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS, values.get(0)); } break; case HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR: exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.InternalServerError : errorMessage), response.headers(), request.uri()); break; default: logger.error("Unrecognized status code {} returned by backend. ActivityId {}", statusCode, activityId); ErrorUtils.logException(request.uri(), activityId); exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), response.headers(), request.uri()); break; } BridgeInternal.setLSN(exception, responseLSN); BridgeInternal.setPartitionKeyRangeId(exception, responsePartitionKeyRangeId); BridgeInternal.setResourceAddress(exception, resourceAddress); BridgeInternal.setRequestHeaders(exception, HttpUtils.asMap(request.headers())); return Mono.error(exception); } ); } }
This is SampleChangeFeedProcessor example, which creates some documents before listening to them, so used it. This is not in the source code.
public static CosmosAsyncClient getCosmosClient() { return new CosmosClientBuilder() .endpoint(SampleConfigurations.HOST) .key(SampleConfigurations.MASTER_KEY) .connectionPolicy(ConnectionPolicy.getDefaultPolicy()) .consistencyLevel(ConsistencyLevel.EVENTUAL) .returnMinimalResponse(false) .buildAsyncClient(); }
.returnMinimalResponse(false)
public static CosmosAsyncClient getCosmosClient() { return new CosmosClientBuilder() .endpoint(SampleConfigurations.HOST) .key(SampleConfigurations.MASTER_KEY) .connectionPolicy(ConnectionPolicy.getDefaultPolicy()) .consistencyLevel(ConsistencyLevel.EVENTUAL) .contentResponseOnWriteEnabled(true) .buildAsyncClient(); }
class SampleChangeFeedProcessor { public static int WAIT_FOR_WORK = 60; public static final String DATABASE_NAME = "db_" + RandomStringUtils.randomAlphabetic(7); public static final String COLLECTION_NAME = "coll_" + RandomStringUtils.randomAlphabetic(7); private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); private static ChangeFeedProcessor changeFeedProcessorInstance; private static boolean isWorkCompleted = false; public static void main (String[]args) { System.out.println("BEGIN Sample"); try { System.out.println("-->CREATE DocumentClient"); CosmosAsyncClient client = getCosmosClient(); System.out.println("-->CREATE sample's database: " + DATABASE_NAME); CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); System.out.println("-->CREATE container for documents: " + COLLECTION_NAME); CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); changeFeedProcessorInstance.start().subscribe(aVoid -> { createNewDocuments(feedContainer, 10, Duration.ofSeconds(3)); isWorkCompleted = true; }); long remainingWork = WAIT_FOR_WORK; while (!isWorkCompleted && remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } if (isWorkCompleted) { if (changeFeedProcessorInstance != null) { changeFeedProcessorInstance.stop().subscribe().wait(10000); } } else { throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); } System.out.println("-->DELETE sample's database: " + DATABASE_NAME); deleteDatabase(cosmosDatabase); Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } System.out.println("END Sample"); System.exit(0); } public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosAsyncContainer feedContainer, CosmosAsyncContainer leaseContainer) { return ChangeFeedProcessor.changeFeedProcessorBuilder() .hostName(hostName) .feedContainer(feedContainer) .leaseContainer(leaseContainer) .handleChanges((List<JsonNode> docs) -> { System.out.println("--->setHandleChanges() START"); for (JsonNode document : docs) { try { System.out.println("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() .writeValueAsString(document)); } catch (JsonProcessingException e) { e.printStackTrace(); } } System.out.println("--->handleChanges() END"); }) .build(); } public static CosmosAsyncDatabase createNewDatabase(CosmosAsyncClient client, String databaseName) { return client.createDatabaseIfNotExists(databaseName).block().getDatabase(); } public static void deleteDatabase(CosmosAsyncDatabase cosmosDatabase) { cosmosDatabase.delete().block(); } public static CosmosAsyncContainer createNewCollection(CosmosAsyncClient client, String databaseName, String collectionName) { CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); CosmosAsyncContainer collectionLink = databaseLink.getContainer(collectionName); CosmosAsyncContainerResponse containerResponse = null; try { containerResponse = collectionLink.read().block(); if (containerResponse != null) { throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName)); } } catch (RuntimeException ex) { if (ex instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) ex; if (cosmosClientException.getStatusCode() != 404) { throw ex; } } else { throw ex; } } CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); containerResponse = databaseLink.createContainer(containerSettings, 10000, requestOptions).block(); if (containerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); } return containerResponse.getContainer(); } public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient client, String databaseName, String leaseCollectionName) { CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); CosmosAsyncContainer leaseCollectionLink = databaseLink.getContainer(leaseCollectionName); CosmosAsyncContainerResponse leaseContainerResponse = null; try { leaseContainerResponse = leaseCollectionLink.read().block(); if (leaseContainerResponse != null) { leaseCollectionLink.delete().block(); try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } catch (RuntimeException ex) { if (ex instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) ex; if (cosmosClientException.getStatusCode() != 404) { throw ex; } } else { throw ex; } } CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block(); if (leaseContainerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); } return leaseContainerResponse.getContainer(); } public static void createNewDocuments(CosmosAsyncContainer containerClient, int count, Duration delay) { String suffix = RandomStringUtils.randomAlphabetic(10); for (int i = 0; i <= count; i++) { CosmosItemProperties document = new CosmosItemProperties(); document.setId(String.format("0%d-%s", i, suffix)); containerClient.createItem(document).subscribe(doc -> { try { System.out.println("---->DOCUMENT WRITE: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() .writeValueAsString(doc)); } catch (JsonProcessingException e) { logger.error("Failure in processing json [{}]", e.getMessage(), e); } }); long remainingWork = delay.toMillis(); try { while (remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } } catch (InterruptedException iex) { break; } } } public static boolean ensureWorkIsDone(Duration delay) { long remainingWork = delay.toMillis(); try { while (!isWorkCompleted && remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } } catch (InterruptedException iex) { return false; } return remainingWork > 0; } }
class SampleChangeFeedProcessor { public static int WAIT_FOR_WORK = 60; public static final String DATABASE_NAME = "db_" + RandomStringUtils.randomAlphabetic(7); public static final String COLLECTION_NAME = "coll_" + RandomStringUtils.randomAlphabetic(7); private static final ObjectMapper OBJECT_MAPPER = Utils.getSimpleObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(SampleChangeFeedProcessor.class.getSimpleName()); private static ChangeFeedProcessor changeFeedProcessorInstance; private static boolean isWorkCompleted = false; public static void main (String[]args) { System.out.println("BEGIN Sample"); try { System.out.println("-->CREATE DocumentClient"); CosmosAsyncClient client = getCosmosClient(); System.out.println("-->CREATE sample's database: " + DATABASE_NAME); CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); System.out.println("-->CREATE container for documents: " + COLLECTION_NAME); CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); changeFeedProcessorInstance.start().subscribe(aVoid -> { createNewDocuments(feedContainer, 10, Duration.ofSeconds(3)); isWorkCompleted = true; }); long remainingWork = WAIT_FOR_WORK; while (!isWorkCompleted && remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } if (isWorkCompleted) { if (changeFeedProcessorInstance != null) { changeFeedProcessorInstance.stop().subscribe().wait(10000); } } else { throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); } System.out.println("-->DELETE sample's database: " + DATABASE_NAME); deleteDatabase(cosmosDatabase); Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } System.out.println("END Sample"); System.exit(0); } public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosAsyncContainer feedContainer, CosmosAsyncContainer leaseContainer) { return ChangeFeedProcessor.changeFeedProcessorBuilder() .hostName(hostName) .feedContainer(feedContainer) .leaseContainer(leaseContainer) .handleChanges((List<JsonNode> docs) -> { System.out.println("--->setHandleChanges() START"); for (JsonNode document : docs) { try { System.out.println("---->DOCUMENT RECEIVED: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() .writeValueAsString(document)); } catch (JsonProcessingException e) { e.printStackTrace(); } } System.out.println("--->handleChanges() END"); }) .build(); } public static CosmosAsyncDatabase createNewDatabase(CosmosAsyncClient client, String databaseName) { return client.createDatabaseIfNotExists(databaseName).block().getDatabase(); } public static void deleteDatabase(CosmosAsyncDatabase cosmosDatabase) { cosmosDatabase.delete().block(); } public static CosmosAsyncContainer createNewCollection(CosmosAsyncClient client, String databaseName, String collectionName) { CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); CosmosAsyncContainer collectionLink = databaseLink.getContainer(collectionName); CosmosAsyncContainerResponse containerResponse = null; try { containerResponse = collectionLink.read().block(); if (containerResponse != null) { throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName)); } } catch (RuntimeException ex) { if (ex instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) ex; if (cosmosClientException.getStatusCode() != 404) { throw ex; } } else { throw ex; } } CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); containerResponse = databaseLink.createContainer(containerSettings, 10000, requestOptions).block(); if (containerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); } return containerResponse.getContainer(); } public static CosmosAsyncContainer createNewLeaseCollection(CosmosAsyncClient client, String databaseName, String leaseCollectionName) { CosmosAsyncDatabase databaseLink = client.getDatabase(databaseName); CosmosAsyncContainer leaseCollectionLink = databaseLink.getContainer(leaseCollectionName); CosmosAsyncContainerResponse leaseContainerResponse = null; try { leaseContainerResponse = leaseCollectionLink.read().block(); if (leaseContainerResponse != null) { leaseCollectionLink.delete().block(); try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } catch (RuntimeException ex) { if (ex instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) ex; if (cosmosClientException.getStatusCode() != 404) { throw ex; } } else { throw ex; } } CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block(); if (leaseContainerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); } return leaseContainerResponse.getContainer(); } public static void createNewDocuments(CosmosAsyncContainer containerClient, int count, Duration delay) { String suffix = RandomStringUtils.randomAlphabetic(10); for (int i = 0; i <= count; i++) { CosmosItemProperties document = new CosmosItemProperties(); document.setId(String.format("0%d-%s", i, suffix)); containerClient.createItem(document).subscribe(doc -> { try { System.out.println("---->DOCUMENT WRITE: " + OBJECT_MAPPER.writerWithDefaultPrettyPrinter() .writeValueAsString(doc)); } catch (JsonProcessingException e) { logger.error("Failure in processing json [{}]", e.getMessage(), e); } }); long remainingWork = delay.toMillis(); try { while (remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } } catch (InterruptedException iex) { break; } } } public static boolean ensureWorkIsDone(Duration delay) { long remainingWork = delay.toMillis(); try { while (!isWorkCompleted && remainingWork > 0) { Thread.sleep(100); remainingWork -= 100; } } catch (InterruptedException iex) { return false; } return remainingWork > 0; } }
is it the case that when change feed is enabled then storage account will have some special container to store them? so its absence means change-feed-not-enabled?
private Mono<Boolean> validateChangefeed() { return this.client.exists() .flatMap(exists -> { if (exists == null || !exists) { return FluxUtil.monoError(logger, new RuntimeException("Changefeed has not been enabled for " + "this account.")); } return Mono.just(true); }); }
+ "this account."));
private Mono<Boolean> validateChangefeed() { return this.client.exists() .flatMap(exists -> { if (exists == null || !exists) { return FluxUtil.monoError(logger, new RuntimeException("Changefeed has not been enabled for " + "this account.")); } return Mono.just(true); }); }
class Changefeed { private final ClientLogger logger = new ClientLogger(Changefeed.class); private static final String SEGMENT_PREFIX = "idx/segments/"; private static final String METADATA_SEGMENT_PATH = "meta/segments.json"; private static final ObjectMapper mapper = new ObjectMapper(); private final BlobContainerAsyncClient client; /* Changefeed container */ private final OffsetDateTime startTime; /* User provided start time. */ private final OffsetDateTime endTime; /* User provided end time. */ private OffsetDateTime lastConsumable; /* Last consumable time. The latest time the changefeed can safely be read from.*/ private OffsetDateTime safeEndTime; /* Soonest time between lastConsumable and endTime. */ private final ChangefeedCursor cfCursor; /* Cursor associated with changefeed. */ private final ChangefeedCursor userCursor; /* User provided cursor. */ private final SegmentFactory segmentFactory; /* Segment factory. */ /** * Creates a new Changefeed. */ Changefeed(BlobContainerAsyncClient client, OffsetDateTime startTime, OffsetDateTime endTime, ChangefeedCursor userCursor, SegmentFactory segmentFactory) { this.client = client; this.startTime = startTime; this.endTime = endTime; this.userCursor = userCursor; this.segmentFactory = segmentFactory; this.cfCursor = new ChangefeedCursor(this.endTime); this.safeEndTime = endTime; } /** * Get all the events for the Changefeed. * @return A reactive stream of {@link BlobChangefeedEventWrapper} */ Flux<BlobChangefeedEventWrapper> getEvents() { return validateChangefeed() .then(populateLastConsumable()) .thenMany(listYears()) .concatMap(this::listSegmentsForYear) .concatMap(this::getEventsForSegment); } /** * Validates that changefeed has been enabled for the account. */ /** * Populates the last consumable property from changefeed metadata. * Log files in any segment that is dated after the date of the LastConsumable property in the * $blobchangefeed/meta/segments.json file, should not be consumed by your application. */ private Mono<OffsetDateTime> populateLastConsumable() { /* We can keep the entire metadata file in memory since it is expected to only be a few hundred bytes. */ return DownloadUtils.downloadToByteArray(this.client, METADATA_SEGMENT_PATH) /* Parse JSON for last consumable. */ .flatMap(json -> { try { JsonNode jsonNode = mapper.reader().readTree(json); this.lastConsumable = OffsetDateTime.parse(jsonNode.get("lastConsumable").asText()); if (this.lastConsumable.isBefore(endTime)) { this.safeEndTime = this.lastConsumable; } return Mono.just(this.lastConsumable); } catch (IOException e) { return FluxUtil.monoError(logger, new UncheckedIOException(e)); } }); } /** * List years for which changefeed data exists. */ private Flux<String> listYears() { return client.listBlobsByHierarchy(SEGMENT_PREFIX) .map(BlobItem::getName) .filter(yearPath -> TimeUtils.validYear(yearPath, startTime, safeEndTime)); } /** * List segments for years of interest. */ private Flux<String> listSegmentsForYear(String year) { return client.listBlobs(new ListBlobsOptions().setPrefix(year)) .map(BlobItem::getName) .filter(segmentPath -> TimeUtils.validSegment(segmentPath, startTime, safeEndTime)); } /** * Get events for segments of interest. */ private Flux<BlobChangefeedEventWrapper> getEventsForSegment(String segment) { OffsetDateTime segmentTime = TimeUtils.convertPathToTime(segment); return segmentFactory.getSegment(segment, cfCursor.toSegmentCursor(segmentTime), userCursor) .getEvents(); } }
class Changefeed { private final ClientLogger logger = new ClientLogger(Changefeed.class); private static final String SEGMENT_PREFIX = "idx/segments/"; private static final String METADATA_SEGMENT_PATH = "meta/segments.json"; private static final ObjectMapper MAPPER = new ObjectMapper(); private final BlobContainerAsyncClient client; /* Changefeed container */ private final OffsetDateTime startTime; /* User provided start time. */ private final OffsetDateTime endTime; /* User provided end time. */ private OffsetDateTime lastConsumable; /* Last consumable time. The latest time the changefeed can safely be read from.*/ private OffsetDateTime safeEndTime; /* Soonest time between lastConsumable and endTime. */ private final ChangefeedCursor cfCursor; /* Cursor associated with changefeed. */ private final ChangefeedCursor userCursor; /* User provided cursor. */ private final SegmentFactory segmentFactory; /* Segment factory. */ /** * Creates a new Changefeed. */ Changefeed(BlobContainerAsyncClient client, OffsetDateTime startTime, OffsetDateTime endTime, ChangefeedCursor userCursor, SegmentFactory segmentFactory) { this.client = client; this.startTime = startTime; this.endTime = endTime; this.userCursor = userCursor; this.segmentFactory = segmentFactory; this.cfCursor = new ChangefeedCursor(this.endTime); this.safeEndTime = endTime; } /** * Get all the events for the Changefeed. * @return A reactive stream of {@link BlobChangefeedEventWrapper} */ Flux<BlobChangefeedEventWrapper> getEvents() { return validateChangefeed() .then(populateLastConsumable()) .thenMany(listYears()) .concatMap(this::listSegmentsForYear) .concatMap(this::getEventsForSegment); } /** * Validates that changefeed has been enabled for the account. */ /* TODO (gapra) : Investigate making this thread safe. */ /** * Populates the last consumable property from changefeed metadata. * Log files in any segment that is dated after the date of the LastConsumable property in the * $blobchangefeed/meta/segments.json file, should not be consumed by your application. */ private Mono<OffsetDateTime> populateLastConsumable() { /* We can keep the entire metadata file in memory since it is expected to only be a few hundred bytes. */ return DownloadUtils.downloadToByteArray(this.client, METADATA_SEGMENT_PATH) /* Parse JSON for last consumable. */ .flatMap(json -> { try { JsonNode jsonNode = MAPPER.reader().readTree(json); this.lastConsumable = OffsetDateTime.parse(jsonNode.get("lastConsumable").asText()); if (this.lastConsumable.isBefore(endTime)) { this.safeEndTime = this.lastConsumable; } return Mono.just(this.lastConsumable); } catch (IOException e) { return FluxUtil.monoError(logger, new UncheckedIOException(e)); } }); } /** * List years for which changefeed data exists. */ private Flux<String> listYears() { return client.listBlobsByHierarchy(SEGMENT_PREFIX) .map(BlobItem::getName) .filter(yearPath -> TimeUtils.validYear(yearPath, startTime, safeEndTime)); } /** * List segments for years of interest. */ private Flux<String> listSegmentsForYear(String year) { return client.listBlobs(new ListBlobsOptions().setPrefix(year)) .map(BlobItem::getName) .filter(segmentPath -> TimeUtils.validSegment(segmentPath, startTime, safeEndTime)); } /** * Get events for segments of interest. */ private Flux<BlobChangefeedEventWrapper> getEventsForSegment(String segment) { OffsetDateTime segmentTime = TimeUtils.convertPathToTime(segment); return segmentFactory.getSegment(segment, cfCursor.toSegmentCursor(segmentTime), userCursor) .getEvents(); } }
The indentation is off here?
void validateUSReceiptData(USReceipt actualRecognizedReceipt, boolean includeTextDetails) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); final Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validatePageRangeData(documentResult.getPageRange().get(0), actualRecognizedReceipt.getRecognizedForm().getPageRange()); validatePageRangeData(documentResult.getPageRange().get(1), actualRecognizedReceipt.getRecognizedForm().getPageRange()); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceipt.getReceiptType().getType()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceipt.getReceiptType().getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceipt.getMerchantName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceipt.getMerchantPhoneNumber(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceipt.getMerchantAddress(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceipt.getTotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceipt.getSubtotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceipt.getTax(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceipt.getTransactionDate(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceipt.getTransactionTime(), readResults, includeTextDetails); validateReceiptItemsData(expectedReceiptFields.get("Items").getValueArray(), actualRecognizedReceipt.getReceiptItems(), readResults, includeTextDetails); }
validatePageRangeData(documentResult.getPageRange().get(0), actualRecognizedReceipt.getRecognizedForm().getPageRange());
void validateUSReceiptData(USReceipt actualRecognizedReceipt, boolean includeTextDetails) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); final Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validatePageRangeData(documentResult.getPageRange().get(0), actualRecognizedReceipt.getRecognizedForm().getPageRange()); validatePageRangeData(documentResult.getPageRange().get(1), actualRecognizedReceipt.getRecognizedForm().getPageRange()); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceipt.getReceiptType().getType()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceipt.getReceiptType().getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceipt.getMerchantName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceipt.getMerchantPhoneNumber(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceipt.getMerchantAddress(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceipt.getTotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceipt.getSubtotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceipt.getTax(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceipt.getTransactionDate(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceipt.getTransactionTime(), readResults, includeTextDetails); validateReceiptItemsData(expectedReceiptFields.get("Items").getValueArray(), actualRecognizedReceipt.getReceiptItems(), readResults, includeTextDetails); }
class FormRecognizerClientTestBase extends TestBase { private static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; private static final String FORM_JPG = "Form_1.jpg"; private static final String INVOICE_PDF = "Invoice_6.pdf"; private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateReferenceElementsData(List<String> expectedElements, IterableStream<FormContent> actualFormContents, List<ReadResult> readResults) { if (expectedElements != null && actualFormContents != null) { List<FormContent> actualFormContentList = actualFormContents.stream().collect(Collectors.toList()); assertEquals(expectedElements.size(), actualFormContentList.size()); for (int i = 0; i < actualFormContentList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormContentList.get(i).getTextContentType().equals(TextContentType.LINE)) { FormLine actualFormLine = (FormLine) actualFormContentList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getFormWords()); } FormWord actualFormContent = (FormWord) actualFormContentList.get(i); assertEquals(expectedTextWord.getText(), actualFormContent.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormContent.getConfidence()); } else { assertEquals(1.0f, actualFormContent.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormContent.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, IterableStream<FormTable> actualFormTables, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTable> actualFormTable = actualFormTables.stream().collect(Collectors.toList()); assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeTextDetails); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, IterableStream<FormTableCell> actualTableCells, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTableCell> actualTableCellList = actualTableCells.stream().collect(Collectors.toList()); assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, IterableStream<FormLine> actualLines) { List<FormLine> actualLineList = actualLines.stream().collect(Collectors.toList()); assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getFormWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, IterableStream<FormWord> actualFormWords) { List<FormWord> actualFormWordList = actualFormWords.stream().collect(Collectors.toList()); assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, BoundingBox actualBoundingBox) { if (actualBoundingBox != null && actualBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField<?> actualFormField, List<ReadResult> readResults, boolean includeTextDetails) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } if (includeTextDetails && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueText().getTextContent(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getFieldValue()); break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getFieldValue()); break; case TIME: assertEquals(expectedFieldValue.getValueTime(), actualFormField.getFieldValue()); break; case STRING: assertEquals(expectedFieldValue.getValueString(), actualFormField.getFieldValue()); break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getFieldValue()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getFieldValue()); break; case OBJECT: case ARRAY: return; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, PageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getStartPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getEndPageNumber()); } private static void validateReceiptItemsData(List<FieldValue> expectedReceiptItemList, List<USReceiptItem> actualReceiptItems, List<ReadResult> readResults, boolean includeTextDetails) { List<USReceiptItem> actualReceiptItemList = new ArrayList<>(actualReceiptItems); assertEquals(expectedReceiptItemList.size(), actualReceiptItemList.size()); for (int i = 0; i < expectedReceiptItemList.size(); i++) { FieldValue expectedReceiptItem = expectedReceiptItemList.get(i); USReceiptItem actualReceiptItem = actualReceiptItemList.get(i); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.NAME.toString()), actualReceiptItem.getName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.QUANTITY.toString()), actualReceiptItem.getQuantity(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.TOTAL_PRICE.toString()), actualReceiptItem.getTotalPrice(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.PRICE.toString()), actualReceiptItem.getPrice(), readResults, includeTextDetails); } } @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateLayoutDataResults(IterableStream<FormPage> actualFormPages, boolean includeTextDetails) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); List<FormPage> actualFormPageList = actualFormPages.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); if (includeTextDetails) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeTextDetails); } } } void validateReceiptResultData(IterableStream<RecognizedReceipt> actualResult, boolean includeTextDetails) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<RecognizedReceipt> actualReceiptList = actualResult.stream().collect(Collectors.toList()); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedReceipt actualReceipt = actualReceiptList.get(i); assertEquals("en-US", actualReceipt.getReceiptLocale()); validateLabeledData(actualReceipt.getRecognizedForm(), includeTextDetails, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); } } void validateRecognizedResult(IterableStream<RecognizedForm> actualForms, boolean includeTextDetails, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); List<RecognizedForm> actualFormList = actualForms.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormList.size(); i++) { validateLayoutDataResults(actualFormList.get(i).getPages(), includeTextDetails); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeTextDetails, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeTextDetails, readResults, pageResults.get(i), pageResults); } } } void receiptSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)); } void receiptSourceUrlRunnerTextDetails(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG), true); } void receiptDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG))); } } void receiptDataRunnerTextDetails(BiConsumer<InputStream, Boolean> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes()), true); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)), true); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void layoutDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(FORM_JPG))); } } void layoutSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(FORM_JPG)); } void customFormDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("testData.png".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(INVOICE_PDF))); } } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, PageResult expectedPage, List<PageResult> pageResults) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); for (int i = 0; i < expectedPage.getKeyValuePairs().size(); i++) { final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i); final FormField<?> actualFormField = actualForm.getFields().get("field-" + i); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelText().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelText().getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelText().getTextContent(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueText().getTextContent(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueText().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getStartPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getEndPageNumber()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField<?> actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { assertEquals(expectedFieldValue.getPage(), actualFormField.getPageNumber()); if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeTextDetails); } }); } protected <T> T clientSetup(Function<HttpPipeline, T> clientBuilder) { AzureKeyCredential credential = null; if (!interceptorManager.isPlaybackMode()) { credential = new AzureKeyCredential(getApiKey()); } HttpClient httpClient; Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddDatePolicy()); HttpPolicyProviders.addBeforeRetryPolicies(policies); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isPlaybackMode()) { httpClient = interceptorManager.getPlaybackClient(); } else { httpClient = new NettyAsyncHttpClientBuilder().wiretap(true).build(); } policies.add(interceptorManager.getRecordPolicy()); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); T client; client = clientBuilder.apply(pipeline); return Objects.requireNonNull(client); } /** * Get the string of API key value based on the test running mode. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
class FormRecognizerClientTestBase extends TestBase { private static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; private static final String FORM_JPG = "Form_1.jpg"; private static final String INVOICE_PDF = "Invoice_6.pdf"; private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateReferenceElementsData(List<String> expectedElements, IterableStream<FormContent> actualFormContents, List<ReadResult> readResults) { if (expectedElements != null && actualFormContents != null) { List<FormContent> actualFormContentList = actualFormContents.stream().collect(Collectors.toList()); assertEquals(expectedElements.size(), actualFormContentList.size()); for (int i = 0; i < actualFormContentList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormContentList.get(i).getTextContentType().equals(TextContentType.LINE)) { FormLine actualFormLine = (FormLine) actualFormContentList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getFormWords()); } FormWord actualFormContent = (FormWord) actualFormContentList.get(i); assertEquals(expectedTextWord.getText(), actualFormContent.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormContent.getConfidence()); } else { assertEquals(1.0f, actualFormContent.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormContent.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, IterableStream<FormTable> actualFormTables, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTable> actualFormTable = actualFormTables.stream().collect(Collectors.toList()); assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeTextDetails); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, IterableStream<FormTableCell> actualTableCells, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTableCell> actualTableCellList = actualTableCells.stream().collect(Collectors.toList()); assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, IterableStream<FormLine> actualLines) { List<FormLine> actualLineList = actualLines.stream().collect(Collectors.toList()); assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getFormWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, IterableStream<FormWord> actualFormWords) { List<FormWord> actualFormWordList = actualFormWords.stream().collect(Collectors.toList()); assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, BoundingBox actualBoundingBox) { if (actualBoundingBox != null && actualBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField<?> actualFormField, List<ReadResult> readResults, boolean includeTextDetails) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } if (includeTextDetails && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueText().getTextContent(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getFieldValue()); break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getFieldValue()); break; case TIME: assertEquals(expectedFieldValue.getValueTime(), actualFormField.getFieldValue()); break; case STRING: assertEquals(expectedFieldValue.getValueString(), actualFormField.getFieldValue()); break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getFieldValue()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getFieldValue()); break; case OBJECT: case ARRAY: return; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, PageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getStartPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getEndPageNumber()); } private static void validateReceiptItemsData(List<FieldValue> expectedReceiptItemList, List<USReceiptItem> actualReceiptItems, List<ReadResult> readResults, boolean includeTextDetails) { List<USReceiptItem> actualReceiptItemList = new ArrayList<>(actualReceiptItems); assertEquals(expectedReceiptItemList.size(), actualReceiptItemList.size()); for (int i = 0; i < expectedReceiptItemList.size(); i++) { FieldValue expectedReceiptItem = expectedReceiptItemList.get(i); USReceiptItem actualReceiptItem = actualReceiptItemList.get(i); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.NAME.toString()), actualReceiptItem.getName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.QUANTITY.toString()), actualReceiptItem.getQuantity(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.TOTAL_PRICE.toString()), actualReceiptItem.getTotalPrice(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.PRICE.toString()), actualReceiptItem.getPrice(), readResults, includeTextDetails); } } @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateLayoutDataResults(IterableStream<FormPage> actualFormPages, boolean includeTextDetails) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); List<FormPage> actualFormPageList = actualFormPages.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); if (includeTextDetails) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeTextDetails); } } } void validateReceiptResultData(IterableStream<RecognizedReceipt> actualResult, boolean includeTextDetails) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<RecognizedReceipt> actualReceiptList = actualResult.stream().collect(Collectors.toList()); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedReceipt actualReceipt = actualReceiptList.get(i); assertEquals("en-US", actualReceipt.getReceiptLocale()); validateLabeledData(actualReceipt.getRecognizedForm(), includeTextDetails, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); } } void validateRecognizedResult(IterableStream<RecognizedForm> actualForms, boolean includeTextDetails, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); List<RecognizedForm> actualFormList = actualForms.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormList.size(); i++) { validateLayoutDataResults(actualFormList.get(i).getPages(), includeTextDetails); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeTextDetails, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeTextDetails, readResults, pageResults.get(i), pageResults); } } } void receiptSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)); } void receiptSourceUrlRunnerTextDetails(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG), true); } void receiptDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG))); } } void receiptDataRunnerTextDetails(BiConsumer<InputStream, Boolean> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes()), true); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)), true); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void layoutDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(FORM_JPG))); } } void layoutSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(FORM_JPG)); } void customFormDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("testData.png".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(INVOICE_PDF))); } } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, PageResult expectedPage, List<PageResult> pageResults) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); for (int i = 0; i < expectedPage.getKeyValuePairs().size(); i++) { final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i); final FormField<?> actualFormField = actualForm.getFields().get("field-" + i); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelText().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelText().getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelText().getTextContent(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueText().getTextContent(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueText().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getStartPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getEndPageNumber()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField<?> actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { assertEquals(expectedFieldValue.getPage(), actualFormField.getPageNumber()); if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeTextDetails); } }); } /** * Get the string of API key value based on the test running mode. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
does this mean we will create a new client every time before a test?
public void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> assertThrows(ErrorResponseException.class, () -> client.beginRecognizeContentFromUrl(invalidSourceUrl))); }
client = getFormRecognizerClient(httpClient, serviceVersion);
public void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> assertThrows(ErrorResponseException.class, () -> client.beginRecognizeContentFromUrl(invalidSourceUrl))); }
class FormRecognizerClientTest extends FormRecognizerClientTestBase { private FormRecognizerClient client; private FormRecognizerClient getFormRecognizerClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (getTestMode() != TestMode.PLAYBACK) { builder.addPolicy(interceptorManager.getRecordPolicy()) .credential(new AzureKeyCredential(getApiKey())); } return builder.buildClient(); } /** * Verifies receipt data for a document using source as file url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptSourceUrlRunner((sourceUrl) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); }); } /** * Verifies receipt data for a document using source as file url and include content when includeTextDetails is * true. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptSourceUrlRunnerTextDetails((sourceUrl, includeTextDetails) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, includeTextDetails, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), true); }); } /** * Verifies receipt data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(data, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_JPEG, false, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); }); } /** * Verifies an exception thrown for a document using null data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(RuntimeException.class, () -> client.beginRecognizeReceipts(null, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_JPEG, false, null)); } /** * Verifies receipt data for a document using source as input stream data. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(getContentDetectionFileData(RECEIPT_LOCAL_URL), RECEIPT_FILE_LENGTH, null, false, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); } /** * Verifies receipt data for a document using source as as input stream data and text content when * includeTextDetails is true. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptDataRunnerTextDetails((data, includeTextDetails) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(data, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_PNG, includeTextDetails, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), true); }); } /** * Verifies layout/content data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(data, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_PNG, null); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); }); } /** * Verifies an exception thrown for a document using null data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(data, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_PNG, null); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeContent(null, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_JPEG, null)); }); } /** * Verifies layout data for a document using source as input stream data. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(getContentDetectionFileData(LAYOUT_LOCAL_URL), LAYOUT_FILE_LENGTH, null, null); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutSourceUrlRunner(sourceUrl -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); }); } /** * Verifies that an exception is thrown for invalid source url for recognizing content information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils /** * Verifies that an exception is thrown for invalid training data source. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); ErrorResponseException httpResponseException = assertThrows( ErrorResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(INVALID_URL, createdModel.getModelId()).getFinalResult()); assertEquals(httpResponseException.getMessage(), (INVALID_SOURCE_URL_ERROR)); }); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(data, trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); })); } /** * Verifies an exception thrown for a document using null data value or null model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(null, syncPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null)); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(data, null, CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null)); }) ); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(getContentDetectionFileData(FORM_LOCAL_URL), trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, null, true, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingUnlabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(data, trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, false, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, false); })); } }
class FormRecognizerClientTest extends FormRecognizerClientTestBase { private FormRecognizerClient client; private FormRecognizerClient getFormRecognizerClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); AzureKeyCredential credential = (getTestMode() == TestMode.PLAYBACK) ? new AzureKeyCredential(INVALID_KEY) : new AzureKeyCredential(getApiKey()); builder.credential(credential); return builder.buildClient(); } /** * Verifies receipt data for a document using source as file url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptSourceUrlRunner((sourceUrl) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); }); } /** * Verifies receipt data for a document using source as file url and include content when includeTextDetails is * true. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptSourceUrlRunnerTextDetails((sourceUrl, includeTextDetails) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, includeTextDetails, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), true); }); } /** * Verifies receipt data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(data, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_JPEG, false, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); }); } /** * Verifies an exception thrown for a document using null data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(RuntimeException.class, () -> client.beginRecognizeReceipts(null, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_JPEG, false, null)); } /** * Verifies receipt data for a document using source as input stream data. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(getContentDetectionFileData(RECEIPT_LOCAL_URL), RECEIPT_FILE_LENGTH, null, false, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); } /** * Verifies receipt data for a document using source as as input stream data and text content when * includeTextDetails is true. */ /** * Verifies layout/content data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(data, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_PNG, null); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); }); } /** * Verifies an exception thrown for a document using null data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(data, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_PNG, null); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeContent(null, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_JPEG, null)); }); } /** * Verifies layout data for a document using source as input stream data. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(getContentDetectionFileData(LAYOUT_LOCAL_URL), LAYOUT_FILE_LENGTH, null, null); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutSourceUrlRunner(sourceUrl -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); }); } /** * Verifies that an exception is thrown for invalid source url for recognizing content information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils /** * Verifies that an exception is thrown for invalid training data source. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); ErrorResponseException httpResponseException = assertThrows( ErrorResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(INVALID_URL, createdModel.getModelId()).getFinalResult()); assertEquals(httpResponseException.getMessage(), (INVALID_SOURCE_URL_ERROR)); }); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(data, trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); })); } /** * Verifies an exception thrown for a document using null data value or null model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(null, syncPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null)); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(data, null, CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null)); }) ); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(getContentDetectionFileData(FORM_LOCAL_URL), trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, null, true, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingUnlabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(data, trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, false, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, false); })); } }
Yes, it is a cheap operation and parameterized tests can only set on method level instead of @beforeAll and @before
public void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> assertThrows(ErrorResponseException.class, () -> client.beginRecognizeContentFromUrl(invalidSourceUrl))); }
client = getFormRecognizerClient(httpClient, serviceVersion);
public void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); invalidSourceUrlRunner((invalidSourceUrl) -> assertThrows(ErrorResponseException.class, () -> client.beginRecognizeContentFromUrl(invalidSourceUrl))); }
class FormRecognizerClientTest extends FormRecognizerClientTestBase { private FormRecognizerClient client; private FormRecognizerClient getFormRecognizerClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion); if (getTestMode() != TestMode.PLAYBACK) { builder.addPolicy(interceptorManager.getRecordPolicy()) .credential(new AzureKeyCredential(getApiKey())); } return builder.buildClient(); } /** * Verifies receipt data for a document using source as file url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptSourceUrlRunner((sourceUrl) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); }); } /** * Verifies receipt data for a document using source as file url and include content when includeTextDetails is * true. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptSourceUrlRunnerTextDetails((sourceUrl, includeTextDetails) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, includeTextDetails, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), true); }); } /** * Verifies receipt data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(data, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_JPEG, false, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); }); } /** * Verifies an exception thrown for a document using null data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(RuntimeException.class, () -> client.beginRecognizeReceipts(null, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_JPEG, false, null)); } /** * Verifies receipt data for a document using source as input stream data. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(getContentDetectionFileData(RECEIPT_LOCAL_URL), RECEIPT_FILE_LENGTH, null, false, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); } /** * Verifies receipt data for a document using source as as input stream data and text content when * includeTextDetails is true. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptDataRunnerTextDetails((data, includeTextDetails) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(data, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_PNG, includeTextDetails, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), true); }); } /** * Verifies layout/content data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(data, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_PNG, null); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); }); } /** * Verifies an exception thrown for a document using null data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(data, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_PNG, null); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeContent(null, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_JPEG, null)); }); } /** * Verifies layout data for a document using source as input stream data. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(getContentDetectionFileData(LAYOUT_LOCAL_URL), LAYOUT_FILE_LENGTH, null, null); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutSourceUrlRunner(sourceUrl -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); }); } /** * Verifies that an exception is thrown for invalid source url for recognizing content information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils /** * Verifies that an exception is thrown for invalid training data source. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); ErrorResponseException httpResponseException = assertThrows( ErrorResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(INVALID_URL, createdModel.getModelId()).getFinalResult()); assertEquals(httpResponseException.getMessage(), (INVALID_SOURCE_URL_ERROR)); }); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(data, trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); })); } /** * Verifies an exception thrown for a document using null data value or null model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(null, syncPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null)); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(data, null, CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null)); }) ); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(getContentDetectionFileData(FORM_LOCAL_URL), trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, null, true, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingUnlabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(data, trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, false, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, false); })); } }
class FormRecognizerClientTest extends FormRecognizerClientTestBase { private FormRecognizerClient client; private FormRecognizerClient getFormRecognizerClient(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); AzureKeyCredential credential = (getTestMode() == TestMode.PLAYBACK) ? new AzureKeyCredential(INVALID_KEY) : new AzureKeyCredential(getApiKey()); builder.credential(credential); return builder.buildClient(); } /** * Verifies receipt data for a document using source as file url. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptSourceUrlRunner((sourceUrl) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); }); } /** * Verifies receipt data for a document using source as file url and include content when includeTextDetails is * true. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptSourceUrlRunnerTextDetails((sourceUrl, includeTextDetails) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceiptsFromUrl(sourceUrl, includeTextDetails, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), true); }); } /** * Verifies receipt data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); receiptDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(data, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_JPEG, false, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); }); } /** * Verifies an exception thrown for a document using null data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); assertThrows(RuntimeException.class, () -> client.beginRecognizeReceipts(null, RECEIPT_FILE_LENGTH, FormContentType.IMAGE_JPEG, false, null)); } /** * Verifies receipt data for a document using source as input stream data. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = client.beginRecognizeReceipts(getContentDetectionFileData(RECEIPT_LOCAL_URL), RECEIPT_FILE_LENGTH, null, false, null); syncPoller.waitForCompletion(); validateReceiptResultData(syncPoller.getFinalResult(), false); } /** * Verifies receipt data for a document using source as as input stream data and text content when * includeTextDetails is true. */ /** * Verifies layout/content data for a document using source as input stream data. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(data, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_PNG, null); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); }); } /** * Verifies an exception thrown for a document using null data value. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutDataRunner((data) -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(data, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_PNG, null); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeContent(null, LAYOUT_FILE_LENGTH, FormContentType.IMAGE_JPEG, null)); }); } /** * Verifies layout data for a document using source as input stream data. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContent(getContentDetectionFileData(LAYOUT_LOCAL_URL), LAYOUT_FILE_LENGTH, null, null); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); layoutSourceUrlRunner(sourceUrl -> { SyncPoller<OperationResult, IterableStream<FormPage>> syncPoller = client.beginRecognizeContentFromUrl(sourceUrl); syncPoller.waitForCompletion(); validateLayoutDataResults(syncPoller.getFinalResult(), false); }); } /** * Verifies that an exception is thrown for invalid source url for recognizing content information. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils /** * Verifies that an exception is thrown for invalid training data source. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); ErrorResponseException httpResponseException = assertThrows( ErrorResponseException.class, () -> client.beginRecognizeCustomFormsFromUrl(INVALID_URL, createdModel.getModelId()).getFinalResult()); assertEquals(httpResponseException.getMessage(), (INVALID_SOURCE_URL_ERROR)); }); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(data, trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); })); } /** * Verifies an exception thrown for a document using null data value or null model id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> syncPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); syncPoller.waitForCompletion(); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(null, syncPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null)); assertThrows(RuntimeException.class, () -> client.beginRecognizeCustomForms(data, null, CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, true, null)); }) ); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. * And the content type is not given. The content type will be auto detected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); beginTrainingLabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(getContentDetectionFileData(FORM_LOCAL_URL), trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, null, true, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), true, true); }); } /** * Verifies custom form data for a document using source as input stream data and valid labeled model Id. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.formrecognizer.TestUtils public void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); customFormDataRunner(data -> beginTrainingUnlabeledRunner((storageSASUrl, useLabelFile) -> { SyncPoller<OperationResult, CustomFormModel> trainingPoller = client.getFormTrainingClient().beginTraining(storageSASUrl, useLabelFile); trainingPoller.waitForCompletion(); SyncPoller<OperationResult, IterableStream<RecognizedForm>> syncPoller = client.beginRecognizeCustomForms(data, trainingPoller.getFinalResult().getModelId(), CUSTOM_FORM_FILE_LENGTH, FormContentType.APPLICATION_PDF, false, null); syncPoller.waitForCompletion(); validateRecognizedResult(syncPoller.getFinalResult(), false, false); })); } }
Will double check the indentation.
void validateUSReceiptData(USReceipt actualRecognizedReceipt, boolean includeTextDetails) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); final Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validatePageRangeData(documentResult.getPageRange().get(0), actualRecognizedReceipt.getRecognizedForm().getPageRange()); validatePageRangeData(documentResult.getPageRange().get(1), actualRecognizedReceipt.getRecognizedForm().getPageRange()); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceipt.getReceiptType().getType()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceipt.getReceiptType().getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceipt.getMerchantName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceipt.getMerchantPhoneNumber(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceipt.getMerchantAddress(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceipt.getTotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceipt.getSubtotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceipt.getTax(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceipt.getTransactionDate(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceipt.getTransactionTime(), readResults, includeTextDetails); validateReceiptItemsData(expectedReceiptFields.get("Items").getValueArray(), actualRecognizedReceipt.getReceiptItems(), readResults, includeTextDetails); }
validatePageRangeData(documentResult.getPageRange().get(0), actualRecognizedReceipt.getRecognizedForm().getPageRange());
void validateUSReceiptData(USReceipt actualRecognizedReceipt, boolean includeTextDetails) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); final Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validatePageRangeData(documentResult.getPageRange().get(0), actualRecognizedReceipt.getRecognizedForm().getPageRange()); validatePageRangeData(documentResult.getPageRange().get(1), actualRecognizedReceipt.getRecognizedForm().getPageRange()); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceipt.getReceiptType().getType()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceipt.getReceiptType().getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceipt.getMerchantName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceipt.getMerchantPhoneNumber(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceipt.getMerchantAddress(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceipt.getTotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceipt.getSubtotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceipt.getTax(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceipt.getTransactionDate(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceipt.getTransactionTime(), readResults, includeTextDetails); validateReceiptItemsData(expectedReceiptFields.get("Items").getValueArray(), actualRecognizedReceipt.getReceiptItems(), readResults, includeTextDetails); }
class FormRecognizerClientTestBase extends TestBase { private static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; private static final String FORM_JPG = "Form_1.jpg"; private static final String INVOICE_PDF = "Invoice_6.pdf"; private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateReferenceElementsData(List<String> expectedElements, IterableStream<FormContent> actualFormContents, List<ReadResult> readResults) { if (expectedElements != null && actualFormContents != null) { List<FormContent> actualFormContentList = actualFormContents.stream().collect(Collectors.toList()); assertEquals(expectedElements.size(), actualFormContentList.size()); for (int i = 0; i < actualFormContentList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormContentList.get(i).getTextContentType().equals(TextContentType.LINE)) { FormLine actualFormLine = (FormLine) actualFormContentList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getFormWords()); } FormWord actualFormContent = (FormWord) actualFormContentList.get(i); assertEquals(expectedTextWord.getText(), actualFormContent.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormContent.getConfidence()); } else { assertEquals(1.0f, actualFormContent.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormContent.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, IterableStream<FormTable> actualFormTables, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTable> actualFormTable = actualFormTables.stream().collect(Collectors.toList()); assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeTextDetails); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, IterableStream<FormTableCell> actualTableCells, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTableCell> actualTableCellList = actualTableCells.stream().collect(Collectors.toList()); assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, IterableStream<FormLine> actualLines) { List<FormLine> actualLineList = actualLines.stream().collect(Collectors.toList()); assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getFormWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, IterableStream<FormWord> actualFormWords) { List<FormWord> actualFormWordList = actualFormWords.stream().collect(Collectors.toList()); assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, BoundingBox actualBoundingBox) { if (actualBoundingBox != null && actualBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField<?> actualFormField, List<ReadResult> readResults, boolean includeTextDetails) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } if (includeTextDetails && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueText().getTextContent(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getFieldValue()); break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getFieldValue()); break; case TIME: assertEquals(expectedFieldValue.getValueTime(), actualFormField.getFieldValue()); break; case STRING: assertEquals(expectedFieldValue.getValueString(), actualFormField.getFieldValue()); break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getFieldValue()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getFieldValue()); break; case OBJECT: case ARRAY: return; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, PageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getStartPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getEndPageNumber()); } private static void validateReceiptItemsData(List<FieldValue> expectedReceiptItemList, List<USReceiptItem> actualReceiptItems, List<ReadResult> readResults, boolean includeTextDetails) { List<USReceiptItem> actualReceiptItemList = new ArrayList<>(actualReceiptItems); assertEquals(expectedReceiptItemList.size(), actualReceiptItemList.size()); for (int i = 0; i < expectedReceiptItemList.size(); i++) { FieldValue expectedReceiptItem = expectedReceiptItemList.get(i); USReceiptItem actualReceiptItem = actualReceiptItemList.get(i); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.NAME.toString()), actualReceiptItem.getName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.QUANTITY.toString()), actualReceiptItem.getQuantity(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.TOTAL_PRICE.toString()), actualReceiptItem.getTotalPrice(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.PRICE.toString()), actualReceiptItem.getPrice(), readResults, includeTextDetails); } } @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateLayoutDataResults(IterableStream<FormPage> actualFormPages, boolean includeTextDetails) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); List<FormPage> actualFormPageList = actualFormPages.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); if (includeTextDetails) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeTextDetails); } } } void validateReceiptResultData(IterableStream<RecognizedReceipt> actualResult, boolean includeTextDetails) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<RecognizedReceipt> actualReceiptList = actualResult.stream().collect(Collectors.toList()); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedReceipt actualReceipt = actualReceiptList.get(i); assertEquals("en-US", actualReceipt.getReceiptLocale()); validateLabeledData(actualReceipt.getRecognizedForm(), includeTextDetails, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); } } void validateRecognizedResult(IterableStream<RecognizedForm> actualForms, boolean includeTextDetails, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); List<RecognizedForm> actualFormList = actualForms.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormList.size(); i++) { validateLayoutDataResults(actualFormList.get(i).getPages(), includeTextDetails); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeTextDetails, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeTextDetails, readResults, pageResults.get(i), pageResults); } } } void receiptSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)); } void receiptSourceUrlRunnerTextDetails(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG), true); } void receiptDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG))); } } void receiptDataRunnerTextDetails(BiConsumer<InputStream, Boolean> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes()), true); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)), true); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void layoutDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(FORM_JPG))); } } void layoutSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(FORM_JPG)); } void customFormDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("testData.png".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(INVOICE_PDF))); } } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, PageResult expectedPage, List<PageResult> pageResults) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); for (int i = 0; i < expectedPage.getKeyValuePairs().size(); i++) { final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i); final FormField<?> actualFormField = actualForm.getFields().get("field-" + i); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelText().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelText().getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelText().getTextContent(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueText().getTextContent(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueText().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getStartPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getEndPageNumber()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField<?> actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { assertEquals(expectedFieldValue.getPage(), actualFormField.getPageNumber()); if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeTextDetails); } }); } protected <T> T clientSetup(Function<HttpPipeline, T> clientBuilder) { AzureKeyCredential credential = null; if (!interceptorManager.isPlaybackMode()) { credential = new AzureKeyCredential(getApiKey()); } HttpClient httpClient; Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddDatePolicy()); HttpPolicyProviders.addBeforeRetryPolicies(policies); if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isPlaybackMode()) { httpClient = interceptorManager.getPlaybackClient(); } else { httpClient = new NettyAsyncHttpClientBuilder().wiretap(true).build(); } policies.add(interceptorManager.getRecordPolicy()); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); T client; client = clientBuilder.apply(pipeline); return Objects.requireNonNull(client); } /** * Get the string of API key value based on the test running mode. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
class FormRecognizerClientTestBase extends TestBase { private static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; private static final String FORM_JPG = "Form_1.jpg"; private static final String INVOICE_PDF = "Invoice_6.pdf"; private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateReferenceElementsData(List<String> expectedElements, IterableStream<FormContent> actualFormContents, List<ReadResult> readResults) { if (expectedElements != null && actualFormContents != null) { List<FormContent> actualFormContentList = actualFormContents.stream().collect(Collectors.toList()); assertEquals(expectedElements.size(), actualFormContentList.size()); for (int i = 0; i < actualFormContentList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormContentList.get(i).getTextContentType().equals(TextContentType.LINE)) { FormLine actualFormLine = (FormLine) actualFormContentList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getFormWords()); } FormWord actualFormContent = (FormWord) actualFormContentList.get(i); assertEquals(expectedTextWord.getText(), actualFormContent.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormContent.getConfidence()); } else { assertEquals(1.0f, actualFormContent.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormContent.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, IterableStream<FormTable> actualFormTables, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTable> actualFormTable = actualFormTables.stream().collect(Collectors.toList()); assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeTextDetails); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, IterableStream<FormTableCell> actualTableCells, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTableCell> actualTableCellList = actualTableCells.stream().collect(Collectors.toList()); assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, IterableStream<FormLine> actualLines) { List<FormLine> actualLineList = actualLines.stream().collect(Collectors.toList()); assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getFormWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, IterableStream<FormWord> actualFormWords) { List<FormWord> actualFormWordList = actualFormWords.stream().collect(Collectors.toList()); assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, BoundingBox actualBoundingBox) { if (actualBoundingBox != null && actualBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField<?> actualFormField, List<ReadResult> readResults, boolean includeTextDetails) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } if (includeTextDetails && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueText().getTextContent(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getFieldValue()); break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getFieldValue()); break; case TIME: assertEquals(expectedFieldValue.getValueTime(), actualFormField.getFieldValue()); break; case STRING: assertEquals(expectedFieldValue.getValueString(), actualFormField.getFieldValue()); break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getFieldValue()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getFieldValue()); break; case OBJECT: case ARRAY: return; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, PageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getStartPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getEndPageNumber()); } private static void validateReceiptItemsData(List<FieldValue> expectedReceiptItemList, List<USReceiptItem> actualReceiptItems, List<ReadResult> readResults, boolean includeTextDetails) { List<USReceiptItem> actualReceiptItemList = new ArrayList<>(actualReceiptItems); assertEquals(expectedReceiptItemList.size(), actualReceiptItemList.size()); for (int i = 0; i < expectedReceiptItemList.size(); i++) { FieldValue expectedReceiptItem = expectedReceiptItemList.get(i); USReceiptItem actualReceiptItem = actualReceiptItemList.get(i); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.NAME.toString()), actualReceiptItem.getName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.QUANTITY.toString()), actualReceiptItem.getQuantity(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.TOTAL_PRICE.toString()), actualReceiptItem.getTotalPrice(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.PRICE.toString()), actualReceiptItem.getPrice(), readResults, includeTextDetails); } } @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateLayoutDataResults(IterableStream<FormPage> actualFormPages, boolean includeTextDetails) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); List<FormPage> actualFormPageList = actualFormPages.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); if (includeTextDetails) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeTextDetails); } } } void validateReceiptResultData(IterableStream<RecognizedReceipt> actualResult, boolean includeTextDetails) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<RecognizedReceipt> actualReceiptList = actualResult.stream().collect(Collectors.toList()); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedReceipt actualReceipt = actualReceiptList.get(i); assertEquals("en-US", actualReceipt.getReceiptLocale()); validateLabeledData(actualReceipt.getRecognizedForm(), includeTextDetails, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); } } void validateRecognizedResult(IterableStream<RecognizedForm> actualForms, boolean includeTextDetails, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); List<RecognizedForm> actualFormList = actualForms.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormList.size(); i++) { validateLayoutDataResults(actualFormList.get(i).getPages(), includeTextDetails); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeTextDetails, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeTextDetails, readResults, pageResults.get(i), pageResults); } } } void receiptSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)); } void receiptSourceUrlRunnerTextDetails(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG), true); } void receiptDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG))); } } void receiptDataRunnerTextDetails(BiConsumer<InputStream, Boolean> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes()), true); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)), true); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void layoutDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(FORM_JPG))); } } void layoutSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(FORM_JPG)); } void customFormDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("testData.png".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(INVOICE_PDF))); } } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, PageResult expectedPage, List<PageResult> pageResults) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); for (int i = 0; i < expectedPage.getKeyValuePairs().size(); i++) { final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i); final FormField<?> actualFormField = actualForm.getFields().get("field-" + i); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelText().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelText().getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelText().getTextContent(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueText().getTextContent(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueText().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getStartPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getEndPageNumber()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField<?> actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { assertEquals(expectedFieldValue.getPage(), actualFormField.getPageNumber()); if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeTextDetails); } }); } /** * Get the string of API key value based on the test running mode. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
indentation revert?
void validateUSReceiptData(USReceipt actualRecognizedReceipt, boolean includeTextDetails) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); final Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validatePageRangeData(documentResult.getPageRange().get(0), actualRecognizedReceipt.getRecognizedForm().getPageRange()); validatePageRangeData(documentResult.getPageRange().get(1), actualRecognizedReceipt.getRecognizedForm().getPageRange()); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceipt.getReceiptType().getType()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceipt.getReceiptType().getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceipt.getMerchantName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceipt.getMerchantPhoneNumber(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceipt.getMerchantAddress(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceipt.getTotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceipt.getSubtotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceipt.getTax(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceipt.getTransactionDate(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceipt.getTransactionTime(), readResults, includeTextDetails); validateReceiptItemsData(expectedReceiptFields.get("Items").getValueArray(), actualRecognizedReceipt.getReceiptItems(), readResults, includeTextDetails); }
validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceipt.getTax(), readResults,
void validateUSReceiptData(USReceipt actualRecognizedReceipt, boolean includeTextDetails) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); final Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validatePageRangeData(documentResult.getPageRange().get(0), actualRecognizedReceipt.getRecognizedForm().getPageRange()); validatePageRangeData(documentResult.getPageRange().get(1), actualRecognizedReceipt.getRecognizedForm().getPageRange()); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceipt.getReceiptType().getType()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceipt.getReceiptType().getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceipt.getMerchantName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceipt.getMerchantPhoneNumber(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceipt.getMerchantAddress(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceipt.getTotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceipt.getSubtotal(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceipt.getTax(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceipt.getTransactionDate(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceipt.getTransactionTime(), readResults, includeTextDetails); validateReceiptItemsData(expectedReceiptFields.get("Items").getValueArray(), actualRecognizedReceipt.getReceiptItems(), readResults, includeTextDetails); }
class FormRecognizerClientTestBase extends TestBase { private static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; private static final String FORM_JPG = "Form_1.jpg"; private static final String INVOICE_PDF = "Invoice_6.pdf"; private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateReferenceElementsData(List<String> expectedElements, IterableStream<FormContent> actualFormContents, List<ReadResult> readResults) { if (expectedElements != null && actualFormContents != null) { List<FormContent> actualFormContentList = actualFormContents.stream().collect(Collectors.toList()); assertEquals(expectedElements.size(), actualFormContentList.size()); for (int i = 0; i < actualFormContentList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormContentList.get(i).getTextContentType().equals(TextContentType.LINE)) { FormLine actualFormLine = (FormLine) actualFormContentList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getFormWords()); } FormWord actualFormContent = (FormWord) actualFormContentList.get(i); assertEquals(expectedTextWord.getText(), actualFormContent.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormContent.getConfidence()); } else { assertEquals(1.0f, actualFormContent.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormContent.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, IterableStream<FormTable> actualFormTables, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTable> actualFormTable = actualFormTables.stream().collect(Collectors.toList()); assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeTextDetails); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, IterableStream<FormTableCell> actualTableCells, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTableCell> actualTableCellList = actualTableCells.stream().collect(Collectors.toList()); assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, IterableStream<FormLine> actualLines) { List<FormLine> actualLineList = actualLines.stream().collect(Collectors.toList()); assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getFormWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, IterableStream<FormWord> actualFormWords) { List<FormWord> actualFormWordList = actualFormWords.stream().collect(Collectors.toList()); assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, BoundingBox actualBoundingBox) { if (actualBoundingBox != null && actualBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField<?> actualFormField, List<ReadResult> readResults, boolean includeTextDetails) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } if (includeTextDetails && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueText().getTextContent(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getFieldValue()); break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getFieldValue()); break; case TIME: assertEquals(expectedFieldValue.getValueTime(), actualFormField.getFieldValue()); break; case STRING: assertEquals(expectedFieldValue.getValueString(), actualFormField.getFieldValue()); break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getFieldValue()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getFieldValue()); break; case OBJECT: case ARRAY: return; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, PageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getStartPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getEndPageNumber()); } private static void validateReceiptItemsData(List<FieldValue> expectedReceiptItemList, List<USReceiptItem> actualReceiptItems, List<ReadResult> readResults, boolean includeTextDetails) { List<USReceiptItem> actualReceiptItemList = new ArrayList<>(actualReceiptItems); assertEquals(expectedReceiptItemList.size(), actualReceiptItemList.size()); for (int i = 0; i < expectedReceiptItemList.size(); i++) { FieldValue expectedReceiptItem = expectedReceiptItemList.get(i); USReceiptItem actualReceiptItem = actualReceiptItemList.get(i); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.NAME.toString()), actualReceiptItem.getName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.QUANTITY.toString()), actualReceiptItem.getQuantity(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.TOTAL_PRICE.toString()), actualReceiptItem.getTotalPrice(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.PRICE.toString()), actualReceiptItem.getPrice(), readResults, includeTextDetails); } } @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateLayoutDataResults(IterableStream<FormPage> actualFormPages, boolean includeTextDetails) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); List<FormPage> actualFormPageList = actualFormPages.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); if (includeTextDetails) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeTextDetails); } } } void validateReceiptResultData(IterableStream<RecognizedReceipt> actualResult, boolean includeTextDetails) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<RecognizedReceipt> actualReceiptList = actualResult.stream().collect(Collectors.toList()); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedReceipt actualReceipt = actualReceiptList.get(i); assertEquals("en-US", actualReceipt.getReceiptLocale()); validateLabeledData(actualReceipt.getRecognizedForm(), includeTextDetails, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); } } void validateRecognizedResult(IterableStream<RecognizedForm> actualForms, boolean includeTextDetails, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); List<RecognizedForm> actualFormList = actualForms.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormList.size(); i++) { validateLayoutDataResults(actualFormList.get(i).getPages(), includeTextDetails); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeTextDetails, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeTextDetails, readResults, pageResults.get(i), pageResults); } } } void receiptSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)); } void receiptSourceUrlRunnerTextDetails(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG), true); } void receiptDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG))); } } void receiptDataRunnerTextDetails(BiConsumer<InputStream, Boolean> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes()), true); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)), true); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void layoutDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(FORM_JPG))); } } void layoutSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(FORM_JPG)); } void customFormDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("testData.png".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(INVOICE_PDF))); } } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, PageResult expectedPage, List<PageResult> pageResults) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); for (int i = 0; i < expectedPage.getKeyValuePairs().size(); i++) { final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i); final FormField<?> actualFormField = actualForm.getFields().get("field-" + i); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelText().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelText().getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelText().getTextContent(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueText().getTextContent(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueText().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getStartPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getEndPageNumber()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField<?> actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { assertEquals(expectedFieldValue.getPage(), actualFormField.getPageNumber()); if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeTextDetails); } }); } /** * Get the string of API key value based on the test running mode. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
class FormRecognizerClientTestBase extends TestBase { private static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; private static final String FORM_JPG = "Form_1.jpg"; private static final String INVOICE_PDF = "Invoice_6.pdf"; private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private final HttpLogOptions httpLogOptions = new HttpLogOptions(); private final Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); private final String clientName = properties.getOrDefault(NAME, "UnknownName"); private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); private static void validateReferenceElementsData(List<String> expectedElements, IterableStream<FormContent> actualFormContents, List<ReadResult> readResults) { if (expectedElements != null && actualFormContents != null) { List<FormContent> actualFormContentList = actualFormContents.stream().collect(Collectors.toList()); assertEquals(expectedElements.size(), actualFormContentList.size()); for (int i = 0; i < actualFormContentList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormContentList.get(i).getTextContentType().equals(TextContentType.LINE)) { FormLine actualFormLine = (FormLine) actualFormContentList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getFormWords()); } FormWord actualFormContent = (FormWord) actualFormContentList.get(i); assertEquals(expectedTextWord.getText(), actualFormContent.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormContent.getConfidence()); } else { assertEquals(1.0f, actualFormContent.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormContent.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, IterableStream<FormTable> actualFormTables, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTable> actualFormTable = actualFormTables.stream().collect(Collectors.toList()); assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeTextDetails); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, IterableStream<FormTableCell> actualTableCells, List<ReadResult> readResults, boolean includeTextDetails) { List<FormTableCell> actualTableCellList = actualTableCells.stream().collect(Collectors.toList()); assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, IterableStream<FormLine> actualLines) { List<FormLine> actualLineList = actualLines.stream().collect(Collectors.toList()); assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getFormWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, IterableStream<FormWord> actualFormWords) { List<FormWord> actualFormWordList = actualFormWords.stream().collect(Collectors.toList()); assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, BoundingBox actualBoundingBox) { if (actualBoundingBox != null && actualBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField<?> actualFormField, List<ReadResult> readResults, boolean includeTextDetails) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } if (includeTextDetails && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueText().getTextContent(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getFieldValue()); break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getFieldValue()); break; case TIME: assertEquals(expectedFieldValue.getValueTime(), actualFormField.getFieldValue()); break; case STRING: assertEquals(expectedFieldValue.getValueString(), actualFormField.getFieldValue()); break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getFieldValue()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getFieldValue()); break; case OBJECT: case ARRAY: return; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, PageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getStartPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getEndPageNumber()); } private static void validateReceiptItemsData(List<FieldValue> expectedReceiptItemList, List<USReceiptItem> actualReceiptItems, List<ReadResult> readResults, boolean includeTextDetails) { List<USReceiptItem> actualReceiptItemList = new ArrayList<>(actualReceiptItems); assertEquals(expectedReceiptItemList.size(), actualReceiptItemList.size()); for (int i = 0; i < expectedReceiptItemList.size(); i++) { FieldValue expectedReceiptItem = expectedReceiptItemList.get(i); USReceiptItem actualReceiptItem = actualReceiptItemList.get(i); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.NAME.toString()), actualReceiptItem.getName(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.QUANTITY.toString()), actualReceiptItem.getQuantity(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.TOTAL_PRICE.toString()), actualReceiptItem.getTotalPrice(), readResults, includeTextDetails); validateFieldValueTransforms(expectedReceiptItem.getValueObject().get(ReceiptItemType.PRICE.toString()), actualReceiptItem.getPrice(), readResults, includeTextDetails); } } @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlTextDetails(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataTextDetailsWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeLayoutInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullValues(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateLayoutDataResults(IterableStream<FormPage> actualFormPages, boolean includeTextDetails) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); List<FormPage> actualFormPageList = actualFormPages.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); if (includeTextDetails) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeTextDetails); } } } void validateReceiptResultData(IterableStream<RecognizedReceipt> actualResult, boolean includeTextDetails) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<RecognizedReceipt> actualReceiptList = actualResult.stream().collect(Collectors.toList()); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedReceipt actualReceipt = actualReceiptList.get(i); assertEquals("en-US", actualReceipt.getReceiptLocale()); validateLabeledData(actualReceipt.getRecognizedForm(), includeTextDetails, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); } } void validateRecognizedResult(IterableStream<RecognizedForm> actualForms, boolean includeTextDetails, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); List<RecognizedForm> actualFormList = actualForms.stream().collect(Collectors.toList()); for (int i = 0; i < actualFormList.size(); i++) { validateLayoutDataResults(actualFormList.get(i).getPages(), includeTextDetails); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeTextDetails, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeTextDetails, readResults, pageResults.get(i), pageResults); } } } void receiptSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)); } void receiptSourceUrlRunnerTextDetails(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG), true); } void receiptDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG))); } } void receiptDataRunnerTextDetails(BiConsumer<InputStream, Boolean> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes()), true); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(RECEIPT_CONTOSO_JPG)), true); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void layoutDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("isPlaybackMode".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(FORM_JPG))); } } void layoutSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(FORM_JPG)); } void customFormDataRunner(Consumer<InputStream> testRunner) { if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream("testData.png".getBytes())); } else { testRunner.accept(getFileData(getStorageTestingFileUrl(INVOICE_PDF))); } } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, PageResult expectedPage, List<PageResult> pageResults) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); for (int i = 0; i < expectedPage.getKeyValuePairs().size(); i++) { final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i); final FormField<?> actualFormField = actualForm.getFields().get("field-" + i); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelText().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelText().getBoundingBox()); if (includeTextDetails) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelText().getTextContent(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueText().getTextContent(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueText().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueText().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeTextDetails, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getStartPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getEndPageNumber()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField<?> actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { assertEquals(expectedFieldValue.getPage(), actualFormField.getPageNumber()); if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeTextDetails); } }); } /** * Get the string of API key value based on the test running mode. * * @return the API key string */ String getApiKey() { return interceptorManager.isPlaybackMode() ? "apiKeyInPlayback" : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
What if we requested 100 events, only 30 showed up in the timeout period, and the next work item wants 10? This logic will add another 10 credits (making it 80 credits) even though we don't need to add more credits to the link.
private void drainQueue() { if (isTerminated()) { return; } currentWork = workQueue.poll(); if (currentWork == null) { return; } subscription.request(currentWork.getNumberOfEvents()); timeoutOperation = Mono.delay(currentWork.getTimeout()) .subscribe(l -> { if (!currentWork.isTerminal()) { completeCurrentWork(currentWork); } }); }
subscription.request(currentWork.getNumberOfEvents());
private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final long prefetch; private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final SynchronousReceiveWork initialWork; private volatile Subscription subscription; private SynchronousReceiveWork currentWork; private Disposable timeoutOperation; private Disposable drainQueueDisposable; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initWork) { this.prefetch = prefetch; this.initialWork = initWork; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", initialWork.getId(), initialWork.getNumberOfEvents(), initialWork.getTimeout()); queueWork(initialWork); } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { currentWork.next(message); if (currentWork.isTerminal()) { logger.info("[{}] Completed. Closing Flux and cancelling subscription.", currentWork.getId()); completeCurrentWork(currentWork); } } private void completeCurrentWork(SynchronousReceiveWork currentWork) { if (isTerminated()) { return; } currentWork.complete(); logger.verbose("[{}] work completed.", currentWork.getId()); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } if (drainQueueDisposable != null && !drainQueueDisposable.isDisposed()) { drainQueueDisposable.dispose(); } if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } if (workQueue.size() > 0) { drain(); } } void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); drain(); } private void drain() { if (!wip.compareAndSet(0, 1)) { return; } drainQueueDisposable = Mono.just(true) .subscribe(l -> { drainQueue(); }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); currentWork.error(throwable); dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } if (currentWork.getError() != null) { currentWork.error(currentWork.getError()); } else { currentWork.complete(); } subscription.cancel(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
Example: When there is only one receive(2) request and it time out. But we got two messages after that. During this time we also got request for another receive(2) . In this case we can use this buffer to send the messages and do not need to ask upstream.
protected void hookOnNext(ServiceBusReceivedMessageContext message) { if (currentWork == null) { bufferMessages.add(message); return; } currentWork.next(message); remaining.decrementAndGet(); if (currentWork.isTerminal()) { currentWork.complete(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } currentWork = workQueue.poll(); if (currentWork != null) { logger.verbose("[{}] Picking up next receive request.", currentWork.getId()); timeoutOperation = getTimeoutOperation(); requestCredits(currentWork.getNumberOfEvents()); } else { if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } } } }
bufferMessages.add(message);
protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final long prefetch; private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final SynchronousReceiveWork initialWork; private final AtomicLong remaining = new AtomicLong(); private volatile Subscription subscription; private SynchronousReceiveWork currentWork; private Disposable timeoutOperation; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.prefetch = prefetch; this.initialWork = initialWork; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; logger.info("[{}] onSubscribe Pending: {}, Scheduling receive timeout task '{}'.", initialWork.getId(), initialWork.getNumberOfEvents(), initialWork.getTimeout()); queueWork(initialWork); } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override /** * * @param requested credits for current {@link SynchronousReceiveWork}. */ private void requestCredits(long requested) { long creditToAdd = requested - remaining.get(); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); } else { logger.verbose("[{}] No need to request credit. ", currentWork.getId()); } } void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); drain(); } private void drain() { if (workQueue.size() == 0) { return; } if (!wip.compareAndSet(0, 1)) { return; } drainQueue(); } private void drainQueue() { if (isTerminated()) { return; } currentWork = workQueue.poll(); if (currentWork == null) { return; } long sentFromBuffer = 0; if (bufferMessages.size() > 0) { while (!bufferMessages.isEmpty() || sentFromBuffer < currentWork.getNumberOfEvents()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); ++sentFromBuffer; } if (sentFromBuffer == currentWork.getNumberOfEvents()) { currentWork.complete(); logger.verbose("[{}] Sent [{}] messages from buffer.", currentWork.getId(), sentFromBuffer); drainQueue(); } } timeoutOperation = getTimeoutOperation(); requestCredits(currentWork.getNumberOfEvents() - sentFromBuffer); } private Disposable getTimeoutOperation() { return Mono.delay(currentWork.getTimeout()) .subscribe(l -> { if (currentWork != null && !currentWork.isTerminal()) { logger.verbose("[{}] Timeout triggered.", currentWork.getId()); currentWork.complete(); } if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } drain(); }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); currentWork.error(throwable); dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } if (currentWork != null) { currentWork.complete(); } subscription.cancel(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } } /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
This can be verbose. It'll get noisy.
protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; logger.info("[{}] onSubscribe Pending: {}, Scheduling receive timeout task '{}'.", initialWork.getId(), initialWork.getNumberOfEvents(), initialWork.getTimeout()); queueWork(initialWork); }
logger.info("[{}] onSubscribe Pending: {}, Scheduling receive timeout task '{}'.", initialWork.getId(),
protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final long prefetch; private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final SynchronousReceiveWork initialWork; private final AtomicLong remaining = new AtomicLong(); private volatile Subscription subscription; private SynchronousReceiveWork currentWork; private Disposable timeoutOperation; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.prefetch = prefetch; this.initialWork = initialWork; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { if (currentWork == null) { bufferMessages.add(message); return; } currentWork.next(message); remaining.decrementAndGet(); if (currentWork.isTerminal()) { currentWork.complete(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } currentWork = workQueue.poll(); if (currentWork != null) { logger.verbose("[{}] Picking up next receive request.", currentWork.getId()); timeoutOperation = getTimeoutOperation(); requestCredits(currentWork.getNumberOfEvents()); } else { if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } } } } /** * * @param requested credits for current {@link SynchronousReceiveWork}. */ private void requestCredits(long requested) { long creditToAdd = requested - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); } else { logger.verbose("[{}] No need to request credit. ", currentWork.getId()); } } void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); drain(); } private void drain() { if (workQueue.size() == 0) { return; } if (!wip.compareAndSet(0, 1)) { return; } drainQueue(); } private void drainQueue() { if (isTerminated()) { return; } currentWork = workQueue.poll(); if (currentWork == null) { return; } long sentFromBuffer = 0; if (bufferMessages.size() > 0) { while (!bufferMessages.isEmpty() || sentFromBuffer < currentWork.getNumberOfEvents()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); ++sentFromBuffer; } if (sentFromBuffer == currentWork.getNumberOfEvents()) { currentWork.complete(); logger.verbose("[{}] Sent [{}] messages from buffer.", currentWork.getId(), sentFromBuffer); drainQueue(); } } timeoutOperation = getTimeoutOperation(); requestCredits(currentWork.getNumberOfEvents() - sentFromBuffer); } private Disposable getTimeoutOperation() { return Mono.delay(currentWork.getTimeout()) .subscribe(l -> { if (currentWork != null && !currentWork.isTerminal()) { logger.verbose("[{}] Timeout triggered.", currentWork.getId()); currentWork.complete(); } if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } drain(); }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); currentWork.error(throwable); dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } if (currentWork != null) { currentWork.complete(); } subscription.cancel(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } } /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
Space after `//`: `// Boundary....`
protected void hookOnNext(ServiceBusReceivedMessageContext message) { if (currentWork == null) { bufferMessages.add(message); return; } currentWork.next(message); remaining.decrementAndGet(); if (currentWork.isTerminal()) { currentWork.complete(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } currentWork = workQueue.poll(); if (currentWork != null) { logger.verbose("[{}] Picking up next receive request.", currentWork.getId()); timeoutOperation = getTimeoutOperation(); requestCredits(currentWork.getNumberOfEvents()); } else { if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } } } }
protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final long prefetch; private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final SynchronousReceiveWork initialWork; private final AtomicLong remaining = new AtomicLong(); private volatile Subscription subscription; private SynchronousReceiveWork currentWork; private Disposable timeoutOperation; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.prefetch = prefetch; this.initialWork = initialWork; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; logger.info("[{}] onSubscribe Pending: {}, Scheduling receive timeout task '{}'.", initialWork.getId(), initialWork.getNumberOfEvents(), initialWork.getTimeout()); queueWork(initialWork); } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override /** * * @param requested credits for current {@link SynchronousReceiveWork}. */ private void requestCredits(long requested) { long creditToAdd = requested - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); } else { logger.verbose("[{}] No need to request credit. ", currentWork.getId()); } } void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); drain(); } private void drain() { if (workQueue.size() == 0) { return; } if (!wip.compareAndSet(0, 1)) { return; } drainQueue(); } private void drainQueue() { if (isTerminated()) { return; } currentWork = workQueue.poll(); if (currentWork == null) { return; } long sentFromBuffer = 0; if (bufferMessages.size() > 0) { while (!bufferMessages.isEmpty() || sentFromBuffer < currentWork.getNumberOfEvents()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); ++sentFromBuffer; } if (sentFromBuffer == currentWork.getNumberOfEvents()) { currentWork.complete(); logger.verbose("[{}] Sent [{}] messages from buffer.", currentWork.getId(), sentFromBuffer); drainQueue(); } } timeoutOperation = getTimeoutOperation(); requestCredits(currentWork.getNumberOfEvents() - sentFromBuffer); } private Disposable getTimeoutOperation() { return Mono.delay(currentWork.getTimeout()) .subscribe(l -> { if (currentWork != null && !currentWork.isTerminal()) { logger.verbose("[{}] Timeout triggered.", currentWork.getId()); currentWork.complete(); } if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } drain(); }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); currentWork.error(throwable); dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } if (currentWork != null) { currentWork.complete(); } subscription.cancel(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } } /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
you never use the prefetch: ``` subscription.request(prefetch); ```
protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; logger.verbose("[{}] onSubscribe Pending: {}, Scheduling receive timeout task '{}'.", initialWork.getId(), initialWork.getNumberOfEvents(), initialWork.getTimeout()); queueWork(initialWork); }
protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final long prefetch; private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final SynchronousReceiveWork initialWork; private final AtomicLong remaining = new AtomicLong(); private volatile Subscription subscription; private SynchronousReceiveWork currentWork; private Disposable timeoutOperation; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.prefetch = prefetch; this.initialWork = initialWork; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override /** * * @return next work to process from queue. */ private SynchronousReceiveWork getNextWorkAndRequest() { SynchronousReceiveWork nextWork = workQueue.poll(); if (nextWork != null) { logger.verbose("[{}] Picking up next receive request.", nextWork.getId()); timeoutOperation = getTimeoutOperation(nextWork.getTimeout()); requestCredits(nextWork.getNumberOfEvents()); } return nextWork; } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { boolean delivered = false; if (currentWork == null) { currentWork = getNextWorkAndRequest(); logger.verbose("No current work, Picked up next receive request."); } if (currentWork != null) { currentWork.next(message); delivered = true; remaining.decrementAndGet(); if (currentWork.isTerminal()) { currentWork.complete(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } currentWork = getNextWorkAndRequest(); logger.verbose("Current work is terminal, Picked up next receive request."); } } if (currentWork == null) { if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } if (!delivered) { bufferMessages.add(message); } } } /** * * @param requested credits for current {@link SynchronousReceiveWork}. */ private void requestCredits(long requested) { long creditToAdd = requested - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); } } void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); drain(); } private void drain() { if (workQueue.size() == 0) { return; } if (!wip.compareAndSet(0, 1)) { return; } drainQueue(); } private void drainQueue() { if (isTerminated()) { return; } currentWork = workQueue.poll(); if (currentWork == null) { return; } long sentFromBuffer = 0; if (bufferMessages.size() > 0) { while (!bufferMessages.isEmpty() || sentFromBuffer < currentWork.getNumberOfEvents()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); ++sentFromBuffer; } if (sentFromBuffer == currentWork.getNumberOfEvents()) { currentWork.complete(); logger.verbose("[{}] Sent [{}] messages from buffer.", currentWork.getId(), sentFromBuffer); drainQueue(); } } timeoutOperation = getTimeoutOperation(currentWork.getTimeout()); requestCredits(currentWork.getNumberOfEvents() - sentFromBuffer); } private Disposable getTimeoutOperation(Duration timeout) { return Mono.delay(timeout) .subscribe(l -> { if (currentWork != null && !currentWork.isTerminal()) { currentWork.complete(); } currentWork = workQueue.poll(); }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); currentWork.error(throwable); dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } if (currentWork != null) { currentWork.complete(); } subscription.cancel(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } } /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
The comment I was trying to make about WIP is to use it **only** for if someone is clearing the queue and to control access to the `drainQueue` method. You also modify this value in `hookOnNext`, but never decrement it when we exit the `drainQueue` method. ```java private void drain() { // If someone is already in this loop, then we are already clearing the queue. if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } ```
private void drain() { if (workQueue.size() == 0) { return; } if (!wip.compareAndSet(0, 1)) { return; } drainQueue(); }
private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final long prefetch; private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final SynchronousReceiveWork initialWork; private final AtomicLong remaining = new AtomicLong(); private volatile Subscription subscription; private SynchronousReceiveWork currentWork; private Disposable timeoutOperation; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.prefetch = prefetch; this.initialWork = initialWork; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; logger.verbose("[{}] onSubscribe Pending: {}, Scheduling receive timeout task '{}'.", initialWork.getId(), initialWork.getNumberOfEvents(), initialWork.getTimeout()); queueWork(initialWork); } /** * * @return next work to process from queue. */ private SynchronousReceiveWork getNextWorkAndRequest() { SynchronousReceiveWork nextWork = workQueue.poll(); if (nextWork != null) { logger.verbose("[{}] Picking up next receive request.", nextWork.getId()); timeoutOperation = getTimeoutOperation(nextWork.getTimeout()); requestCredits(nextWork.getNumberOfEvents()); } return nextWork; } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { boolean delivered = false; if (currentWork == null) { currentWork = getNextWorkAndRequest(); logger.verbose("No current work, Picked up next receive request."); } if (currentWork != null) { currentWork.next(message); delivered = true; remaining.decrementAndGet(); if (currentWork.isTerminal()) { currentWork.complete(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } currentWork = getNextWorkAndRequest(); logger.verbose("Current work is terminal, Picked up next receive request."); } } if (currentWork == null) { if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } if (!delivered) { bufferMessages.add(message); } } } /** * * @param requested credits for current {@link SynchronousReceiveWork}. */ private void requestCredits(long requested) { long creditToAdd = requested - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); } } void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); drain(); } private void drainQueue() { if (isTerminated()) { return; } currentWork = workQueue.poll(); if (currentWork == null) { return; } long sentFromBuffer = 0; if (bufferMessages.size() > 0) { while (!bufferMessages.isEmpty() || sentFromBuffer < currentWork.getNumberOfEvents()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); ++sentFromBuffer; } if (sentFromBuffer == currentWork.getNumberOfEvents()) { currentWork.complete(); logger.verbose("[{}] Sent [{}] messages from buffer.", currentWork.getId(), sentFromBuffer); drainQueue(); } } timeoutOperation = getTimeoutOperation(currentWork.getTimeout()); requestCredits(currentWork.getNumberOfEvents() - sentFromBuffer); } private Disposable getTimeoutOperation(Duration timeout) { return Mono.delay(timeout) .subscribe(l -> { if (currentWork != null && !currentWork.isTerminal()) { currentWork.complete(); } currentWork = workQueue.poll(); }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); currentWork.error(throwable); dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } if (currentWork != null) { currentWork.complete(); } subscription.cancel(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ /*** * Drain the queue using a lock on current work in progress. */ private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } } /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
Do you need this variable? if the subscription != null, I'll assume there is an upstream. Also, if we call hookonSubscribe twice, it'll stomp over the previous subscription. We should guard against this by only setting it when it is null and erroring when someone wants to set it again. You'll see a setOnce in some of the reactor operations.
protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); }
this.subscription = subscription;
protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (currentTimeoutOperation == null || bufferMessages.size() > 0 )) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; continue; } if (currentTimeoutOperation == null) { currentTimeoutOperation = getTimeoutOperation(currentWork); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } } /** * @param work on which timeout thread need to start. * * @return */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } } /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
Is there any benefit to setting this to null again (and in a few places)? Once a subscription is disposed calling dispose again is a no-op.
private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (currentTimeoutOperation == null || bufferMessages.size() > 0 )) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; continue; } if (currentTimeoutOperation == null) { currentTimeoutOperation = getTimeoutOperation(currentWork); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } }
currentTimeoutOperation = null;
private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ /** * @param work on which timeout thread need to start. * * @return */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
Having a current work is always tied to a timeout operation. Checking currentWork != null should be enough.
private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (currentTimeoutOperation == null || bufferMessages.size() > 0 )) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; continue; } if (currentTimeoutOperation == null) { currentTimeoutOperation = getTimeoutOperation(currentWork); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } }
currentTimeoutOperation = null;
private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ /** * @param work on which timeout thread need to start. * * @return */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
We might pick currentWork more than one time from workQueue. `currentTimeoutOperation == null` will indicate that are we picking up first time. We do not need to process currentWork if is picked up second time and no bufferMessages to send to it. `while ((currentWork = workQueue.peek()) != null && (currentTimeoutOperation == null || bufferMessages.size() > 0 )) {` The timeout Operation is not removing currentWork from he queue, thus currentWork needs be picked up again, thus we need to threat this different and go in the loop and remove this timeout work. setting `currentTimeoutOperation = null` indicate this case also.
private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (currentTimeoutOperation == null || bufferMessages.size() > 0 )) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; continue; } if (currentTimeoutOperation == null) { currentTimeoutOperation = getTimeoutOperation(currentWork); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null & !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } }
currentTimeoutOperation = null;
private void drainQueue() { if (isTerminated()) { return; } synchronized (currentWorkLock) { if (currentWork != null && currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } while ((currentWork = workQueue.peek()) != null && (!currentWork.isProcessingStarted() || bufferMessages.size() > 0)) { if (currentWork.isTerminal()) { workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } continue; } if (!currentWork.isProcessingStarted()) { currentTimeoutOperation = getTimeoutOperation(currentWork); currentWork.startedProcessing(); } while (bufferMessages.size() > 0 && !currentWork.isTerminal()) { currentWork.next(bufferMessages.poll()); remaining.decrementAndGet(); } if (currentWork.isTerminal()) { if (currentWork.getError() == null) { currentWork.complete(); } workQueue.remove(currentWork); if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } logger.verbose("The work [{}] is complete.", currentWork.getId()); } else { long creditToAdd = currentWork.getRemaining() - (remaining.get() + bufferMessages.size()); if (creditToAdd > 0) { remaining.addAndGet(creditToAdd); subscription.request(creditToAdd); logger.verbose("Requesting [{}] from upstream for work [{}].", creditToAdd, currentWork.getId()); } } } } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ /** * @param work on which timeout thread need to start. * * @return */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } }
class SynchronousMessageSubscriber extends BaseSubscriber<ServiceBusReceivedMessageContext> { private final ClientLogger logger = new ClientLogger(SynchronousMessageSubscriber.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger wip = new AtomicInteger(); private final Queue<SynchronousReceiveWork> workQueue = new ConcurrentLinkedQueue<>(); private final Queue<ServiceBusReceivedMessageContext> bufferMessages = new ConcurrentLinkedQueue<>(); private final AtomicLong remaining = new AtomicLong(); private final long requested; private final Object currentWorkLock = new Object(); private Disposable currentTimeoutOperation; private SynchronousReceiveWork currentWork; private boolean subscriberInitialized; private volatile Subscription subscription; private static final AtomicReferenceFieldUpdater<SynchronousMessageSubscriber, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(SynchronousMessageSubscriber.class, Subscription.class, "subscription"); SynchronousMessageSubscriber(long prefetch, SynchronousReceiveWork initialWork) { this.workQueue.add(initialWork); requested = initialWork.getNumberOfEvents() > prefetch ? initialWork.getNumberOfEvents() : prefetch; } /** * On an initial subscription, will take the first work item, and request that amount of work for it. * @param subscription Subscription for upstream. */ @Override protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } } /** * Publishes the event to the current {@link SynchronousReceiveWork}. If that work item is complete, will dispose of * the subscriber. * @param message Event to publish. */ @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); } /** * Queue the work to be picked up by drain loop. * @param work to be queued. */ void queueWork(SynchronousReceiveWork work) { logger.info("[{}] Pending: {}, Scheduling receive timeout task '{}'.", work.getId(), work.getNumberOfEvents(), work.getTimeout()); workQueue.add(work); if (subscriberInitialized) { drain(); } } /** * Drain the work, only one thread can be in this loop at a time. */ private void drain() { if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { final int decremented = wip.decrementAndGet(); if (decremented != 0) { logger.warning("There should be 0, but was: {}", decremented); } } } /*** * Drain the queue using a lock on current work in progress. */ /** * @param work on which timeout thread need to start. * * @return {@link Disposable} for the timeout operation. */ private Disposable getTimeoutOperation(SynchronousReceiveWork work) { Duration timeout = work.getTimeout(); return Mono.delay(timeout).thenReturn(work) .subscribe(l -> { synchronized (currentWorkLock) { if (currentWork == work) { work.timeout(); } } }); } /** * {@inheritDoc} */ @Override protected void hookOnError(Throwable throwable) { logger.error("[{}] Errors occurred upstream", currentWork.getId(), throwable); synchronized (currentWorkLock) { currentWork.error(throwable); } dispose(); } @Override protected void hookOnCancel() { if (isDisposed.getAndSet(true)) { return; } synchronized (currentWorkLock) { if (currentWork != null) { currentWork.complete(); } if (currentTimeoutOperation != null && !currentTimeoutOperation.isDisposed()) { currentTimeoutOperation.dispose(); } currentTimeoutOperation = null; } subscription.cancel(); } private boolean isTerminated() { return isDisposed.get(); } int getWorkQueueSize() { return this.workQueue.size(); } long getRequested() { return this.requested; } boolean isSubscriberInitialized() { return this.subscriberInitialized; } }
yup, will address some of the name changes in another PR.
public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); }
public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTraining() { String trainingSetSource = "{training-set-SAS-URL}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient * with options */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix( "Invoice"); formTrainingAsyncClient.beginTraining(trainingSetSource, true, trainModelOptions, Duration.ofSeconds(5) ).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; formTrainingAsyncClient.beginTraining(trainingFilesUrl, useTrainingLabels).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient * with options */ public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix("Invoice"); formTrainingAsyncClient.beginTraining(trainingFilesUrl, true, trainModelOptions, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ }
Do these tests are always expected to run in Direct mode?
public void before_UniqueIndexTest() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .buildAsyncClient(); database = createDatabase(client, databaseId); }
.directMode(DirectConnectionConfig.getDefaultConfig())
public void before_UniqueIndexTest() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .buildAsyncClient(); database = createDatabase(client, databaseId); }
class UniqueIndexTest extends TestSuiteBase { protected static final int TIMEOUT = 30000; protected static final int SETUP_TIMEOUT = 20000; protected static final int SHUTDOWN_TIMEOUT = 20000; private final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncClient client; private CosmosAsyncDatabase database; private CosmosAsyncContainer collection; @Test(groups = { "long" }, timeOut = TIMEOUT) public void insertWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); excludedPath.setPath("/*"); indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); includedPath1.setPath("/name/?"); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); collectionDefinition.setIndexingPolicy(indexingPolicy); ObjectMapper om = new ObjectMapper(); JsonNode doc1 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", JsonNode.class); JsonNode doc2 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"playwright\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); JsonNode doc3 = om.readValue("{\"name\":\"حافظ شیرازی\",\"description\":\"poet\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); collection = database.createContainer(collectionDefinition).block().getContainer(); CosmosItemProperties properties = BridgeInternal.getProperties(collection.createItem(doc1).block()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemProperties itemSettings = BridgeInternal.getProperties( collection.readItem(properties.getId(), PartitionKey.NONE, options, CosmosItemProperties.class) .block()); assertThat(itemSettings.getId()).isEqualTo(doc1.get("id").textValue()); try { collection.createItem(doc1).block(); fail("Did not throw due to unique constraint (create)"); } catch (RuntimeException e) { assertThat(getDocumentClientException(e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } collection.createItem(doc2).block(); collection.createItem(doc3).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT * 1000) public void replaceAndDeleteWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); collection = database.createContainer(collectionDefinition).block().getContainer(); ObjectMapper om = new ObjectMapper(); ObjectNode doc1 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc3 = om.readValue("{\"name\":\"Rabindranath Tagore\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc2 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"mathematician\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); CosmosItemProperties doc1Inserted = BridgeInternal.getProperties(collection.createItem(doc1, new CosmosItemRequestOptions()).block()); BridgeInternal.getProperties(collection.replaceItem(doc1Inserted, doc1.get("id").asText(), PartitionKey.NONE, new CosmosItemRequestOptions()) .block()); CosmosItemProperties doc2Inserted = BridgeInternal.getProperties(collection .createItem(doc2, new CosmosItemRequestOptions()) .block()); CosmosItemProperties doc2Replacement = new CosmosItemProperties(ModelBridgeInternal.toJsonFromJsonSerializable(doc1Inserted)); doc2Replacement.setId( doc2Inserted.getId()); try { collection.replaceItem(doc2Replacement, doc2Inserted.getId(), PartitionKey.NONE, new CosmosItemRequestOptions()).block(); fail("Did not throw due to unique constraint"); } catch (RuntimeException ex) { assertThat(getDocumentClientException(ex).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } doc3.put("id", doc1Inserted.getId()); collection.replaceItem(doc3, doc1Inserted.getId(), PartitionKey.NONE).block(); collection.deleteItem(doc1Inserted.getId(), PartitionKey.NONE).block(); collection.createItem(doc1, new CosmosItemRequestOptions()).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT) public void uniqueKeySerializationDeserialization() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); excludedPath.setPath("/*"); indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); includedPath1.setPath("/name/?"); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); collectionDefinition.setIndexingPolicy(indexingPolicy); CosmosAsyncContainer createdCollection = database.createContainer(collectionDefinition).block().getContainer(); CosmosContainerProperties collection = createdCollection.read().block().getProperties(); assertThat(collection.getUniqueKeyPolicy()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()) .hasSameSizeAs(collectionDefinition.getUniqueKeyPolicy().getUniqueKeys()); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys() .stream().map(ui -> ui.getPaths()).collect(Collectors.toList())) .containsExactlyElementsOf( ImmutableList.of(ImmutableList.of("/name", "/description"))); } private CosmosClientException getDocumentClientException(RuntimeException e) { CosmosClientException dce = Utils.as(e, CosmosClientException.class); assertThat(dce).isNotNull(); return dce; } @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(database); safeClose(client); } }
class UniqueIndexTest extends TestSuiteBase { protected static final int TIMEOUT = 30000; protected static final int SETUP_TIMEOUT = 20000; protected static final int SHUTDOWN_TIMEOUT = 20000; private final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncClient client; private CosmosAsyncDatabase database; private CosmosAsyncContainer collection; @Test(groups = { "long" }, timeOut = TIMEOUT) public void insertWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); excludedPath.setPath("/*"); indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); includedPath1.setPath("/name/?"); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); collectionDefinition.setIndexingPolicy(indexingPolicy); ObjectMapper om = new ObjectMapper(); JsonNode doc1 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", JsonNode.class); JsonNode doc2 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"playwright\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); JsonNode doc3 = om.readValue("{\"name\":\"حافظ شیرازی\",\"description\":\"poet\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); collection = database.createContainer(collectionDefinition).block().getContainer(); CosmosItemProperties properties = BridgeInternal.getProperties(collection.createItem(doc1).block()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemProperties itemSettings = BridgeInternal.getProperties( collection.readItem(properties.getId(), PartitionKey.NONE, options, CosmosItemProperties.class) .block()); assertThat(itemSettings.getId()).isEqualTo(doc1.get("id").textValue()); try { collection.createItem(doc1).block(); fail("Did not throw due to unique constraint (create)"); } catch (RuntimeException e) { assertThat(getDocumentClientException(e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } collection.createItem(doc2).block(); collection.createItem(doc3).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT * 1000) public void replaceAndDeleteWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); collection = database.createContainer(collectionDefinition).block().getContainer(); ObjectMapper om = new ObjectMapper(); ObjectNode doc1 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc3 = om.readValue("{\"name\":\"Rabindranath Tagore\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc2 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"mathematician\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); CosmosItemProperties doc1Inserted = BridgeInternal.getProperties(collection.createItem(doc1, new CosmosItemRequestOptions()).block()); BridgeInternal.getProperties(collection.replaceItem(doc1Inserted, doc1.get("id").asText(), PartitionKey.NONE, new CosmosItemRequestOptions()) .block()); CosmosItemProperties doc2Inserted = BridgeInternal.getProperties(collection .createItem(doc2, new CosmosItemRequestOptions()) .block()); CosmosItemProperties doc2Replacement = new CosmosItemProperties(ModelBridgeInternal.toJsonFromJsonSerializable(doc1Inserted)); doc2Replacement.setId( doc2Inserted.getId()); try { collection.replaceItem(doc2Replacement, doc2Inserted.getId(), PartitionKey.NONE, new CosmosItemRequestOptions()).block(); fail("Did not throw due to unique constraint"); } catch (RuntimeException ex) { assertThat(getDocumentClientException(ex).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } doc3.put("id", doc1Inserted.getId()); collection.replaceItem(doc3, doc1Inserted.getId(), PartitionKey.NONE).block(); collection.deleteItem(doc1Inserted.getId(), PartitionKey.NONE).block(); collection.createItem(doc1, new CosmosItemRequestOptions()).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT) public void uniqueKeySerializationDeserialization() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); excludedPath.setPath("/*"); indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); includedPath1.setPath("/name/?"); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); collectionDefinition.setIndexingPolicy(indexingPolicy); CosmosAsyncContainer createdCollection = database.createContainer(collectionDefinition).block().getContainer(); CosmosContainerProperties collection = createdCollection.read().block().getProperties(); assertThat(collection.getUniqueKeyPolicy()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()) .hasSameSizeAs(collectionDefinition.getUniqueKeyPolicy().getUniqueKeys()); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys() .stream().map(ui -> ui.getPaths()).collect(Collectors.toList())) .containsExactlyElementsOf( ImmutableList.of(ImmutableList.of("/name", "/description"))); } private CosmosClientException getDocumentClientException(RuntimeException e) { CosmosClientException dce = Utils.as(e, CosmosClientException.class); assertThat(dce).isNotNull(); return dce; } @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(database); safeClose(client); } }
Yes, I have not changed the connection mode of the tests - they will run as it is as they were running earlier. Since earlier also, default was DIRECT mode.
public void before_UniqueIndexTest() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .buildAsyncClient(); database = createDatabase(client, databaseId); }
.directMode(DirectConnectionConfig.getDefaultConfig())
public void before_UniqueIndexTest() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .consistencyLevel(ConsistencyLevel.SESSION) .contentResponseOnWriteEnabled(true) .buildAsyncClient(); database = createDatabase(client, databaseId); }
class UniqueIndexTest extends TestSuiteBase { protected static final int TIMEOUT = 30000; protected static final int SETUP_TIMEOUT = 20000; protected static final int SHUTDOWN_TIMEOUT = 20000; private final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncClient client; private CosmosAsyncDatabase database; private CosmosAsyncContainer collection; @Test(groups = { "long" }, timeOut = TIMEOUT) public void insertWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); excludedPath.setPath("/*"); indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); includedPath1.setPath("/name/?"); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); collectionDefinition.setIndexingPolicy(indexingPolicy); ObjectMapper om = new ObjectMapper(); JsonNode doc1 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", JsonNode.class); JsonNode doc2 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"playwright\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); JsonNode doc3 = om.readValue("{\"name\":\"حافظ شیرازی\",\"description\":\"poet\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); collection = database.createContainer(collectionDefinition).block().getContainer(); CosmosItemProperties properties = BridgeInternal.getProperties(collection.createItem(doc1).block()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemProperties itemSettings = BridgeInternal.getProperties( collection.readItem(properties.getId(), PartitionKey.NONE, options, CosmosItemProperties.class) .block()); assertThat(itemSettings.getId()).isEqualTo(doc1.get("id").textValue()); try { collection.createItem(doc1).block(); fail("Did not throw due to unique constraint (create)"); } catch (RuntimeException e) { assertThat(getDocumentClientException(e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } collection.createItem(doc2).block(); collection.createItem(doc3).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT * 1000) public void replaceAndDeleteWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); collection = database.createContainer(collectionDefinition).block().getContainer(); ObjectMapper om = new ObjectMapper(); ObjectNode doc1 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc3 = om.readValue("{\"name\":\"Rabindranath Tagore\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc2 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"mathematician\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); CosmosItemProperties doc1Inserted = BridgeInternal.getProperties(collection.createItem(doc1, new CosmosItemRequestOptions()).block()); BridgeInternal.getProperties(collection.replaceItem(doc1Inserted, doc1.get("id").asText(), PartitionKey.NONE, new CosmosItemRequestOptions()) .block()); CosmosItemProperties doc2Inserted = BridgeInternal.getProperties(collection .createItem(doc2, new CosmosItemRequestOptions()) .block()); CosmosItemProperties doc2Replacement = new CosmosItemProperties(ModelBridgeInternal.toJsonFromJsonSerializable(doc1Inserted)); doc2Replacement.setId( doc2Inserted.getId()); try { collection.replaceItem(doc2Replacement, doc2Inserted.getId(), PartitionKey.NONE, new CosmosItemRequestOptions()).block(); fail("Did not throw due to unique constraint"); } catch (RuntimeException ex) { assertThat(getDocumentClientException(ex).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } doc3.put("id", doc1Inserted.getId()); collection.replaceItem(doc3, doc1Inserted.getId(), PartitionKey.NONE).block(); collection.deleteItem(doc1Inserted.getId(), PartitionKey.NONE).block(); collection.createItem(doc1, new CosmosItemRequestOptions()).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT) public void uniqueKeySerializationDeserialization() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); excludedPath.setPath("/*"); indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); includedPath1.setPath("/name/?"); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); collectionDefinition.setIndexingPolicy(indexingPolicy); CosmosAsyncContainer createdCollection = database.createContainer(collectionDefinition).block().getContainer(); CosmosContainerProperties collection = createdCollection.read().block().getProperties(); assertThat(collection.getUniqueKeyPolicy()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()) .hasSameSizeAs(collectionDefinition.getUniqueKeyPolicy().getUniqueKeys()); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys() .stream().map(ui -> ui.getPaths()).collect(Collectors.toList())) .containsExactlyElementsOf( ImmutableList.of(ImmutableList.of("/name", "/description"))); } private CosmosClientException getDocumentClientException(RuntimeException e) { CosmosClientException dce = Utils.as(e, CosmosClientException.class); assertThat(dce).isNotNull(); return dce; } @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(database); safeClose(client); } }
class UniqueIndexTest extends TestSuiteBase { protected static final int TIMEOUT = 30000; protected static final int SETUP_TIMEOUT = 20000; protected static final int SHUTDOWN_TIMEOUT = 20000; private final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncClient client; private CosmosAsyncDatabase database; private CosmosAsyncContainer collection; @Test(groups = { "long" }, timeOut = TIMEOUT) public void insertWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); excludedPath.setPath("/*"); indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); includedPath1.setPath("/name/?"); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); collectionDefinition.setIndexingPolicy(indexingPolicy); ObjectMapper om = new ObjectMapper(); JsonNode doc1 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", JsonNode.class); JsonNode doc2 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"playwright\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); JsonNode doc3 = om.readValue("{\"name\":\"حافظ شیرازی\",\"description\":\"poet\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); collection = database.createContainer(collectionDefinition).block().getContainer(); CosmosItemProperties properties = BridgeInternal.getProperties(collection.createItem(doc1).block()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemProperties itemSettings = BridgeInternal.getProperties( collection.readItem(properties.getId(), PartitionKey.NONE, options, CosmosItemProperties.class) .block()); assertThat(itemSettings.getId()).isEqualTo(doc1.get("id").textValue()); try { collection.createItem(doc1).block(); fail("Did not throw due to unique constraint (create)"); } catch (RuntimeException e) { assertThat(getDocumentClientException(e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } collection.createItem(doc2).block(); collection.createItem(doc3).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT * 1000) public void replaceAndDeleteWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); collection = database.createContainer(collectionDefinition).block().getContainer(); ObjectMapper om = new ObjectMapper(); ObjectNode doc1 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc3 = om.readValue("{\"name\":\"Rabindranath Tagore\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc2 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"mathematician\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); CosmosItemProperties doc1Inserted = BridgeInternal.getProperties(collection.createItem(doc1, new CosmosItemRequestOptions()).block()); BridgeInternal.getProperties(collection.replaceItem(doc1Inserted, doc1.get("id").asText(), PartitionKey.NONE, new CosmosItemRequestOptions()) .block()); CosmosItemProperties doc2Inserted = BridgeInternal.getProperties(collection .createItem(doc2, new CosmosItemRequestOptions()) .block()); CosmosItemProperties doc2Replacement = new CosmosItemProperties(ModelBridgeInternal.toJsonFromJsonSerializable(doc1Inserted)); doc2Replacement.setId( doc2Inserted.getId()); try { collection.replaceItem(doc2Replacement, doc2Inserted.getId(), PartitionKey.NONE, new CosmosItemRequestOptions()).block(); fail("Did not throw due to unique constraint"); } catch (RuntimeException ex) { assertThat(getDocumentClientException(ex).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } doc3.put("id", doc1Inserted.getId()); collection.replaceItem(doc3, doc1Inserted.getId(), PartitionKey.NONE).block(); collection.deleteItem(doc1Inserted.getId(), PartitionKey.NONE).block(); collection.createItem(doc1, new CosmosItemRequestOptions()).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT) public void uniqueKeySerializationDeserialization() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); indexingPolicy.setIndexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); excludedPath.setPath("/*"); indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); includedPath1.setPath("/name/?"); includedPath1.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(Index.hash(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); collectionDefinition.setIndexingPolicy(indexingPolicy); CosmosAsyncContainer createdCollection = database.createContainer(collectionDefinition).block().getContainer(); CosmosContainerProperties collection = createdCollection.read().block().getProperties(); assertThat(collection.getUniqueKeyPolicy()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()) .hasSameSizeAs(collectionDefinition.getUniqueKeyPolicy().getUniqueKeys()); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys() .stream().map(ui -> ui.getPaths()).collect(Collectors.toList())) .containsExactlyElementsOf( ImmutableList.of(ImmutableList.of("/name", "/description"))); } private CosmosClientException getDocumentClientException(RuntimeException e) { CosmosClientException dce = Utils.as(e, CosmosClientException.class); assertThat(dce).isNotNull(); return dce; } @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(database); safeClose(client); } }
don't return a singleton object otherwise, changing it once for one client may affect other clients too. ```suggestion return new GatewayConnectionConfig() ```
public static GatewayConnectionConfig getDefaultConfig() { return GatewayConnectionConfig.defaultConfig; }
return GatewayConnectionConfig.defaultConfig;
public static GatewayConnectionConfig getDefaultConfig() { return new GatewayConnectionConfig(); }
class GatewayConnectionConfig { private static final GatewayConnectionConfig defaultConfig = new GatewayConnectionConfig(); private Duration requestTimeout; private int maxPoolSize; private Duration idleConnectionTimeout; private InetSocketAddress inetSocketProxyAddress; /** * Constructor. */ public GatewayConnectionConfig() { this.idleConnectionTimeout = DEFAULT_IDLE_CONNECTION_TIMEOUT; this.maxPoolSize = DEFAULT_MAX_POOL_SIZE; this.requestTimeout = DEFAULT_REQUEST_TIMEOUT; } /** * Gets the default Gateway connection configuration. * * @return the default gateway connection configuration. */ /** * Gets the request timeout (time to wait for response from network peer). * * @return the request timeout duration. */ public Duration getRequestTimeout() { return this.requestTimeout; } /** * Sets the request timeout (time to wait for response from network peer). * The default is 60 seconds. * * @param requestTimeout the request timeout duration. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setRequestTimeout(Duration requestTimeout) { this.requestTimeout = requestTimeout; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxPoolSize() { return this.maxPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxPoolSize The value of the connection pool size. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; return this; } /** * Gets the value of the timeout for an idle connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleConnectionTimeout() { return this.idleConnectionTimeout; } /** * sets the value of the timeout for an idle connection. After that time, * the connection will be automatically closed. * * @param idleConnectionTimeout the duration for an idle connection. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the InetSocketAddress of proxy server. * * @return the value of proxyHost. */ public InetSocketAddress getProxy() { return this.inetSocketProxyAddress; } /** * This will create the InetSocketAddress for proxy server, * all the requests to cosmoDB will route from this address. * * @param proxy The proxy server. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setProxy(InetSocketAddress proxy) { this.inetSocketProxyAddress = proxy; return this; } @Override public String toString() { return "GatewayConnectionConfig{" + "requestTimeout=" + requestTimeout + ", maxPoolSize=" + maxPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", inetSocketProxyAddress=" + inetSocketProxyAddress + '}'; } }
class GatewayConnectionConfig { private static final Duration DEFAULT_REQUEST_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final int DEFAULT_MAX_POOL_SIZE = 1000; private Duration requestTimeout; private int maxConnectionPoolSize; private Duration idleConnectionTimeout; private InetSocketAddress inetSocketProxyAddress; /** * Constructor. */ public GatewayConnectionConfig() { this.idleConnectionTimeout = DEFAULT_IDLE_CONNECTION_TIMEOUT; this.maxConnectionPoolSize = DEFAULT_MAX_POOL_SIZE; this.requestTimeout = DEFAULT_REQUEST_TIMEOUT; } /** * Gets the default Gateway connection configuration. * * @return the default gateway connection configuration. */ /** * Gets the request timeout (time to wait for response from network peer). * * @return the request timeout duration. */ public Duration getRequestTimeout() { return this.requestTimeout; } /** * Sets the request timeout (time to wait for response from network peer). * The default is 60 seconds. * * @param requestTimeout the request timeout duration. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setRequestTimeout(Duration requestTimeout) { this.requestTimeout = requestTimeout; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleConnectionTimeout() { return this.idleConnectionTimeout; } /** * sets the value of the timeout for an idle connection. After that time, * the connection will be automatically closed. * * @param idleConnectionTimeout the duration for an idle connection. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the InetSocketAddress of proxy server. * * @return the value of proxyHost. */ public InetSocketAddress getProxy() { return this.inetSocketProxyAddress; } /** * This will create the InetSocketAddress for proxy server, * all the requests to cosmoDB will route from this address. * * @param proxy The proxy server. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setProxy(InetSocketAddress proxy) { this.inetSocketProxyAddress = proxy; return this; } @Override public String toString() { return "GatewayConnectionConfig{" + "requestTimeout=" + requestTimeout + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", inetSocketProxyAddress=" + inetSocketProxyAddress + '}'; } }
don't return a static singleton instance otherwise changing the default for one client may affect the other client defaults too. ```suggestion return new DirectConnectoinConfig() ```
public static DirectConnectionConfig getDefaultConfig() { return DirectConnectionConfig.defaultConfig; }
return DirectConnectionConfig.defaultConfig;
public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_CHANNEL_TIMEOUT = Duration.ZERO; private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final int DEFAULT_MAX_CHANNELS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_ENDPOINT = 10; private static final DirectConnectionConfig defaultConfig = new DirectConnectionConfig(); private Duration connectionTimeout; private Duration idleChannelTimeout; private Duration idleEndpointTimeout; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; /** * Constructor. */ public DirectConnectionConfig() { this.connectionTimeout = null; this.idleChannelTimeout = DEFAULT_IDLE_CHANNEL_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxChannelsPerEndpoint = DEFAULT_MAX_CHANNELS_PER_ENDPOINT; this.maxRequestsPerChannel = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; } /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ /** * Gets the direct connection timeout * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the direct connection timeout * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle channel timeout * @return idle channel timeout */ public Duration getIdleChannelTimeout() { return idleChannelTimeout; } /** * Sets the idle channel timeout * @param idleChannelTimeout idle channel timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleChannelTimeout(Duration idleChannelTimeout) { this.idleChannelTimeout = idleChannelTimeout; return this; } /** * Gets the idle endpoint timeout * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max channels per endpoint * @return the max channels per endpoint */ public int getMaxChannelsPerEndpoint() { return maxChannelsPerEndpoint; } /** * Sets the max channels per endpoint * @param maxChannelsPerEndpoint the max channels per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxChannelsPerEndpoint(int maxChannelsPerEndpoint) { this.maxChannelsPerEndpoint = maxChannelsPerEndpoint; return this; } /** * Gets the max requests per endpoint * @return the max requests per endpoint */ public int getMaxRequestsPerChannel() { return maxRequestsPerChannel; } /** * Sets the max requests per endpoint * @param maxRequestsPerChannel the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerChannel(int maxRequestsPerChannel) { this.maxRequestsPerChannel = maxRequestsPerChannel; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleChannelTimeout=" + idleChannelTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxChannelsPerEndpoint=" + maxChannelsPerEndpoint + ", maxRequestsPerChannel=" + maxRequestsPerChannel + '}'; } }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_CHANNEL_TIMEOUT = Duration.ZERO; private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final int DEFAULT_MAX_CHANNELS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_ENDPOINT = 10; private Duration connectionTimeout; private Duration idleChannelTimeout; private Duration idleEndpointTimeout; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; /** * Constructor. */ public DirectConnectionConfig() { this.connectionTimeout = null; this.idleChannelTimeout = DEFAULT_IDLE_CHANNEL_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxChannelsPerEndpoint = DEFAULT_MAX_CHANNELS_PER_ENDPOINT; this.maxRequestsPerChannel = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; } /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ /** * Gets the direct connection timeout * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the direct connection timeout * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle channel timeout * @return idle channel timeout */ public Duration getIdleChannelTimeout() { return idleChannelTimeout; } /** * Sets the idle channel timeout * @param idleChannelTimeout idle channel timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleChannelTimeout(Duration idleChannelTimeout) { this.idleChannelTimeout = idleChannelTimeout; return this; } /** * Gets the idle endpoint timeout * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max channels per endpoint * @return the max channels per endpoint */ public int getMaxChannelsPerEndpoint() { return maxChannelsPerEndpoint; } /** * Sets the max channels per endpoint * @param maxChannelsPerEndpoint the max channels per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxChannelsPerEndpoint(int maxChannelsPerEndpoint) { this.maxChannelsPerEndpoint = maxChannelsPerEndpoint; return this; } /** * Gets the max requests per endpoint * @return the max requests per endpoint */ public int getMaxRequestsPerChannel() { return maxRequestsPerChannel; } /** * Sets the max requests per endpoint * @param maxRequestsPerChannel the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerChannel(int maxRequestsPerChannel) { this.maxRequestsPerChannel = maxRequestsPerChannel; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleChannelTimeout=" + idleChannelTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxChannelsPerEndpoint=" + maxChannelsPerEndpoint + ", maxRequestsPerChannel=" + maxRequestsPerChannel + '}'; } }
```suggestion endpointDiscoveryEnabled ```
public static CosmosClientBuilder cloneCosmosClientBuilder(CosmosClientBuilder builder) { CosmosClientBuilder copy = new CosmosClientBuilder(); copy.endpoint(builder.getEndpoint()) .key(builder.getKey()) .directMode(builder.getDirectConnectionConfig()) .gatewayMode(builder.getGatewayConnectionConfig()) .consistencyLevel(builder.getConsistencyLevel()) .keyCredential(builder.getKeyCredential()) .permissions(builder.getPermissions()) .authorizationTokenResolver(builder.getAuthorizationTokenResolver()) .resourceToken(builder.getResourceToken()) .contentResponseOnWriteEnabled(builder.isContentResponseOnWriteEnabled()) .userAgentSuffix(builder.getUserAgentSuffix()) .throttlingRetryOptions(builder.getThrottlingRetryOptions()) .preferredRegions(builder.getPreferredRegions()) .endpointDiscoverEnabled(builder.isEndpointDiscoveryEnabled()) .multipleWriteRegionsEnabled(builder.isMultipleWriteRegionsEnabled()) .readRequestsFallbackEnabled(builder.isReadRequestsFallbackEnabled()); return copy; }
.endpointDiscoverEnabled(builder.isEndpointDiscoveryEnabled())
public static CosmosClientBuilder cloneCosmosClientBuilder(CosmosClientBuilder builder) { CosmosClientBuilder copy = new CosmosClientBuilder(); copy.endpoint(builder.getEndpoint()) .key(builder.getKey()) .directMode(builder.getDirectConnectionConfig()) .gatewayMode(builder.getGatewayConnectionConfig()) .consistencyLevel(builder.getConsistencyLevel()) .keyCredential(builder.getKeyCredential()) .permissions(builder.getPermissions()) .authorizationTokenResolver(builder.getAuthorizationTokenResolver()) .resourceToken(builder.getResourceToken()) .contentResponseOnWriteEnabled(builder.isContentResponseOnWriteEnabled()) .userAgentSuffix(builder.getUserAgentSuffix()) .throttlingRetryOptions(builder.getThrottlingRetryOptions()) .preferredRegions(builder.getPreferredRegions()) .endpointDiscoveryEnabled(builder.isEndpointDiscoveryEnabled()) .multipleWriteRegionsEnabled(builder.isMultipleWriteRegionsEnabled()) .readRequestsFallbackEnabled(builder.isReadRequestsFallbackEnabled()); return copy; }
class CosmosBridgeInternal { public static AsyncDocumentClient getAsyncDocumentClient(CosmosClient client) { return client.asyncClient().getDocClientWrapper(); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosAsyncClient client) { return client.getDocClientWrapper(); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosAsyncDatabase cosmosAsyncDatabase) { return cosmosAsyncDatabase.getDocClientWrapper(); } public static CosmosAsyncDatabase getCosmosDatabaseWithNewClient(CosmosAsyncDatabase cosmosDatabase, CosmosAsyncClient client) { return new CosmosAsyncDatabase(cosmosDatabase.getId(), client); } public static CosmosAsyncContainer getCosmosContainerWithNewClient(CosmosAsyncContainer cosmosContainer, CosmosAsyncDatabase cosmosDatabase, CosmosAsyncClient client) { return new CosmosAsyncContainer(cosmosContainer.getId(), CosmosBridgeInternal.getCosmosDatabaseWithNewClient(cosmosDatabase, client)); } public static AsyncDocumentClient getContextClient(CosmosAsyncDatabase database) { return database.getClient().getContextClient(); } public static AsyncDocumentClient getContextClient(CosmosAsyncContainer container) { return container.getDatabase().getClient().getContextClient(); } public static CosmosAsyncContainer getCosmosAsyncContainer(CosmosContainer container) { return container.asyncContainer; } public static ConsistencyLevel getConsistencyLevel(CosmosClientBuilder cosmosClientBuilder) { return cosmosClientBuilder.getConsistencyLevel(); } public static ConnectionPolicy getConnectionPolicy(CosmosClientBuilder cosmosClientBuilder) { return cosmosClientBuilder.getConnectionPolicy(); } }
class CosmosBridgeInternal { public static AsyncDocumentClient getAsyncDocumentClient(CosmosClient client) { return client.asyncClient().getDocClientWrapper(); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosAsyncClient client) { return client.getDocClientWrapper(); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosAsyncDatabase cosmosAsyncDatabase) { return cosmosAsyncDatabase.getDocClientWrapper(); } public static CosmosAsyncDatabase getCosmosDatabaseWithNewClient(CosmosAsyncDatabase cosmosDatabase, CosmosAsyncClient client) { return new CosmosAsyncDatabase(cosmosDatabase.getId(), client); } public static CosmosAsyncContainer getCosmosContainerWithNewClient(CosmosAsyncContainer cosmosContainer, CosmosAsyncDatabase cosmosDatabase, CosmosAsyncClient client) { return new CosmosAsyncContainer(cosmosContainer.getId(), CosmosBridgeInternal.getCosmosDatabaseWithNewClient(cosmosDatabase, client)); } public static AsyncDocumentClient getContextClient(CosmosAsyncDatabase database) { return database.getClient().getContextClient(); } public static AsyncDocumentClient getContextClient(CosmosAsyncContainer container) { return container.getDatabase().getClient().getContextClient(); } public static CosmosAsyncContainer getCosmosAsyncContainer(CosmosContainer container) { return container.asyncContainer; } public static ConsistencyLevel getConsistencyLevel(CosmosClientBuilder cosmosClientBuilder) { return cosmosClientBuilder.getConsistencyLevel(); } public static ConnectionPolicy getConnectionPolicy(CosmosClientBuilder cosmosClientBuilder) { return cosmosClientBuilder.getConnectionPolicy(); } }
Yes, makes sense.
public static GatewayConnectionConfig getDefaultConfig() { return GatewayConnectionConfig.defaultConfig; }
return GatewayConnectionConfig.defaultConfig;
public static GatewayConnectionConfig getDefaultConfig() { return new GatewayConnectionConfig(); }
class GatewayConnectionConfig { private static final GatewayConnectionConfig defaultConfig = new GatewayConnectionConfig(); private Duration requestTimeout; private int maxPoolSize; private Duration idleConnectionTimeout; private InetSocketAddress inetSocketProxyAddress; /** * Constructor. */ public GatewayConnectionConfig() { this.idleConnectionTimeout = DEFAULT_IDLE_CONNECTION_TIMEOUT; this.maxPoolSize = DEFAULT_MAX_POOL_SIZE; this.requestTimeout = DEFAULT_REQUEST_TIMEOUT; } /** * Gets the default Gateway connection configuration. * * @return the default gateway connection configuration. */ /** * Gets the request timeout (time to wait for response from network peer). * * @return the request timeout duration. */ public Duration getRequestTimeout() { return this.requestTimeout; } /** * Sets the request timeout (time to wait for response from network peer). * The default is 60 seconds. * * @param requestTimeout the request timeout duration. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setRequestTimeout(Duration requestTimeout) { this.requestTimeout = requestTimeout; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxPoolSize() { return this.maxPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxPoolSize The value of the connection pool size. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; return this; } /** * Gets the value of the timeout for an idle connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleConnectionTimeout() { return this.idleConnectionTimeout; } /** * sets the value of the timeout for an idle connection. After that time, * the connection will be automatically closed. * * @param idleConnectionTimeout the duration for an idle connection. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the InetSocketAddress of proxy server. * * @return the value of proxyHost. */ public InetSocketAddress getProxy() { return this.inetSocketProxyAddress; } /** * This will create the InetSocketAddress for proxy server, * all the requests to cosmoDB will route from this address. * * @param proxy The proxy server. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setProxy(InetSocketAddress proxy) { this.inetSocketProxyAddress = proxy; return this; } @Override public String toString() { return "GatewayConnectionConfig{" + "requestTimeout=" + requestTimeout + ", maxPoolSize=" + maxPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", inetSocketProxyAddress=" + inetSocketProxyAddress + '}'; } }
class GatewayConnectionConfig { private static final Duration DEFAULT_REQUEST_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_IDLE_CONNECTION_TIMEOUT = Duration.ofSeconds(60); private static final int DEFAULT_MAX_POOL_SIZE = 1000; private Duration requestTimeout; private int maxConnectionPoolSize; private Duration idleConnectionTimeout; private InetSocketAddress inetSocketProxyAddress; /** * Constructor. */ public GatewayConnectionConfig() { this.idleConnectionTimeout = DEFAULT_IDLE_CONNECTION_TIMEOUT; this.maxConnectionPoolSize = DEFAULT_MAX_POOL_SIZE; this.requestTimeout = DEFAULT_REQUEST_TIMEOUT; } /** * Gets the default Gateway connection configuration. * * @return the default gateway connection configuration. */ /** * Gets the request timeout (time to wait for response from network peer). * * @return the request timeout duration. */ public Duration getRequestTimeout() { return this.requestTimeout; } /** * Sets the request timeout (time to wait for response from network peer). * The default is 60 seconds. * * @param requestTimeout the request timeout duration. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setRequestTimeout(Duration requestTimeout) { this.requestTimeout = requestTimeout; return this; } /** * Gets the value of the connection pool size the client is using. * * @return connection pool size. */ public int getMaxConnectionPoolSize() { return this.maxConnectionPoolSize; } /** * Sets the value of the connection pool size, the default * is 1000. * * @param maxConnectionPoolSize The value of the connection pool size. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setMaxConnectionPoolSize(int maxConnectionPoolSize) { this.maxConnectionPoolSize = maxConnectionPoolSize; return this; } /** * Gets the value of the timeout for an idle connection, the default is 60 * seconds. * * @return Idle connection timeout duration. */ public Duration getIdleConnectionTimeout() { return this.idleConnectionTimeout; } /** * sets the value of the timeout for an idle connection. After that time, * the connection will be automatically closed. * * @param idleConnectionTimeout the duration for an idle connection. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the InetSocketAddress of proxy server. * * @return the value of proxyHost. */ public InetSocketAddress getProxy() { return this.inetSocketProxyAddress; } /** * This will create the InetSocketAddress for proxy server, * all the requests to cosmoDB will route from this address. * * @param proxy The proxy server. * @return the {@link GatewayConnectionConfig}. */ public GatewayConnectionConfig setProxy(InetSocketAddress proxy) { this.inetSocketProxyAddress = proxy; return this; } @Override public String toString() { return "GatewayConnectionConfig{" + "requestTimeout=" + requestTimeout + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", inetSocketProxyAddress=" + inetSocketProxyAddress + '}'; } }
Yes, makes sense.
public static DirectConnectionConfig getDefaultConfig() { return DirectConnectionConfig.defaultConfig; }
return DirectConnectionConfig.defaultConfig;
public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_CHANNEL_TIMEOUT = Duration.ZERO; private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final int DEFAULT_MAX_CHANNELS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_ENDPOINT = 10; private static final DirectConnectionConfig defaultConfig = new DirectConnectionConfig(); private Duration connectionTimeout; private Duration idleChannelTimeout; private Duration idleEndpointTimeout; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; /** * Constructor. */ public DirectConnectionConfig() { this.connectionTimeout = null; this.idleChannelTimeout = DEFAULT_IDLE_CHANNEL_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxChannelsPerEndpoint = DEFAULT_MAX_CHANNELS_PER_ENDPOINT; this.maxRequestsPerChannel = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; } /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ /** * Gets the direct connection timeout * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the direct connection timeout * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle channel timeout * @return idle channel timeout */ public Duration getIdleChannelTimeout() { return idleChannelTimeout; } /** * Sets the idle channel timeout * @param idleChannelTimeout idle channel timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleChannelTimeout(Duration idleChannelTimeout) { this.idleChannelTimeout = idleChannelTimeout; return this; } /** * Gets the idle endpoint timeout * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max channels per endpoint * @return the max channels per endpoint */ public int getMaxChannelsPerEndpoint() { return maxChannelsPerEndpoint; } /** * Sets the max channels per endpoint * @param maxChannelsPerEndpoint the max channels per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxChannelsPerEndpoint(int maxChannelsPerEndpoint) { this.maxChannelsPerEndpoint = maxChannelsPerEndpoint; return this; } /** * Gets the max requests per endpoint * @return the max requests per endpoint */ public int getMaxRequestsPerChannel() { return maxRequestsPerChannel; } /** * Sets the max requests per endpoint * @param maxRequestsPerChannel the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerChannel(int maxRequestsPerChannel) { this.maxRequestsPerChannel = maxRequestsPerChannel; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleChannelTimeout=" + idleChannelTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxChannelsPerEndpoint=" + maxChannelsPerEndpoint + ", maxRequestsPerChannel=" + maxRequestsPerChannel + '}'; } }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_CHANNEL_TIMEOUT = Duration.ZERO; private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final int DEFAULT_MAX_CHANNELS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_ENDPOINT = 10; private Duration connectionTimeout; private Duration idleChannelTimeout; private Duration idleEndpointTimeout; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; /** * Constructor. */ public DirectConnectionConfig() { this.connectionTimeout = null; this.idleChannelTimeout = DEFAULT_IDLE_CHANNEL_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxChannelsPerEndpoint = DEFAULT_MAX_CHANNELS_PER_ENDPOINT; this.maxRequestsPerChannel = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; } /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ /** * Gets the direct connection timeout * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the direct connection timeout * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle channel timeout * @return idle channel timeout */ public Duration getIdleChannelTimeout() { return idleChannelTimeout; } /** * Sets the idle channel timeout * @param idleChannelTimeout idle channel timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleChannelTimeout(Duration idleChannelTimeout) { this.idleChannelTimeout = idleChannelTimeout; return this; } /** * Gets the idle endpoint timeout * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max channels per endpoint * @return the max channels per endpoint */ public int getMaxChannelsPerEndpoint() { return maxChannelsPerEndpoint; } /** * Sets the max channels per endpoint * @param maxChannelsPerEndpoint the max channels per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxChannelsPerEndpoint(int maxChannelsPerEndpoint) { this.maxChannelsPerEndpoint = maxChannelsPerEndpoint; return this; } /** * Gets the max requests per endpoint * @return the max requests per endpoint */ public int getMaxRequestsPerChannel() { return maxRequestsPerChannel; } /** * Sets the max requests per endpoint * @param maxRequestsPerChannel the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerChannel(int maxRequestsPerChannel) { this.maxRequestsPerChannel = maxRequestsPerChannel; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleChannelTimeout=" + idleChannelTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxChannelsPerEndpoint=" + maxChannelsPerEndpoint + ", maxRequestsPerChannel=" + maxRequestsPerChannel + '}'; } }
Done.
public static CosmosClientBuilder cloneCosmosClientBuilder(CosmosClientBuilder builder) { CosmosClientBuilder copy = new CosmosClientBuilder(); copy.endpoint(builder.getEndpoint()) .key(builder.getKey()) .directMode(builder.getDirectConnectionConfig()) .gatewayMode(builder.getGatewayConnectionConfig()) .consistencyLevel(builder.getConsistencyLevel()) .keyCredential(builder.getKeyCredential()) .permissions(builder.getPermissions()) .authorizationTokenResolver(builder.getAuthorizationTokenResolver()) .resourceToken(builder.getResourceToken()) .contentResponseOnWriteEnabled(builder.isContentResponseOnWriteEnabled()) .userAgentSuffix(builder.getUserAgentSuffix()) .throttlingRetryOptions(builder.getThrottlingRetryOptions()) .preferredRegions(builder.getPreferredRegions()) .endpointDiscoverEnabled(builder.isEndpointDiscoveryEnabled()) .multipleWriteRegionsEnabled(builder.isMultipleWriteRegionsEnabled()) .readRequestsFallbackEnabled(builder.isReadRequestsFallbackEnabled()); return copy; }
.endpointDiscoverEnabled(builder.isEndpointDiscoveryEnabled())
public static CosmosClientBuilder cloneCosmosClientBuilder(CosmosClientBuilder builder) { CosmosClientBuilder copy = new CosmosClientBuilder(); copy.endpoint(builder.getEndpoint()) .key(builder.getKey()) .directMode(builder.getDirectConnectionConfig()) .gatewayMode(builder.getGatewayConnectionConfig()) .consistencyLevel(builder.getConsistencyLevel()) .keyCredential(builder.getKeyCredential()) .permissions(builder.getPermissions()) .authorizationTokenResolver(builder.getAuthorizationTokenResolver()) .resourceToken(builder.getResourceToken()) .contentResponseOnWriteEnabled(builder.isContentResponseOnWriteEnabled()) .userAgentSuffix(builder.getUserAgentSuffix()) .throttlingRetryOptions(builder.getThrottlingRetryOptions()) .preferredRegions(builder.getPreferredRegions()) .endpointDiscoveryEnabled(builder.isEndpointDiscoveryEnabled()) .multipleWriteRegionsEnabled(builder.isMultipleWriteRegionsEnabled()) .readRequestsFallbackEnabled(builder.isReadRequestsFallbackEnabled()); return copy; }
class CosmosBridgeInternal { public static AsyncDocumentClient getAsyncDocumentClient(CosmosClient client) { return client.asyncClient().getDocClientWrapper(); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosAsyncClient client) { return client.getDocClientWrapper(); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosAsyncDatabase cosmosAsyncDatabase) { return cosmosAsyncDatabase.getDocClientWrapper(); } public static CosmosAsyncDatabase getCosmosDatabaseWithNewClient(CosmosAsyncDatabase cosmosDatabase, CosmosAsyncClient client) { return new CosmosAsyncDatabase(cosmosDatabase.getId(), client); } public static CosmosAsyncContainer getCosmosContainerWithNewClient(CosmosAsyncContainer cosmosContainer, CosmosAsyncDatabase cosmosDatabase, CosmosAsyncClient client) { return new CosmosAsyncContainer(cosmosContainer.getId(), CosmosBridgeInternal.getCosmosDatabaseWithNewClient(cosmosDatabase, client)); } public static AsyncDocumentClient getContextClient(CosmosAsyncDatabase database) { return database.getClient().getContextClient(); } public static AsyncDocumentClient getContextClient(CosmosAsyncContainer container) { return container.getDatabase().getClient().getContextClient(); } public static CosmosAsyncContainer getCosmosAsyncContainer(CosmosContainer container) { return container.asyncContainer; } public static ConsistencyLevel getConsistencyLevel(CosmosClientBuilder cosmosClientBuilder) { return cosmosClientBuilder.getConsistencyLevel(); } public static ConnectionPolicy getConnectionPolicy(CosmosClientBuilder cosmosClientBuilder) { return cosmosClientBuilder.getConnectionPolicy(); } }
class CosmosBridgeInternal { public static AsyncDocumentClient getAsyncDocumentClient(CosmosClient client) { return client.asyncClient().getDocClientWrapper(); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosAsyncClient client) { return client.getDocClientWrapper(); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosAsyncDatabase cosmosAsyncDatabase) { return cosmosAsyncDatabase.getDocClientWrapper(); } public static CosmosAsyncDatabase getCosmosDatabaseWithNewClient(CosmosAsyncDatabase cosmosDatabase, CosmosAsyncClient client) { return new CosmosAsyncDatabase(cosmosDatabase.getId(), client); } public static CosmosAsyncContainer getCosmosContainerWithNewClient(CosmosAsyncContainer cosmosContainer, CosmosAsyncDatabase cosmosDatabase, CosmosAsyncClient client) { return new CosmosAsyncContainer(cosmosContainer.getId(), CosmosBridgeInternal.getCosmosDatabaseWithNewClient(cosmosDatabase, client)); } public static AsyncDocumentClient getContextClient(CosmosAsyncDatabase database) { return database.getClient().getContextClient(); } public static AsyncDocumentClient getContextClient(CosmosAsyncContainer container) { return container.getDatabase().getClient().getContextClient(); } public static CosmosAsyncContainer getCosmosAsyncContainer(CosmosContainer container) { return container.asyncContainer; } public static ConsistencyLevel getConsistencyLevel(CosmosClientBuilder cosmosClientBuilder) { return cosmosClientBuilder.getConsistencyLevel(); } public static ConnectionPolicy getConnectionPolicy(CosmosClientBuilder cosmosClientBuilder) { return cosmosClientBuilder.getConnectionPolicy(); } }
this seems odd, can be closed in last line and then begin .subscribe( from this line.
public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix( "Invoice"); formTrainingAsyncClient.beginTraining(trainingSetSource, true, trainModelOptions, Duration.ofSeconds(5) ).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); }
).subscribe(recognizePollingOperation -> {
public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix("Invoice"); formTrainingAsyncClient.beginTraining(trainingFilesUrl, true, trainModelOptions, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTraining() { String trainingSetSource = "{training-set-SAS-URL}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient * with options */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); } }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; formTrainingAsyncClient.beginTraining(trainingFilesUrl, useTrainingLabels).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient * with options */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); } }
nitpick: seems like this spacing isn't as good as how it used to be
public static Mono<ContentType> detectContentType(Flux<ByteBuffer> buffer) { byte[] header = new byte[4]; int[] written = new int[]{0}; ContentType[] contentType = {ContentType.fromString("none")}; return buffer.map(chunk -> { final int len = chunk.remaining(); for (int i = 0; i < len; i++) { header[written[0]] = chunk.get(i); written[0]++; if (written[0] == 4) { if (isJpeg(header)) { contentType[0] = ContentType.IMAGE_JPEG; } else if (isPdf(header)) { contentType[0] = ContentType.APPLICATION_PDF; } else if (isPng(header)) { contentType[0] = ContentType.IMAGE_PNG; } else if (isTiff(header)) { contentType[0] = ContentType.IMAGE_TIFF; } return false; } } return true; }) .takeWhile(doContinue -> doContinue) .then(Mono.defer(() -> { if (contentType[0] != null) { return Mono.just(contentType[0]); } else { return Mono.error(new RuntimeException("Content type could not be detected. " + "Should use other overload API that takes content type.")); } })); }
.takeWhile(doContinue -> doContinue)
public static Mono<ContentType> detectContentType(Flux<ByteBuffer> buffer) { byte[] header = new byte[4]; int[] written = new int[]{0}; ContentType[] contentType = {ContentType.fromString("none")}; return buffer.map(chunk -> { final int len = chunk.remaining(); for (int i = 0; i < len; i++) { header[written[0]] = chunk.get(i); written[0]++; if (written[0] == 4) { if (isJpeg(header)) { contentType[0] = ContentType.IMAGE_JPEG; } else if (isPdf(header)) { contentType[0] = ContentType.APPLICATION_PDF; } else if (isPng(header)) { contentType[0] = ContentType.IMAGE_PNG; } else if (isTiff(header)) { contentType[0] = ContentType.IMAGE_TIFF; } return false; } } return true; }) .takeWhile(doContinue -> doContinue) .then(Mono.defer(() -> { if (contentType[0] != null) { return Mono.just(contentType[0]); } else { return Mono.error(new RuntimeException("Content type could not be detected. " + "Should use other overload API that takes content type.")); } })); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final int BYTE_BUFFER_CHUNK_SIZE = 4096; private Utility() { } /** * Automatically detect byte buffer's content type. * <p> * Given the source: <a href="https: * * @param buffer The byte buffer input. * * @return The {@link Mono} of {@link ContentType} content type. */ private static boolean isJpeg(byte[] header) { return (header[0] == (byte) 0xff && header[1] == (byte) 0xd8); } private static boolean isPdf(byte[] header) { return header[0] == (byte) 0x25 && header[1] == (byte) 0x50 && header[2] == (byte) 0x44 && header[3] == (byte) 0x46; } private static boolean isPng(byte[] header) { return header[0] == (byte) 0x89 && header[1] == (byte) 0x50 && header[2] == (byte) 0x4e && header[3] == (byte) 0x47; } private static boolean isTiff(byte[] header) { return (header[0] == (byte) 0x49 && header[1] == (byte) 0x49 && header[2] == (byte) 0x2a && header[3] == (byte) 0x0) || (header[0] == (byte) 0x4d && header[1] == (byte) 0x4d && header[2] == (byte) 0x0 && header[3] == (byte) 0x2a); } /** * Creates a Flux of ByteBuffer, with each ByteBuffer wrapping bytes read from the given * InputStream. * * @param inputStream InputStream to back the Flux * * @return Flux of ByteBuffer backed by the InputStream */ public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { Pair pair = new Pair(); return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[BYTE_BUFFER_CHUNK_SIZE]; try { int numBytes = inputStream.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw LOGGER.logExceptionAsError(new RuntimeException(ioe)); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(Pair::buffer) .cache(); } /** * Extracts the result ID from the URL. * * @param operationLocation The URL specified in the 'Operation-Location' response header containing the * resultId used to track the progress and obtain the result of the analyze operation. * * @return The resultId used to track the progress. */ public static String parseModelId(String operationLocation) { if (!CoreUtils.isNullOrEmpty(operationLocation)) { int lastIndex = operationLocation.lastIndexOf('/'); if (lastIndex != -1) { return operationLocation.substring(lastIndex + 1); } } throw LOGGER.logExceptionAsError( new RuntimeException("Failed to parse operation header for result Id from: " + operationLocation)); } /** * Given an iterable will apply the indexing function to it and return the index and each item of the iterable. * * @param iterable the list to apply the mapping function to. * @param biConsumer the function which accepts the index and the each value of the iterable. * @param <T> the type of items being returned. */ public static <T> void forEachWithIndex(Iterable<T> iterable, BiConsumer<Integer, T> biConsumer) { int[] index = new int[]{0}; iterable.forEach(element -> biConsumer.accept(index[0]++, element)); } private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final int BYTE_BUFFER_CHUNK_SIZE = 4096; private Utility() { } /** * Automatically detect byte buffer's content type. * <p> * Given the source: <a href="https: * * @param buffer The byte buffer input. * * @return The {@link Mono} of {@link ContentType} content type. */ private static boolean isJpeg(byte[] header) { return (header[0] == (byte) 0xff && header[1] == (byte) 0xd8); } private static boolean isPdf(byte[] header) { return header[0] == (byte) 0x25 && header[1] == (byte) 0x50 && header[2] == (byte) 0x44 && header[3] == (byte) 0x46; } private static boolean isPng(byte[] header) { return header[0] == (byte) 0x89 && header[1] == (byte) 0x50 && header[2] == (byte) 0x4e && header[3] == (byte) 0x47; } private static boolean isTiff(byte[] header) { return (header[0] == (byte) 0x49 && header[1] == (byte) 0x49 && header[2] == (byte) 0x2a && header[3] == (byte) 0x0) || (header[0] == (byte) 0x4d && header[1] == (byte) 0x4d && header[2] == (byte) 0x0 && header[3] == (byte) 0x2a); } /** * Creates a Flux of ByteBuffer, with each ByteBuffer wrapping bytes read from the given * InputStream. * * @param inputStream InputStream to back the Flux * * @return Flux of ByteBuffer backed by the InputStream */ public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { Pair pair = new Pair(); return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[BYTE_BUFFER_CHUNK_SIZE]; try { int numBytes = inputStream.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw LOGGER.logExceptionAsError(new RuntimeException(ioe)); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(Pair::buffer) .cache(); } /** * Extracts the result ID from the URL. * * @param operationLocation The URL specified in the 'Operation-Location' response header containing the * resultId used to track the progress and obtain the result of the analyze operation. * * @return The resultId used to track the progress. */ public static String parseModelId(String operationLocation) { if (!CoreUtils.isNullOrEmpty(operationLocation)) { int lastIndex = operationLocation.lastIndexOf('/'); if (lastIndex != -1) { return operationLocation.substring(lastIndex + 1); } } throw LOGGER.logExceptionAsError( new RuntimeException("Failed to parse operation header for result Id from: " + operationLocation)); } /** * Given an iterable will apply the indexing function to it and return the index and each item of the iterable. * * @param iterable the list to apply the mapping function to. * @param biConsumer the function which accepts the index and the each value of the iterable. * @param <T> the type of items being returned. */ public static <T> void forEachWithIndex(Iterable<T> iterable, BiConsumer<Integer, T> biConsumer) { int[] index = new int[]{0}; iterable.forEach(element -> biConsumer.accept(index[0]++, element)); } private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
probably better to change the code snippets to, making it trainingFilesUrl, useTrainingLabels
public void beginTraining() { String trainingSetSource = "{training-set-SAS-URL}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); }
formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile).subscribe(
public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; formTrainingAsyncClient.beginTraining(trainingFilesUrl, useTrainingLabels).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient * with options */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix( "Invoice"); formTrainingAsyncClient.beginTraining(trainingSetSource, true, trainModelOptions, Duration.ofSeconds(5) ).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); } }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient * with options */ public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix("Invoice"); formTrainingAsyncClient.beginTraining(trainingFilesUrl, true, trainModelOptions, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); } }
maybe you're going to address this in another PR, but from this meeting we also determined to change getModelInfos -> getCustomModels
public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); }
public void getModelInfos() { formTrainingAsyncClient.getModelInfos().subscribe(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn())); }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTraining() { String trainingSetSource = "{training-set-SAS-URL}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient * with options */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix( "Invoice"); formTrainingAsyncClient.beginTraining(trainingSetSource, true, trainModelOptions, Duration.ofSeconds(5) ).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ }
class FormTrainingAsyncClientJavaDocCodeSnippets { private FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); /** * Code snippet for {@link FormTrainingAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { FormTrainingAsyncClient formTrainingAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient() .getFormTrainingAsyncClient(); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; formTrainingAsyncClient.beginTraining(trainingFilesUrl, useTrainingLabels).subscribe( recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient * with options */ public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix("Invoice"); formTrainingAsyncClient.beginTraining(trainingFilesUrl, true, trainModelOptions, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted%n", modelId); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ }
Yeah, they were correctly formatted now.
public static Mono<ContentType> detectContentType(Flux<ByteBuffer> buffer) { byte[] header = new byte[4]; int[] written = new int[]{0}; ContentType[] contentType = {ContentType.fromString("none")}; return buffer.map(chunk -> { final int len = chunk.remaining(); for (int i = 0; i < len; i++) { header[written[0]] = chunk.get(i); written[0]++; if (written[0] == 4) { if (isJpeg(header)) { contentType[0] = ContentType.IMAGE_JPEG; } else if (isPdf(header)) { contentType[0] = ContentType.APPLICATION_PDF; } else if (isPng(header)) { contentType[0] = ContentType.IMAGE_PNG; } else if (isTiff(header)) { contentType[0] = ContentType.IMAGE_TIFF; } return false; } } return true; }) .takeWhile(doContinue -> doContinue) .then(Mono.defer(() -> { if (contentType[0] != null) { return Mono.just(contentType[0]); } else { return Mono.error(new RuntimeException("Content type could not be detected. " + "Should use other overload API that takes content type.")); } })); }
.takeWhile(doContinue -> doContinue)
public static Mono<ContentType> detectContentType(Flux<ByteBuffer> buffer) { byte[] header = new byte[4]; int[] written = new int[]{0}; ContentType[] contentType = {ContentType.fromString("none")}; return buffer.map(chunk -> { final int len = chunk.remaining(); for (int i = 0; i < len; i++) { header[written[0]] = chunk.get(i); written[0]++; if (written[0] == 4) { if (isJpeg(header)) { contentType[0] = ContentType.IMAGE_JPEG; } else if (isPdf(header)) { contentType[0] = ContentType.APPLICATION_PDF; } else if (isPng(header)) { contentType[0] = ContentType.IMAGE_PNG; } else if (isTiff(header)) { contentType[0] = ContentType.IMAGE_TIFF; } return false; } } return true; }) .takeWhile(doContinue -> doContinue) .then(Mono.defer(() -> { if (contentType[0] != null) { return Mono.just(contentType[0]); } else { return Mono.error(new RuntimeException("Content type could not be detected. " + "Should use other overload API that takes content type.")); } })); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final int BYTE_BUFFER_CHUNK_SIZE = 4096; private Utility() { } /** * Automatically detect byte buffer's content type. * <p> * Given the source: <a href="https: * * @param buffer The byte buffer input. * * @return The {@link Mono} of {@link ContentType} content type. */ private static boolean isJpeg(byte[] header) { return (header[0] == (byte) 0xff && header[1] == (byte) 0xd8); } private static boolean isPdf(byte[] header) { return header[0] == (byte) 0x25 && header[1] == (byte) 0x50 && header[2] == (byte) 0x44 && header[3] == (byte) 0x46; } private static boolean isPng(byte[] header) { return header[0] == (byte) 0x89 && header[1] == (byte) 0x50 && header[2] == (byte) 0x4e && header[3] == (byte) 0x47; } private static boolean isTiff(byte[] header) { return (header[0] == (byte) 0x49 && header[1] == (byte) 0x49 && header[2] == (byte) 0x2a && header[3] == (byte) 0x0) || (header[0] == (byte) 0x4d && header[1] == (byte) 0x4d && header[2] == (byte) 0x0 && header[3] == (byte) 0x2a); } /** * Creates a Flux of ByteBuffer, with each ByteBuffer wrapping bytes read from the given * InputStream. * * @param inputStream InputStream to back the Flux * * @return Flux of ByteBuffer backed by the InputStream */ public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { Pair pair = new Pair(); return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[BYTE_BUFFER_CHUNK_SIZE]; try { int numBytes = inputStream.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw LOGGER.logExceptionAsError(new RuntimeException(ioe)); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(Pair::buffer) .cache(); } /** * Extracts the result ID from the URL. * * @param operationLocation The URL specified in the 'Operation-Location' response header containing the * resultId used to track the progress and obtain the result of the analyze operation. * * @return The resultId used to track the progress. */ public static String parseModelId(String operationLocation) { if (!CoreUtils.isNullOrEmpty(operationLocation)) { int lastIndex = operationLocation.lastIndexOf('/'); if (lastIndex != -1) { return operationLocation.substring(lastIndex + 1); } } throw LOGGER.logExceptionAsError( new RuntimeException("Failed to parse operation header for result Id from: " + operationLocation)); } /** * Given an iterable will apply the indexing function to it and return the index and each item of the iterable. * * @param iterable the list to apply the mapping function to. * @param biConsumer the function which accepts the index and the each value of the iterable. * @param <T> the type of items being returned. */ public static <T> void forEachWithIndex(Iterable<T> iterable, BiConsumer<Integer, T> biConsumer) { int[] index = new int[]{0}; iterable.forEach(element -> biConsumer.accept(index[0]++, element)); } private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final int BYTE_BUFFER_CHUNK_SIZE = 4096; private Utility() { } /** * Automatically detect byte buffer's content type. * <p> * Given the source: <a href="https: * * @param buffer The byte buffer input. * * @return The {@link Mono} of {@link ContentType} content type. */ private static boolean isJpeg(byte[] header) { return (header[0] == (byte) 0xff && header[1] == (byte) 0xd8); } private static boolean isPdf(byte[] header) { return header[0] == (byte) 0x25 && header[1] == (byte) 0x50 && header[2] == (byte) 0x44 && header[3] == (byte) 0x46; } private static boolean isPng(byte[] header) { return header[0] == (byte) 0x89 && header[1] == (byte) 0x50 && header[2] == (byte) 0x4e && header[3] == (byte) 0x47; } private static boolean isTiff(byte[] header) { return (header[0] == (byte) 0x49 && header[1] == (byte) 0x49 && header[2] == (byte) 0x2a && header[3] == (byte) 0x0) || (header[0] == (byte) 0x4d && header[1] == (byte) 0x4d && header[2] == (byte) 0x0 && header[3] == (byte) 0x2a); } /** * Creates a Flux of ByteBuffer, with each ByteBuffer wrapping bytes read from the given * InputStream. * * @param inputStream InputStream to back the Flux * * @return Flux of ByteBuffer backed by the InputStream */ public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { Pair pair = new Pair(); return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[BYTE_BUFFER_CHUNK_SIZE]; try { int numBytes = inputStream.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw LOGGER.logExceptionAsError(new RuntimeException(ioe)); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(Pair::buffer) .cache(); } /** * Extracts the result ID from the URL. * * @param operationLocation The URL specified in the 'Operation-Location' response header containing the * resultId used to track the progress and obtain the result of the analyze operation. * * @return The resultId used to track the progress. */ public static String parseModelId(String operationLocation) { if (!CoreUtils.isNullOrEmpty(operationLocation)) { int lastIndex = operationLocation.lastIndexOf('/'); if (lastIndex != -1) { return operationLocation.substring(lastIndex + 1); } } throw LOGGER.logExceptionAsError( new RuntimeException("Failed to parse operation header for result Id from: " + operationLocation)); } /** * Given an iterable will apply the indexing function to it and return the index and each item of the iterable. * * @param iterable the list to apply the mapping function to. * @param biConsumer the function which accepts the index and the each value of the iterable. * @param <T> the type of items being returned. */ public static <T> void forEachWithIndex(Iterable<T> iterable, BiConsumer<Integer, T> biConsumer) { int[] index = new int[]{0}; iterable.forEach(element -> biConsumer.accept(index[0]++, element)); } private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
nit: doesn't need a new line
public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false) .setPrefix("Invoice"); boolean useTrainingLabels = true; CustomFormModel customFormModel = formTrainingClient.beginTraining( trainingFilesUrl, useTrainingLabels, trainModelOptions, Duration.ofSeconds(5)).getFinalResult(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }
.setPrefix("Invoice");
public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix("Invoice"); boolean useTrainingLabels = true; CustomFormModel customFormModel = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels, trainModelOptions, Duration.ofSeconds(5)).getFinalResult(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }
class FormTrainingClientJavaDocCodeSnippets { private FormTrainingClient formTrainingClient = new FormRecognizerClientBuilder().buildClient() .getFormTrainingClient(); /** * Code snippet for {@link FormTrainingClient} initialization */ public void formTrainingClientInInitialization() { FormTrainingClient formTrainingClient = new FormRecognizerClientBuilder().buildClient() .getFormTrainingClient(); } /** * Code snippet for {@link FormTrainingClient */ public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; CustomFormModel customFormModel = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels).getFinalResult(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); } /** * Code snippet for {@link FormTrainingClient * with options */ /** * Code snippet for {@link FormTrainingClient */ public void getCustomModel() { String modelId = "{model_id}"; CustomFormModel customFormModel = formTrainingClient.getCustomModel(modelId); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); } /** * Code snippet for {@link FormTrainingClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; Response<CustomFormModel> response = formTrainingClient.getCustomModelWithResponse(modelId, Context.NONE); System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); } /** * Code snippet for {@link FormTrainingClient */ public void getAccountProperties() { AccountProperties accountProperties = formTrainingClient.getAccountProperties(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); } /** * Code snippet for {@link FormTrainingClient */ public void getAccountPropertiesWithResponse() { Response<AccountProperties> response = formTrainingClient.getAccountPropertiesWithResponse(Context.NONE); System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); } /** * Code snippet for {@link FormTrainingClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingClient.deleteModel(modelId); System.out.printf("Model Id: %s is deleted.%n", modelId); } /** * Code snippet for {@link FormTrainingClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; Response<Void> response = formTrainingClient.deleteModelWithResponse(modelId, Context.NONE); System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted.%n", modelId); } /** * Code snippet for {@link FormTrainingClient */ public void getModelInfos() { formTrainingClient.getModelInfos().forEach(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn()) ); } /** * Code snippet for {@link FormTrainingClient */ public void getModelInfosWithContext() { formTrainingClient.getModelInfos(Context.NONE).forEach(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn()) ); } }
class FormTrainingClientJavaDocCodeSnippets { private FormTrainingClient formTrainingClient = new FormRecognizerClientBuilder().buildClient() .getFormTrainingClient(); /** * Code snippet for {@link FormTrainingClient} initialization */ public void formTrainingClientInInitialization() { FormTrainingClient formTrainingClient = new FormRecognizerClientBuilder().buildClient() .getFormTrainingClient(); } /** * Code snippet for {@link FormTrainingClient */ public void beginTraining() { String trainingFilesUrl = "{training-set-SAS-URL}"; boolean useTrainingLabels = true; CustomFormModel customFormModel = formTrainingClient.beginTraining(trainingFilesUrl, useTrainingLabels).getFinalResult(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); } /** * Code snippet for {@link FormTrainingClient * with options */ /** * Code snippet for {@link FormTrainingClient */ public void getCustomModel() { String modelId = "{model_id}"; CustomFormModel customFormModel = formTrainingClient.getCustomModel(modelId); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); } /** * Code snippet for {@link FormTrainingClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; Response<CustomFormModel> response = formTrainingClient.getCustomModelWithResponse(modelId, Context.NONE); System.out.printf("Response Status Code: %d.", response.getStatusCode()); CustomFormModel customFormModel = response.getValue(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Field: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); } /** * Code snippet for {@link FormTrainingClient */ public void getAccountProperties() { AccountProperties accountProperties = formTrainingClient.getAccountProperties(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); } /** * Code snippet for {@link FormTrainingClient */ public void getAccountPropertiesWithResponse() { Response<AccountProperties> response = formTrainingClient.getAccountPropertiesWithResponse(Context.NONE); System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getCustomModelLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCustomModelCount()); } /** * Code snippet for {@link FormTrainingClient */ public void deleteModel() { String modelId = "{model_id}"; formTrainingClient.deleteModel(modelId); System.out.printf("Model Id: %s is deleted.%n", modelId); } /** * Code snippet for {@link FormTrainingClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; Response<Void> response = formTrainingClient.deleteModelWithResponse(modelId, Context.NONE); System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model Id: %s is deleted.%n", modelId); } /** * Code snippet for {@link FormTrainingClient */ public void getModelInfos() { formTrainingClient.getModelInfos().forEach(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn()) ); } /** * Code snippet for {@link FormTrainingClient */ public void getModelInfosWithContext() { formTrainingClient.getModelInfos(Context.NONE).forEach(customModel -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", customModel.getModelId(), customModel.getStatus(), customModel.getCreatedOn(), customModel.getLastUpdatedOn()) ); } }
We're still leaking the auth token; just because we override the toString(), it will not prevent someone trapping and dumping the exception object via an object mapper or some other serialization method which ignores the toString() override. The initial fix that creates a copy of the request header map is a better one if we cannot reuse the original header while removing the sensitive header parts. I checked the code and we only invoke the respective setRequestHeaders() method in exceptional cases only; the only concern here is the memory hit which could go as high as 16k per each request header.
public String toString() { return getClass().getSimpleName() + "{" + "error=" + cosmosError + ", resourceAddress='" + resourceAddress + '\'' + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
+ filterSensitiveData(requestHeaders) + '}';
public String toString() { return getClass().getSimpleName() + "{" + "error=" + cosmosError + ", resourceAddress='" + resourceAddress + '\'' + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + filterSensitiveData(requestHeaders) + '}'; }
class CosmosClientException extends AzureException { private static final long serialVersionUID = 1L; private final int statusCode; private final Map<String, String> responseHeaders; private CosmosResponseDiagnostics cosmosResponseDiagnostics; private final RequestTimeline requestTimeline; private CosmosError cosmosError; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; protected CosmosClientException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.requestTimeline = RequestTimeline.empty(); this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. */ CosmosClientException(int statusCode) { this(statusCode, null, null, null); } /** * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosClientException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosClientException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosClientException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosClientException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosClientException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosClientException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosClientException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosResponseDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosResponseDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } /** * Gets the error code associated with the exception. * * @return the error. */ public CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Response Diagnostic Statistics associated with this exception. * * @return Cosmos Response Diagnostic Statistics associated with this exception. */ public CosmosResponseDiagnostics getResponseDiagnostics() { return cosmosResponseDiagnostics; } CosmosClientException setResponseDiagnostics(CosmosResponseDiagnostics cosmosResponseDiagnostics) { this.cosmosResponseDiagnostics = cosmosResponseDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf(ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } }
class CosmosClientException extends AzureException { private static final long serialVersionUID = 1L; private final int statusCode; private final Map<String, String> responseHeaders; private CosmosResponseDiagnostics cosmosResponseDiagnostics; private final RequestTimeline requestTimeline; private CosmosError cosmosError; long lsn; String partitionKeyRangeId; Map<String, String> requestHeaders; Uri requestUri; String resourceAddress; protected CosmosClientException(int statusCode, String message, Map<String, String> responseHeaders, Throwable cause) { super(message, cause); this.statusCode = statusCode; this.requestTimeline = RequestTimeline.empty(); this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); } /** * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. */ CosmosClientException(int statusCode) { this(statusCode, null, null, null); } /** * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ protected CosmosClientException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); ModelBridgeInternal.setProperty(cosmosError, Constants.Properties.MESSAGE, errorMessage); } /** * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ protected CosmosClientException(int statusCode, Exception innerException) { this(statusCode, null, null, innerException); } /** * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosClientException(int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** * Creates a new instance of the CosmosClientException class. * * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ protected CosmosClientException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map<String, String> responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; } /** * Creates a new instance of the CosmosClientException class. * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ protected CosmosClientException(String message, Exception exception, Map<String, String> responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @Override public String getMessage() { if (cosmosResponseDiagnostics == null) { return innerErrorMessage(); } return innerErrorMessage() + ", " + cosmosResponseDiagnostics.toString(); } /** * Gets the activity ID associated with the request. * * @return the activity ID. */ public String getActivityId() { if (this.responseHeaders != null) { return this.responseHeaders.get(HttpConstants.HttpHeaders.ACTIVITY_ID); } return null; } /** * Gets the http status code. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the sub status code. * * @return the status code. */ public int getSubStatusCode() { int code = HttpConstants.SubStatusCodes.UNKNOWN; if (this.responseHeaders != null) { String subStatusString = this.responseHeaders.get(HttpConstants.HttpHeaders.SUB_STATUS); if (StringUtils.isNotEmpty(subStatusString)) { try { code = Integer.parseInt(subStatusString); } catch (NumberFormatException e) { } } } return code; } /** * Gets the error code associated with the exception. * * @return the error. */ public CosmosError getError() { return this.cosmosError; } void setError(CosmosError cosmosError) { this.cosmosError = cosmosError; } /** * Gets the recommended time duration after which the client can retry failed * requests * * @return the recommended time duration after which the client can retry failed * requests. */ public Duration getRetryAfterDuration() { long retryIntervalInMilliseconds = 0; if (this.responseHeaders != null) { String header = this.responseHeaders.get(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (StringUtils.isNotEmpty(header)) { try { retryIntervalInMilliseconds = Long.parseLong(header); } catch (NumberFormatException e) { } } } return Duration.ofMillis(retryIntervalInMilliseconds); } /** * Gets the response headers as key-value pairs * * @return the response headers */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the resource address associated with this exception. * * @return the resource address associated with this exception. */ String getResourceAddress() { return this.resourceAddress; } /** * Gets the Cosmos Response Diagnostic Statistics associated with this exception. * * @return Cosmos Response Diagnostic Statistics associated with this exception. */ public CosmosResponseDiagnostics getResponseDiagnostics() { return cosmosResponseDiagnostics; } CosmosClientException setResponseDiagnostics(CosmosResponseDiagnostics cosmosResponseDiagnostics) { this.cosmosResponseDiagnostics = cosmosResponseDiagnostics; return this; } @Override String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (cosmosError != null) { innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { innerErrorMessage = String.valueOf(ModelBridgeInternal.getObjectFromJsonSerializable(cosmosError, "Errors")); } } return innerErrorMessage; } private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); } return null; } private List<Map.Entry<String, String>> filterSensitiveData(Map<String, String> requestHeaders) { if (requestHeaders == null) { return null; } return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); } void setResourceAddress(String resourceAddress) { this.resourceAddress = resourceAddress; } }
what does 0 as idle connection timeout mean?
public DirectConnectionConfig() { this.connectionTimeout = null; this.idleConnectionTimeout = Duration.ZERO; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; }
this.idleConnectionTimeout = Duration.ZERO;
public DirectConnectionConfig() { this.idleConnectionTimeout = Duration.ZERO; this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_CONNECTION; }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final int DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_ENDPOINT = 10; private Duration connectionTimeout; private Duration idleConnectionTimeout; private Duration idleEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; /** * Constructor. */ /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); } /** * Gets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint * * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint * * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle connection timeout for direct client * Default value is {@link Duration * Direct client doesn't close connections to an endpoint * by default unless specified. * * @return idle connection timeout */ public Duration getIdleConnectionTimeout() { return idleConnectionTimeout; } /** * Sets the idle connection timeout * Default value is {@link Duration * Direct client doesn't close connections to an endpoint * by default unless specified. * * @param idleConnectionTimeout idle connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the idle endpoint timeout * Default value is 70 seconds. * * If there are no connections to a specific endpoint for idle endpoint timeout, * direct client closes that endpoint to save resources and I/O cost. * * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * Default value is 70 seconds. * * If there are no connections to a specific endpoint for idle endpoint timeout, * direct client closes that endpoint to save resources and I/O cost. * * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max connections per endpoint * Default value is 30 * * @return the max connections per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max connections per endpoint * Default value is 30 * * @param maxConnectionsPerEndpoint the max connections per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per connection per endpoint * Default value is 10 * * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per connection per endpoint * Default value is 10 * * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleConnectionTimeout=" + idleConnectionTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + '}'; } }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(60L); private static final int DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_CONNECTION = 10; private Duration connectionTimeout; private Duration idleConnectionTimeout; private Duration idleEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; /** * Constructor. */ /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); } /** * Gets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint. * * Configures timeout for underlying Netty Channel {@link ChannelOption * * By default, the connection timeout is 60 seconds. * * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint. * * Configures timeout for underlying Netty Channel {@link ChannelOption * * By default, the connection timeout is 60 seconds. * * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle connection timeout for direct client * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @return idle connection timeout */ public Duration getIdleConnectionTimeout() { return idleConnectionTimeout; } /** * Sets the idle connection timeout * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @param idleConnectionTimeout idle connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the idle endpoint timeout * * Default value is 70 seconds. * * If there are no requests to a specific endpoint for idle endpoint timeout duration, * direct client closes all connections to that endpoint to save resources and I/O cost. * * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * * Default value is 70 seconds. * * If there are no requests to a specific endpoint for idle endpoint timeout duration, * direct client closes all connections to that endpoint to save resources and I/O cost. * * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max connections per endpoint * This represents the size of connection pool for a specific endpoint * * Default value is 30 * * @return the max connections per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max connections per endpoint * This represents the size of connection pool for a specific endpoint * * Default value is 30 * * @param maxConnectionsPerEndpoint the max connections per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per connection * This represents the number of requests that will be queued * on a single connection for a specific endpoint * * Default value is 10 * * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per connection * This represents the number of requests that will be queued * on a single connection for a specific endpoint * * Default value is 10 * * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleConnectionTimeout=" + idleConnectionTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + '}'; } }
```java this.connectionTimeout = null; ``` why is this null?
public DirectConnectionConfig() { this.connectionTimeout = null; this.idleConnectionTimeout = Duration.ZERO; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; }
this.connectionTimeout = null;
public DirectConnectionConfig() { this.idleConnectionTimeout = Duration.ZERO; this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_CONNECTION; }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final int DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_ENDPOINT = 10; private Duration connectionTimeout; private Duration idleConnectionTimeout; private Duration idleEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; /** * Constructor. */ /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); } /** * Gets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint * * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint * * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle connection timeout for direct client * Default value is {@link Duration * Direct client doesn't close connections to an endpoint * by default unless specified. * * @return idle connection timeout */ public Duration getIdleConnectionTimeout() { return idleConnectionTimeout; } /** * Sets the idle connection timeout * Default value is {@link Duration * Direct client doesn't close connections to an endpoint * by default unless specified. * * @param idleConnectionTimeout idle connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the idle endpoint timeout * Default value is 70 seconds. * * If there are no connections to a specific endpoint for idle endpoint timeout, * direct client closes that endpoint to save resources and I/O cost. * * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * Default value is 70 seconds. * * If there are no connections to a specific endpoint for idle endpoint timeout, * direct client closes that endpoint to save resources and I/O cost. * * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max connections per endpoint * Default value is 30 * * @return the max connections per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max connections per endpoint * Default value is 30 * * @param maxConnectionsPerEndpoint the max connections per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per connection per endpoint * Default value is 10 * * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per connection per endpoint * Default value is 10 * * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleConnectionTimeout=" + idleConnectionTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + '}'; } }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(60L); private static final int DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_CONNECTION = 10; private Duration connectionTimeout; private Duration idleConnectionTimeout; private Duration idleEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; /** * Constructor. */ /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); } /** * Gets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint. * * Configures timeout for underlying Netty Channel {@link ChannelOption * * By default, the connection timeout is 60 seconds. * * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint. * * Configures timeout for underlying Netty Channel {@link ChannelOption * * By default, the connection timeout is 60 seconds. * * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle connection timeout for direct client * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @return idle connection timeout */ public Duration getIdleConnectionTimeout() { return idleConnectionTimeout; } /** * Sets the idle connection timeout * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @param idleConnectionTimeout idle connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the idle endpoint timeout * * Default value is 70 seconds. * * If there are no requests to a specific endpoint for idle endpoint timeout duration, * direct client closes all connections to that endpoint to save resources and I/O cost. * * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * * Default value is 70 seconds. * * If there are no requests to a specific endpoint for idle endpoint timeout duration, * direct client closes all connections to that endpoint to save resources and I/O cost. * * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max connections per endpoint * This represents the size of connection pool for a specific endpoint * * Default value is 30 * * @return the max connections per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max connections per endpoint * This represents the size of connection pool for a specific endpoint * * Default value is 30 * * @param maxConnectionsPerEndpoint the max connections per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per connection * This represents the number of requests that will be queued * on a single connection for a specific endpoint * * Default value is 10 * * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per connection * This represents the number of requests that will be queued * on a single connection for a specific endpoint * * Default value is 10 * * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleConnectionTimeout=" + idleConnectionTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + '}'; } }
I have referred this in docs in `get/set` API.
public DirectConnectionConfig() { this.connectionTimeout = null; this.idleConnectionTimeout = Duration.ZERO; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; }
this.idleConnectionTimeout = Duration.ZERO;
public DirectConnectionConfig() { this.idleConnectionTimeout = Duration.ZERO; this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_CONNECTION; }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final int DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_ENDPOINT = 10; private Duration connectionTimeout; private Duration idleConnectionTimeout; private Duration idleEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; /** * Constructor. */ /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); } /** * Gets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint * * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint * * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle connection timeout for direct client * Default value is {@link Duration * Direct client doesn't close connections to an endpoint * by default unless specified. * * @return idle connection timeout */ public Duration getIdleConnectionTimeout() { return idleConnectionTimeout; } /** * Sets the idle connection timeout * Default value is {@link Duration * Direct client doesn't close connections to an endpoint * by default unless specified. * * @param idleConnectionTimeout idle connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the idle endpoint timeout * Default value is 70 seconds. * * If there are no connections to a specific endpoint for idle endpoint timeout, * direct client closes that endpoint to save resources and I/O cost. * * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * Default value is 70 seconds. * * If there are no connections to a specific endpoint for idle endpoint timeout, * direct client closes that endpoint to save resources and I/O cost. * * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max connections per endpoint * Default value is 30 * * @return the max connections per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max connections per endpoint * Default value is 30 * * @param maxConnectionsPerEndpoint the max connections per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per connection per endpoint * Default value is 10 * * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per connection per endpoint * Default value is 10 * * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleConnectionTimeout=" + idleConnectionTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + '}'; } }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(60L); private static final int DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_CONNECTION = 10; private Duration connectionTimeout; private Duration idleConnectionTimeout; private Duration idleEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; /** * Constructor. */ /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); } /** * Gets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint. * * Configures timeout for underlying Netty Channel {@link ChannelOption * * By default, the connection timeout is 60 seconds. * * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint. * * Configures timeout for underlying Netty Channel {@link ChannelOption * * By default, the connection timeout is 60 seconds. * * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle connection timeout for direct client * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @return idle connection timeout */ public Duration getIdleConnectionTimeout() { return idleConnectionTimeout; } /** * Sets the idle connection timeout * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @param idleConnectionTimeout idle connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the idle endpoint timeout * * Default value is 70 seconds. * * If there are no requests to a specific endpoint for idle endpoint timeout duration, * direct client closes all connections to that endpoint to save resources and I/O cost. * * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * * Default value is 70 seconds. * * If there are no requests to a specific endpoint for idle endpoint timeout duration, * direct client closes all connections to that endpoint to save resources and I/O cost. * * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max connections per endpoint * This represents the size of connection pool for a specific endpoint * * Default value is 30 * * @return the max connections per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max connections per endpoint * This represents the size of connection pool for a specific endpoint * * Default value is 30 * * @param maxConnectionsPerEndpoint the max connections per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per connection * This represents the number of requests that will be queued * on a single connection for a specific endpoint * * Default value is 10 * * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per connection * This represents the number of requests that will be queued * on a single connection for a specific endpoint * * Default value is 10 * * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleConnectionTimeout=" + idleConnectionTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + '}'; } }
will get rid of the redundant initializer.
public DirectConnectionConfig() { this.connectionTimeout = null; this.idleConnectionTimeout = Duration.ZERO; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; }
this.connectionTimeout = null;
public DirectConnectionConfig() { this.idleConnectionTimeout = Duration.ZERO; this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_CONNECTION; }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final int DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_ENDPOINT = 10; private Duration connectionTimeout; private Duration idleConnectionTimeout; private Duration idleEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; /** * Constructor. */ /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); } /** * Gets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint * * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint * * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle connection timeout for direct client * Default value is {@link Duration * Direct client doesn't close connections to an endpoint * by default unless specified. * * @return idle connection timeout */ public Duration getIdleConnectionTimeout() { return idleConnectionTimeout; } /** * Sets the idle connection timeout * Default value is {@link Duration * Direct client doesn't close connections to an endpoint * by default unless specified. * * @param idleConnectionTimeout idle connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the idle endpoint timeout * Default value is 70 seconds. * * If there are no connections to a specific endpoint for idle endpoint timeout, * direct client closes that endpoint to save resources and I/O cost. * * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * Default value is 70 seconds. * * If there are no connections to a specific endpoint for idle endpoint timeout, * direct client closes that endpoint to save resources and I/O cost. * * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max connections per endpoint * Default value is 30 * * @return the max connections per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max connections per endpoint * Default value is 30 * * @param maxConnectionsPerEndpoint the max connections per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per connection per endpoint * Default value is 10 * * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per connection per endpoint * Default value is 10 * * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleConnectionTimeout=" + idleConnectionTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + '}'; } }
class DirectConnectionConfig { private static final Duration DEFAULT_IDLE_ENDPOINT_TIMEOUT = Duration.ofSeconds(70L); private static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(60L); private static final int DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT = 30; private static final int DEFAULT_MAX_REQUESTS_PER_CONNECTION = 10; private Duration connectionTimeout; private Duration idleConnectionTimeout; private Duration idleEndpointTimeout; private int maxConnectionsPerEndpoint; private int maxRequestsPerConnection; /** * Constructor. */ /** * Gets the default DIRECT connection configuration. * * @return the default direct connection configuration. */ public static DirectConnectionConfig getDefaultConfig() { return new DirectConnectionConfig(); } /** * Gets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint. * * Configures timeout for underlying Netty Channel {@link ChannelOption * * By default, the connection timeout is 60 seconds. * * @return direct connection timeout */ public Duration getConnectionTimeout() { return connectionTimeout; } /** * Sets the connection timeout for direct client, * represents timeout for establishing connections with an endpoint. * * Configures timeout for underlying Netty Channel {@link ChannelOption * * By default, the connection timeout is 60 seconds. * * @param connectionTimeout the connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * Gets the idle connection timeout for direct client * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @return idle connection timeout */ public Duration getIdleConnectionTimeout() { return idleConnectionTimeout; } /** * Sets the idle connection timeout * * Default value is {@link Duration * * Direct client doesn't close a single connection to an endpoint * by default unless specified. * * @param idleConnectionTimeout idle connection timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleConnectionTimeout(Duration idleConnectionTimeout) { this.idleConnectionTimeout = idleConnectionTimeout; return this; } /** * Gets the idle endpoint timeout * * Default value is 70 seconds. * * If there are no requests to a specific endpoint for idle endpoint timeout duration, * direct client closes all connections to that endpoint to save resources and I/O cost. * * @return the idle endpoint timeout */ public Duration getIdleEndpointTimeout() { return idleEndpointTimeout; } /** * Sets the idle endpoint timeout * * Default value is 70 seconds. * * If there are no requests to a specific endpoint for idle endpoint timeout duration, * direct client closes all connections to that endpoint to save resources and I/O cost. * * @param idleEndpointTimeout the idle endpoint timeout * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setIdleEndpointTimeout(Duration idleEndpointTimeout) { this.idleEndpointTimeout = idleEndpointTimeout; return this; } /** * Gets the max connections per endpoint * This represents the size of connection pool for a specific endpoint * * Default value is 30 * * @return the max connections per endpoint */ public int getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Sets the max connections per endpoint * This represents the size of connection pool for a specific endpoint * * Default value is 30 * * @param maxConnectionsPerEndpoint the max connections per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxConnectionsPerEndpoint(int maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Gets the max requests per connection * This represents the number of requests that will be queued * on a single connection for a specific endpoint * * Default value is 10 * * @return the max requests per endpoint */ public int getMaxRequestsPerConnection() { return maxRequestsPerConnection; } /** * Sets the max requests per connection * This represents the number of requests that will be queued * on a single connection for a specific endpoint * * Default value is 10 * * @param maxRequestsPerConnection the max requests per endpoint * @return the {@link DirectConnectionConfig} */ public DirectConnectionConfig setMaxRequestsPerConnection(int maxRequestsPerConnection) { this.maxRequestsPerConnection = maxRequestsPerConnection; return this; } @Override public String toString() { return "DirectConnectionConfig{" + "connectionTimeout=" + connectionTimeout + ", idleConnectionTimeout=" + idleConnectionTimeout + ", idleEndpointTimeout=" + idleEndpointTimeout + ", maxConnectionsPerEndpoint=" + maxConnectionsPerEndpoint + ", maxRequestsPerConnection=" + maxRequestsPerConnection + '}'; } }
I don't quite know why [this sample code](https://github.com/Azure/azure-service-bus/blob/08df9251dd93d40e087372671b11a562686859cb/samples/Java/azure-servicebus/QueuesWithProxy/src/main/java/com/microsoft/azure/servicebus/samples/queueswithproxy/QueuesWithProxy.java) has this line. Since I am using localhost and the host name will be different from service bus host. If I enable this line, the proxy cannot be created properly. I don't think this line is necessary but just want to point out.
public void managementClientWithProxy() throws InterruptedException, ServiceBusException { String proxyHostName = "127.0.0.1"; int proxyPort = 8888; final ProxySelector systemDefaultSelector = ProxySelector.getDefault(); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(URI uri) { if (uri != null && uri.getHost() != null ) { List<Proxy> proxies = new LinkedList<>(); proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostName, proxyPort))); return proxies; } return systemDefaultSelector.select(uri); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe){ if (uri == null || sa == null || ioe == null) { throw new IllegalArgumentException("Arguments can't be null."); } systemDefaultSelector.connectFailed(uri, sa, ioe); } }); URI namespaceEndpointURI = TestUtils.getNamespaceEndpointURI(); ClientSettings managementClientSettings = TestUtils.getManagementClientSettings(); ManagementClient managementClient = new ManagementClient(namespaceEndpointURI, managementClientSettings); String queueName = "proxy" + UUID.randomUUID().toString().substring(0, 8); QueueDescription q = new QueueDescription(queueName); QueueDescription qCreated = managementClient.createQueue(q); Assert.assertEquals(q, qCreated); }
public void managementClientWithProxy() throws Exception { String proxyHostName = "127.0.0.1"; int proxyPort = 8888; final ProxySelector systemDefaultSelector = ProxySelector.getDefault(); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(URI uri) { if (uri != null && uri.getHost() != null ) { List<Proxy> proxies = new LinkedList<>(); proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostName, proxyPort))); return proxies; } return systemDefaultSelector.select(uri); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe){ if (uri == null || sa == null || ioe == null) { throw new IllegalArgumentException("Arguments can't be null."); } systemDefaultSelector.connectFailed(uri, sa, ioe); } }); URI namespaceEndpointURI = TestUtils.getNamespaceEndpointURI(); ClientSettings managementClientSettings = TestUtils.getManagementClientSettings(); ManagementClient managementClient = new ManagementClient(namespaceEndpointURI, managementClientSettings); String queueName = "test" + UUID.randomUUID().toString().substring(0, 8); QueueDescription q = new QueueDescription(queueName); QueueDescription qCreated = managementClient.createQueue(q); Assert.assertEquals(q, qCreated); String connectionString = TestUtils.getNamespaceConnectionString(); ConnectionStringBuilder connStrBuilder = new ConnectionStringBuilder(connectionString, queueName); connStrBuilder.setTransportType(TransportType.AMQP_WEB_SOCKETS); QueueClient sendClient = new QueueClient(connStrBuilder, ReceiveMode.PEEKLOCK); Message message = new Message("hello"); sendClient.sendAsync(message).thenRunAsync(() -> sendClient.closeAsync()); waitForEnter(10); }
class ManagementClientProxyTest { @Test }
class ManagementClientProxyTest { @Ignore @Test private void waitForEnter(int seconds) { ExecutorService executor = Executors.newCachedThreadPool(); try { executor.invokeAny(Arrays.asList(() -> { System.in.read(); return 0; }, () -> { Thread.sleep(seconds * 1000); return 0; })); } catch (Exception e) { } } }
I am wondering if it may be easier/better to set the properties in the client that enables the integration with the default mechanisms that Java networking uses for proxy configuration - documented [here](https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html). ```suggestion .setUseProxySelector(true) .setUseProxyProperties(true) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); ```
public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); if(shouldUseProxy(this.namespaceEndpointURI.getHost())){ InetSocketAddress address = (InetSocketAddress)this.proxies.get(0).address(); String proxyHostName=address.getHostName(); int proxyPort=address.getPort(); clientBuilder.setProxyServer(new ProxyServer.Builder(proxyHostName,proxyPort)); } this.asyncHttpClient = asyncHttpClient(clientBuilder); }
}
public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setUseProxySelector(true) .setUseProxyProperties(true) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); this.asyncHttpClient = asyncHttpClient(clientBuilder); }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private MessagingFactory factory; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; private List<Proxy> proxies; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ public boolean shouldUseProxy(final String hostName) { final URI uri = createURIFromHostNamePort(hostName, ClientConstants.HTTPS_PORT); final ProxySelector proxySelector = ProxySelector.getDefault(); if (proxySelector == null) { return false; } final List<Proxy> proxies = proxySelector.select(uri); if (isProxyAddressLegal(proxies)) { this.proxies = proxies; return true; } else { return false; } } private static URI createURIFromHostNamePort(final String hostName, final int port) { return URI.create(String.format(ClientConstants.HTTPS_URI_FORMAT, hostName, port)); } private static boolean isProxyAddressLegal(final List<Proxy> proxies) { return proxies != null && !proxies.isEmpty() && proxies.get(0).type() == Proxy.Type.HTTP && proxies.get(0).address() != null && proxies.get(0).address() instanceof InetSocketAddress; } /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } try { DocumentBuilderFactory dbf = SerializerUtil.getDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private MessagingFactory factory; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; private List<Proxy> proxies; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } try { DocumentBuilderFactory dbf = SerializerUtil.getDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
@giventocode Thanks for pointing to this resource to offer more background. I verified that this change would have the same impact: select the default proxy set by ProxySelector, this is also what I was trying to do in my changes but don't aware that there are already system level support built into Java. I also verified this from here: https://www.javadoc.io/static/com.ning/async-http-client/1.9.31/com/ning/http/client/AsyncHttpClientConfig.Builder.html. It also discusses "If useProxySelector is set to true but setProxyServer(ProxyServer) was used to explicitly set a proxy server, the latter is preferred.", so should we just have .setUseProxySelector(true)? Have also verified that setting only this property will achieve the same goal in my test.
public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); if(shouldUseProxy(this.namespaceEndpointURI.getHost())){ InetSocketAddress address = (InetSocketAddress)this.proxies.get(0).address(); String proxyHostName=address.getHostName(); int proxyPort=address.getPort(); clientBuilder.setProxyServer(new ProxyServer.Builder(proxyHostName,proxyPort)); } this.asyncHttpClient = asyncHttpClient(clientBuilder); }
}
public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setUseProxySelector(true) .setUseProxyProperties(true) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); this.asyncHttpClient = asyncHttpClient(clientBuilder); }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private MessagingFactory factory; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; private List<Proxy> proxies; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ public boolean shouldUseProxy(final String hostName) { final URI uri = createURIFromHostNamePort(hostName, ClientConstants.HTTPS_PORT); final ProxySelector proxySelector = ProxySelector.getDefault(); if (proxySelector == null) { return false; } final List<Proxy> proxies = proxySelector.select(uri); if (isProxyAddressLegal(proxies)) { this.proxies = proxies; return true; } else { return false; } } private static URI createURIFromHostNamePort(final String hostName, final int port) { return URI.create(String.format(ClientConstants.HTTPS_URI_FORMAT, hostName, port)); } private static boolean isProxyAddressLegal(final List<Proxy> proxies) { return proxies != null && !proxies.isEmpty() && proxies.get(0).type() == Proxy.Type.HTTP && proxies.get(0).address() != null && proxies.get(0).address() instanceof InetSocketAddress; } /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } try { DocumentBuilderFactory dbf = SerializerUtil.getDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private MessagingFactory factory; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; private List<Proxy> proxies; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } try { DocumentBuilderFactory dbf = SerializerUtil.getDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
```suggestion TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); ```
public void useAadAsyncClient() { DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .endpoint("{endpoint}") .credential(defaultCredential) .buildAsyncClient(); }
DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
public void useAadAsyncClient() { TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .endpoint("{endpoint}") .credential(defaultCredential) .buildAsyncClient(); }
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting async client using AzureKeyCredential authentication. */ public void useAzureKeyCredentialAsyncClient() { TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for getting async client using AAD authentication. */ /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } /** * Code snippet for handling exception */ public void handlingException() { List<DetectLanguageInput> documents = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un documento escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(documents, null, Context.NONE); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } } /** * Code snippet for analyzing sentiment of a document. */ public void analyzeSentiment() { String document = "The hotel was dark and unclean. I like microsoft."; DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(document); System.out.printf("Analyzed document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Analyzed sentence sentiment: %s.%n", sentenceSentiment.getSentiment())); } /** * Code snippet for detecting language in a document. */ public void detectLanguages() { String document = "Bonjour tout le monde"; DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(document); System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore()); } /** * Code snippet for recognizing category entity in a document. */ public void recognizeEntity() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsClient.recognizeEntities(document).forEach(entity -> System.out.printf("Recognized entity: %s, category: %s, subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); } /** * Code snippet for recognizing linked entity in a document. */ public void recognizeLinkedEntity() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getMatches().forEach(match -> System.out.printf("Text: %s, confidence score: %f.%n", match.getText(), match.getConfidenceScore())); }); } /** * Code snippet for extracting key phrases in a document. */ public void extractKeyPhrases() { String document = "My cat might need to see a veterinarian."; System.out.println("Extracted phrases:"); textAnalyticsClient.extractKeyPhrases(document).forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } }
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting async client using AzureKeyCredential authentication. */ public void useAzureKeyCredentialAsyncClient() { TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for getting async client using AAD authentication. */ /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } /** * Code snippet for handling exception */ public void handlingException() { List<DetectLanguageInput> documents = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un documento escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(documents, null, Context.NONE); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } } /** * Code snippet for analyzing sentiment of a document. */ public void analyzeSentiment() { String document = "The hotel was dark and unclean. I like microsoft."; DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(document); System.out.printf("Analyzed document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Analyzed sentence sentiment: %s.%n", sentenceSentiment.getSentiment())); } /** * Code snippet for detecting language in a document. */ public void detectLanguages() { String document = "Bonjour tout le monde"; DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(document); System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore()); } /** * Code snippet for recognizing category entity in a document. */ public void recognizeEntity() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsClient.recognizeEntities(document).forEach(entity -> System.out.printf("Recognized entity: %s, category: %s, subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); } /** * Code snippet for recognizing linked entity in a document. */ public void recognizeLinkedEntity() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getMatches().forEach(match -> System.out.printf("Text: %s, confidence score: %f.%n", match.getText(), match.getConfidenceScore())); }); } /** * Code snippet for extracting key phrases in a document. */ public void extractKeyPhrases() { String document = "My cat might need to see a veterinarian."; System.out.println("Extracted phrases:"); textAnalyticsClient.extractKeyPhrases(document).forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } }
Thanks for the additional insights. I further reviewed the code and in a nutshell: if there's a proxy selector, the proxy uri is retrieved from it and then is set explicitly as the proxy server to use. So a few things to consider: - One of the benefits of implementing a proxy selector is that it allows you to filter/decide what proxy to use for a given URL - by overriding ``` java.util.List<Proxy> select(URI uri)```. The current implementation seems like it'd block this ability as the proxy selector won't be used at all. - Java also provides a standard way to set the proxy explicitly, as per below. It seems like this also won't be possible. ``` System.setProperty("http.proxyHost", "webcache.example.com"); System.setProperty("http.proxyPort", "8080"); ``` As per the suggestion, if we set the flags in the underlying config of the asynchttpclient so it enables the default Java proxy setting behavior, then users can use the Java standard way of setting the proxies and extending how proxies are used programmatically.
public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); if(shouldUseProxy(this.namespaceEndpointURI.getHost())){ InetSocketAddress address = (InetSocketAddress)this.proxies.get(0).address(); String proxyHostName=address.getHostName(); int proxyPort=address.getPort(); clientBuilder.setProxyServer(new ProxyServer.Builder(proxyHostName,proxyPort)); } this.asyncHttpClient = asyncHttpClient(clientBuilder); }
}
public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setUseProxySelector(true) .setUseProxyProperties(true) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); this.asyncHttpClient = asyncHttpClient(clientBuilder); }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private MessagingFactory factory; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; private List<Proxy> proxies; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ public boolean shouldUseProxy(final String hostName) { final URI uri = createURIFromHostNamePort(hostName, ClientConstants.HTTPS_PORT); final ProxySelector proxySelector = ProxySelector.getDefault(); if (proxySelector == null) { return false; } final List<Proxy> proxies = proxySelector.select(uri); if (isProxyAddressLegal(proxies)) { this.proxies = proxies; return true; } else { return false; } } private static URI createURIFromHostNamePort(final String hostName, final int port) { return URI.create(String.format(ClientConstants.HTTPS_URI_FORMAT, hostName, port)); } private static boolean isProxyAddressLegal(final List<Proxy> proxies) { return proxies != null && !proxies.isEmpty() && proxies.get(0).type() == Proxy.Type.HTTP && proxies.get(0).address() != null && proxies.get(0).address() instanceof InetSocketAddress; } /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } try { DocumentBuilderFactory dbf = SerializerUtil.getDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private MessagingFactory factory; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; private List<Proxy> proxies; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } try { DocumentBuilderFactory dbf = SerializerUtil.getDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
I have discussed with @giventocode offline and we have decided to add both `.setUseProxySelector(true)` (compatible with AMQP websockets to use ProxySelector for send/receive operations) and `.setUseProxyProperties(true)` (users can use the Java standard way of setting the proxies and extending how proxies are used programmatically for ManagementClient.)
public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); if(shouldUseProxy(this.namespaceEndpointURI.getHost())){ InetSocketAddress address = (InetSocketAddress)this.proxies.get(0).address(); String proxyHostName=address.getHostName(); int proxyPort=address.getPort(); clientBuilder.setProxyServer(new ProxyServer.Builder(proxyHostName,proxyPort)); } this.asyncHttpClient = asyncHttpClient(clientBuilder); }
}
public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setUseProxySelector(true) .setUseProxyProperties(true) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); this.asyncHttpClient = asyncHttpClient(clientBuilder); }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private MessagingFactory factory; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; private List<Proxy> proxies; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ public boolean shouldUseProxy(final String hostName) { final URI uri = createURIFromHostNamePort(hostName, ClientConstants.HTTPS_PORT); final ProxySelector proxySelector = ProxySelector.getDefault(); if (proxySelector == null) { return false; } final List<Proxy> proxies = proxySelector.select(uri); if (isProxyAddressLegal(proxies)) { this.proxies = proxies; return true; } else { return false; } } private static URI createURIFromHostNamePort(final String hostName, final int port) { return URI.create(String.format(ClientConstants.HTTPS_URI_FORMAT, hostName, port)); } private static boolean isProxyAddressLegal(final List<Proxy> proxies) { return proxies != null && !proxies.isEmpty() && proxies.get(0).type() == Proxy.Type.HTTP && proxies.get(0).address() != null && proxies.get(0).address() instanceof InetSocketAddress; } /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } try { DocumentBuilderFactory dbf = SerializerUtil.getDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private MessagingFactory factory; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; private List<Proxy> proxies; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } try { DocumentBuilderFactory dbf = SerializerUtil.getDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
I saw this ref page using DefaultAzureCredential. https://github.com/Azure/azure-sdk-for-java/wiki/Identity-and-Authentication Should I follow it or use TokenCredential?
public void useAadAsyncClient() { DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .endpoint("{endpoint}") .credential(defaultCredential) .buildAsyncClient(); }
DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
public void useAadAsyncClient() { TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .endpoint("{endpoint}") .credential(defaultCredential) .buildAsyncClient(); }
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting async client using AzureKeyCredential authentication. */ public void useAzureKeyCredentialAsyncClient() { TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for getting async client using AAD authentication. */ /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } /** * Code snippet for handling exception */ public void handlingException() { List<DetectLanguageInput> documents = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un documento escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(documents, null, Context.NONE); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } } /** * Code snippet for analyzing sentiment of a document. */ public void analyzeSentiment() { String document = "The hotel was dark and unclean. I like microsoft."; DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(document); System.out.printf("Analyzed document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Analyzed sentence sentiment: %s.%n", sentenceSentiment.getSentiment())); } /** * Code snippet for detecting language in a document. */ public void detectLanguages() { String document = "Bonjour tout le monde"; DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(document); System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore()); } /** * Code snippet for recognizing category entity in a document. */ public void recognizeEntity() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsClient.recognizeEntities(document).forEach(entity -> System.out.printf("Recognized entity: %s, category: %s, subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); } /** * Code snippet for recognizing linked entity in a document. */ public void recognizeLinkedEntity() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getMatches().forEach(match -> System.out.printf("Text: %s, confidence score: %f.%n", match.getText(), match.getConfidenceScore())); }); } /** * Code snippet for extracting key phrases in a document. */ public void extractKeyPhrases() { String document = "My cat might need to see a veterinarian."; System.out.println("Extracted phrases:"); textAnalyticsClient.extractKeyPhrases(document).forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } }
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting async client using AzureKeyCredential authentication. */ public void useAzureKeyCredentialAsyncClient() { TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for getting async client using AAD authentication. */ /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } /** * Code snippet for handling exception */ public void handlingException() { List<DetectLanguageInput> documents = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un documento escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(documents, null, Context.NONE); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } } /** * Code snippet for analyzing sentiment of a document. */ public void analyzeSentiment() { String document = "The hotel was dark and unclean. I like microsoft."; DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(document); System.out.printf("Analyzed document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Analyzed sentence sentiment: %s.%n", sentenceSentiment.getSentiment())); } /** * Code snippet for detecting language in a document. */ public void detectLanguages() { String document = "Bonjour tout le monde"; DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(document); System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore()); } /** * Code snippet for recognizing category entity in a document. */ public void recognizeEntity() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsClient.recognizeEntities(document).forEach(entity -> System.out.printf("Recognized entity: %s, category: %s, subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); } /** * Code snippet for recognizing linked entity in a document. */ public void recognizeLinkedEntity() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getMatches().forEach(match -> System.out.printf("Text: %s, confidence score: %f.%n", match.getText(), match.getConfidenceScore())); }); } /** * Code snippet for extracting key phrases in a document. */ public void extractKeyPhrases() { String document = "My cat might need to see a veterinarian."; System.out.println("Extracted phrases:"); textAnalyticsClient.extractKeyPhrases(document).forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } }
It's better to use `TokenCredential` rather than a specific implementation. The builder says that `credential()` requires TokenCredential.
public void useAadAsyncClient() { DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .endpoint("{endpoint}") .credential(defaultCredential) .buildAsyncClient(); }
DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
public void useAadAsyncClient() { TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .endpoint("{endpoint}") .credential(defaultCredential) .buildAsyncClient(); }
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting async client using AzureKeyCredential authentication. */ public void useAzureKeyCredentialAsyncClient() { TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for getting async client using AAD authentication. */ /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } /** * Code snippet for handling exception */ public void handlingException() { List<DetectLanguageInput> documents = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un documento escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(documents, null, Context.NONE); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } } /** * Code snippet for analyzing sentiment of a document. */ public void analyzeSentiment() { String document = "The hotel was dark and unclean. I like microsoft."; DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(document); System.out.printf("Analyzed document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Analyzed sentence sentiment: %s.%n", sentenceSentiment.getSentiment())); } /** * Code snippet for detecting language in a document. */ public void detectLanguages() { String document = "Bonjour tout le monde"; DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(document); System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore()); } /** * Code snippet for recognizing category entity in a document. */ public void recognizeEntity() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsClient.recognizeEntities(document).forEach(entity -> System.out.printf("Recognized entity: %s, category: %s, subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); } /** * Code snippet for recognizing linked entity in a document. */ public void recognizeLinkedEntity() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getMatches().forEach(match -> System.out.printf("Text: %s, confidence score: %f.%n", match.getText(), match.getConfidenceScore())); }); } /** * Code snippet for extracting key phrases in a document. */ public void extractKeyPhrases() { String document = "My cat might need to see a veterinarian."; System.out.println("Extracted phrases:"); textAnalyticsClient.extractKeyPhrases(document).forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } }
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting async client using AzureKeyCredential authentication. */ public void useAzureKeyCredentialAsyncClient() { TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for getting async client using AAD authentication. */ /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } /** * Code snippet for handling exception */ public void handlingException() { List<DetectLanguageInput> documents = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un documento escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(documents, null, Context.NONE); } catch (HttpResponseException e) { System.out.println(e.getMessage()); } } /** * Code snippet for analyzing sentiment of a document. */ public void analyzeSentiment() { String document = "The hotel was dark and unclean. I like microsoft."; DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(document); System.out.printf("Analyzed document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Analyzed sentence sentiment: %s.%n", sentenceSentiment.getSentiment())); } /** * Code snippet for detecting language in a document. */ public void detectLanguages() { String document = "Bonjour tout le monde"; DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(document); System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore()); } /** * Code snippet for recognizing category entity in a document. */ public void recognizeEntity() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsClient.recognizeEntities(document).forEach(entity -> System.out.printf("Recognized entity: %s, category: %s, subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); } /** * Code snippet for recognizing linked entity in a document. */ public void recognizeLinkedEntity() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getMatches().forEach(match -> System.out.printf("Text: %s, confidence score: %f.%n", match.getText(), match.getConfidenceScore())); }); } /** * Code snippet for extracting key phrases in a document. */ public void extractKeyPhrases() { String document = "My cat might need to see a veterinarian."; System.out.println("Extracted phrases:"); textAnalyticsClient.extractKeyPhrases(document).forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } }
this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
public FormRecognizerClientBuilder credential(TokenCredential tokenCredential) { Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); this.tokenCredential = tokenCredential; return this; }
this.tokenCredential = tokenCredential;
public FormRecognizerClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); return this; }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String DEFAULT_SCOPE = "https: private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private TokenCredential tokenCredential; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .build(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); } else if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link FormRecognizerClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is {@code null}. */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
class FormRecognizerClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON; private static final String ACCEPT_HEADER = "Accept"; private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-formrecognizer.properties"; private static final String NAME = "name"; private static final String VERSION = "version"; private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); private static final String DEFAULT_SCOPE = "https: private final ClientLogger logger = new ClientLogger(FormRecognizerClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private final String clientName; private final String clientVersion; private String endpoint; private AzureKeyCredential credential; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private Configuration configuration; private RetryPolicy retryPolicy; private TokenCredential tokenCredential; private FormRecognizerServiceVersion version; static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; static final Duration DEFAULT_DURATION = Duration.ofSeconds(5); /** * The constructor with defaults. */ public FormRecognizerClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(FORM_RECOGNIZER_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); } /** * Creates a {@link FormRecognizerClient} based on options set in the builder. Every time * {@code buildClient()} is called a new instance of {@link FormRecognizerClient} is created. * * <p> * If {@link * {@link * settings are ignored * </p> * * @return A FormRecognizerClient with the options set from the builder. * @throws NullPointerException if {@link * {@link * @throws IllegalArgumentException if {@link */ public FormRecognizerClient buildClient() { return new FormRecognizerClient(buildAsyncClient()); } /** * Creates a {@link FormRecognizerAsyncClient} based on options set in the builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link FormRecognizerAsyncClient} is created. * * <p> * If {@link * {@link * settings are ignored. * </p> * * @return A FormRecognizerAsyncClient with the options set from the builder. * @throws NullPointerException if {@link * has not been set. * @throws IllegalArgumentException if {@link */ public FormRecognizerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); final Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; final FormRecognizerServiceVersion serviceVersion = version != null ? version : FormRecognizerServiceVersion.getLatest(); HttpPipeline pipeline = httpPipeline; if (pipeline == null) { pipeline = getDefaultHttpPipeline(buildConfiguration); } final FormRecognizerClientImpl formRecognizerAPI = new FormRecognizerClientImplBuilder() .endpoint(endpoint) .pipeline(pipeline) .buildClient(); return new FormRecognizerAsyncClient(formRecognizerAPI, serviceVersion); } private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) { final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); policies.add(new AddDatePolicy()); if (tokenCredential != null) { policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); } else if (credential != null) { policies.add(new AzureKeyCredentialPolicy(OCP_APIM_SUBSCRIPTION_KEY, credential)); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); } /** * Sets the service endpoint for the Azure Form Recognizer instance. * * @param endpoint The URL of the Azure Form Recognizer instance service requests to and receive responses from. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException if {@code endpoint} is null * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public FormRecognizerClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex)); } if (endpoint.endsWith("/")) { this.endpoint = endpoint.substring(0, endpoint.length() - 1); } else { this.endpoint = endpoint; } return this; } /** * Sets the {@link AzureKeyCredential} to use when authenticating HTTP requests for this * FormRecognizerClientBuilder. * * @param apiKeyCredential {@link AzureKeyCredential} API key credential * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code apiKeyCredential} is {@code null} */ public FormRecognizerClientBuilder credential(AzureKeyCredential apiKeyCredential) { this.credential = Objects.requireNonNull(apiKeyCredential, "'apiKeyCredential' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link FormRecognizerClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ /** * Sets the logging configuration for HTTP requests and responses. * * <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel * which will prevent logging.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated FormRecognizerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public FormRecognizerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder 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 HTTP pipeline to use for the service client. * <p> * If {@code pipeline} is set, all other settings are ignored, aside from * {@link FormRecognizerClientBuilder * {@link FormRecognizerClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = httpPipeline; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * 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 FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy * <p> * The default retry policy will be used if not provided {@link FormRecognizerClientBuilder * to build {@link FormRecognizerAsyncClient} or {@link FormRecognizerClient}. * * @param retryPolicy user's retry policy applied to each request. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link FormRecognizerServiceVersion} 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 FormRecognizerServiceVersion} of the service to be used when making requests. * * @return The updated FormRecognizerClientBuilder object. */ public FormRecognizerClientBuilder serviceVersion(FormRecognizerServiceVersion version) { this.version = version; return this; } }
nit: `.build` can be on the same line.
public void useAadAsyncClient() { TokenCredential credential = new DefaultAzureCredentialBuilder() .build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .endpoint("{endpoint}") .credential(credential) .buildClient(); }
.build();
public void useAadAsyncClient() { TokenCredential credential = new DefaultAzureCredentialBuilder().build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .endpoint("{endpoint}") .credential(credential) .buildClient(); }
class ReadmeSamples { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); private FormTrainingClient formTrainingClient = formRecognizerClient.getFormTrainingClient(); /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting async client using AAD authentication. */ /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } public void recognizeCustomForm() { String analyzeFilePath = "{file_source_url}"; String modelId = "{custom_trained_model_id}"; SyncPoller<OperationResult, IterableStream<RecognizedForm>> recognizeFormPoller = formRecognizerClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId); IterableStream<RecognizedForm> recognizedForms = recognizeFormPoller.getFinalResult(); recognizedForms.forEach(form -> { System.out.println("----------- Recognized Form -----------"); System.out.printf("Form type: %s%n", form.getFormType()); form.getFields().forEach((label, formField) -> { System.out.printf("Field %s has value %s with confidence score of %d.%n", label, formField.getFieldValue(), formField.getConfidence()); }); System.out.print("-----------------------------------"); }); } public void recognizeContent() { String analyzeFilePath = "{file_source_url}"; SyncPoller<OperationResult, IterableStream<FormPage>> recognizeLayoutPoller = formRecognizerClient.beginRecognizeContentFromUrl(analyzeFilePath); IterableStream<FormPage> layoutPageResults = recognizeLayoutPoller.getFinalResult(); layoutPageResults.forEach(formPage -> { System.out.println("----Recognizing content ----"); System.out.printf("Has width: %d and height: %d, measured with unit: %s.%n", formPage.getWidth(), formPage.getHeight(), formPage.getUnit()); formPage.getTables().forEach(formTable -> { System.out.printf("Table has %d rows and %d columns.%n", formTable.getRowCount(), formTable.getColumnCount()); formTable.getCells().forEach(formTableCell -> { System.out.printf("Cell has text %s.%n", formTableCell.getText()); }); System.out.println(); }); }); } public void recognizeReceipt() { String receiptSourceUrl = "https: + "/contoso-allinone.jpg"; SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> syncPoller = formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptSourceUrl); IterableStream<RecognizedReceipt> receiptPageResults = syncPoller.getFinalResult(); receiptPageResults.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name %s%n", usReceipt.getMerchantName().getName()); System.out.printf("Merchant Name Value: %s%n", usReceipt.getMerchantName().getFieldValue()); System.out.printf("Merchant Address %s%n", usReceipt.getMerchantAddress().getName()); System.out.printf("Merchant Address Value: %s%n", usReceipt.getMerchantAddress().getFieldValue()); System.out.printf("Merchant Phone Number %s%n", usReceipt.getMerchantPhoneNumber().getName()); System.out.printf("Merchant Phone Number Value: %s%n", usReceipt.getMerchantPhoneNumber().getFieldValue()); System.out.printf("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); }); } public void trainModel() { String trainingSetSource = "{unlabeled_training_set_SAS_URL}"; SyncPoller<OperationResult, CustomFormModel> trainingPoller = formTrainingClient.beginTraining(trainingSetSource, false); CustomFormModel customFormModel = trainingPoller.getFinalResult(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); System.out.printf("Model created on: %s%n", customFormModel.getCreatedOn()); System.out.printf("Model last updated: %s%n%n", customFormModel.getLastUpdatedOn()); System.out.println("Recognized Fields:"); customFormModel.getSubModels().forEach(customFormSubModel -> { customFormSubModel.getFieldMap().forEach((field, customFormModelField) -> System.out.printf("Field: %s Field Label: %s%n", field, customFormModelField.getLabel())); }); } public void manageModels() { AtomicReference<String> modelId = new AtomicReference<>(); AccountProperties accountProperties = formTrainingClient.getAccountProperties(); System.out.printf("The account has %s custom models, and we can have at most %s custom models", accountProperties.getCount(), accountProperties.getLimit()); PagedIterable<CustomFormModelInfo> customModels = formTrainingClient.getModelInfos(); System.out.println("We have following models in the account:"); customModels.forEach(customFormModelInfo -> { System.out.printf("Model Id: %s%n", customFormModelInfo.getModelId()); modelId.set(customFormModelInfo.getModelId()); CustomFormModel customModel = formTrainingClient.getCustomModel(customFormModelInfo.getModelId()); System.out.printf("Model Status: %s%n", customModel.getModelStatus()); System.out.printf("Created on: %s%n", customModel.getCreatedOn()); System.out.printf("Updated on: %s%n", customModel.getLastUpdatedOn()); customModel.getSubModels().forEach(customFormSubModel -> { System.out.printf("Custom Model Form type: %s%n", customFormSubModel.getFormType()); System.out.printf("Custom Model Accuracy: %d%n", customFormSubModel.getAccuracy()); if (customFormSubModel.getFieldMap() != null) { customFormSubModel.getFieldMap().forEach((fieldText, customFormModelField) -> { System.out.printf("Field Text: %s%n", fieldText); System.out.printf("Field Accuracy: %d%n", customFormModelField.getAccuracy()); }); } }); }); formTrainingClient.deleteModel(modelId.get()); } /** * Code snippet for handling exception */ public void handlingException() { try { formRecognizerClient.beginRecognizeContentFromUrl("invalidSourceUrl"); } catch (ErrorResponseException e) { System.out.println(e.getMessage()); } } }
class ReadmeSamples { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); private FormTrainingClient formTrainingClient = new FormTrainingClientBuilder().buildClient(); /** * Code snippet for getting sync client using the AzureKeyCredential authentication. */ public void useAzureKeyCredentialSyncClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for getting async client using AAD authentication. */ /** * Code snippet for rotating AzureKeyCredential of the client */ public void rotatingAzureKeyCredential() { AzureKeyCredential credential = new AzureKeyCredential("{key}"); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(credential) .endpoint("{endpoint}") .buildClient(); credential.update("{new_key}"); } public void recognizeCustomForm() { String formUrl = "{file_url}"; String modelId = "{custom_trained_model_id}"; SyncPoller<OperationResult, List<RecognizedForm>> recognizeFormPoller = formRecognizerClient.beginRecognizeCustomFormsFromUrl(formUrl, modelId); List<RecognizedForm> recognizedForms = recognizeFormPoller.getFinalResult(); for (int i = 0; i < recognizedForms.size(); i++) { RecognizedForm form = recognizedForms.get(i); System.out.printf("----------- Recognized Form %s%n-----------", i); System.out.printf("Form type: %s%n", form.getFormType()); form.getFields().forEach((label, formField) -> { System.out.printf("Field %s has value %s with confidence score of %d.%n", label, formField.getFieldValue(), formField.getConfidence()); }); System.out.print("-----------------------------------"); } } public void recognizeContent() { String contentFileUrl = "{file_url}"; SyncPoller<OperationResult, List<FormPage>> recognizeContentPoller = formRecognizerClient.beginRecognizeContentFromUrl(contentFileUrl); List<FormPage> contentPageResults = recognizeContentPoller.getFinalResult(); for (int i = 0; i < contentPageResults.size(); i++) { FormPage formPage = contentPageResults.get(i); System.out.printf("----Recognizing content for page %s%n----", i); System.out.printf("Has width: %d and height: %d, measured with unit: %s.%n", formPage.getWidth(), formPage.getHeight(), formPage.getUnit()); formPage.getTables().forEach(formTable -> { System.out.printf("Table has %d rows and %d columns.%n", formTable.getRowCount(), formTable.getColumnCount()); formTable.getCells().forEach(formTableCell -> { System.out.printf("Cell has text %s.%n", formTableCell.getText()); }); System.out.println(); }); } } public void recognizeReceipt() { String receiptUrl = "https: + "/contoso-allinone.jpg"; SyncPoller<OperationResult, List<RecognizedReceipt>> syncPoller = formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl); List<RecognizedReceipt> receiptPageResults = syncPoller.getFinalResult(); for (int i = 0; i < receiptPageResults.size(); i++) { System.out.printf("----Recognizing receipt for page %s%n----", i); RecognizedReceipt recognizedReceipt = receiptPageResults.get(i); USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Merchant Name %s%n", usReceipt.getMerchantName().getName()); System.out.printf("Merchant Name Value: %s%n", usReceipt.getMerchantName().getFieldValue()); System.out.printf("Merchant Address %s%n", usReceipt.getMerchantAddress().getName()); System.out.printf("Merchant Address Value: %s%n", usReceipt.getMerchantAddress().getFieldValue()); System.out.printf("Merchant Phone Number %s%n", usReceipt.getMerchantPhoneNumber().getName()); System.out.printf("Merchant Phone Number Value: %s%n", usReceipt.getMerchantPhoneNumber().getFieldValue()); System.out.printf("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); } } public void trainModel() { String trainingFilesUrl = "{training_set_SAS_URL}"; SyncPoller<OperationResult, CustomFormModel> trainingPoller = formTrainingClient.beginTraining(trainingFilesUrl, false); CustomFormModel customFormModel = trainingPoller.getFinalResult(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); System.out.printf("Model requested on: %s%n", customFormModel.getRequestedOn()); System.out.printf("Model training completed on: %s%n%n", customFormModel.getCompletedOn()); System.out.println("Recognized Fields:"); customFormModel.getSubmodels().forEach(customFormSubmodel -> { customFormSubmodel.getFieldMap().forEach((field, customFormModelField) -> System.out.printf("Field: %s Field Label: %s%n", field, customFormModelField.getLabel())); }); } public void manageModels() { AtomicReference<String> modelId = new AtomicReference<>(); AccountProperties accountProperties = formTrainingClient.getAccountProperties(); System.out.printf("The account has %s custom models, and we can have at most %s custom models", accountProperties.getCustomModelCount(), accountProperties.getCustomModelLimit()); PagedIterable<CustomFormModelInfo> customModels = formTrainingClient.listCustomModels(); System.out.println("We have following models in the account:"); customModels.forEach(customFormModelInfo -> { System.out.printf("Model Id: %s%n", customFormModelInfo.getModelId()); modelId.set(customFormModelInfo.getModelId()); CustomFormModel customModel = formTrainingClient.getCustomModel(customFormModelInfo.getModelId()); System.out.printf("Model Status: %s%n", customModel.getModelStatus()); System.out.printf("Created on: %s%n", customModel.getRequestedOn()); System.out.printf("Updated on: %s%n", customModel.getCompletedOn()); customModel.getSubmodels().forEach(customFormSubmodel -> { System.out.printf("Custom Model Form type: %s%n", customFormSubmodel.getFormType()); System.out.printf("Custom Model Accuracy: %d%n", customFormSubmodel.getAccuracy()); if (customFormSubmodel.getFieldMap() != null) { customFormSubmodel.getFieldMap().forEach((fieldText, customFormModelField) -> { System.out.printf("Field Text: %s%n", fieldText); System.out.printf("Field Accuracy: %d%n", customFormModelField.getAccuracy()); }); } }); }); formTrainingClient.deleteModel(modelId.get()); } /** * Code snippet for handling exception */ public void handlingException() { try { formRecognizerClient.beginRecognizeContentFromUrl("invalidSourceUrl"); } catch (ErrorResponseException e) { System.out.println(e.getMessage()); } } }
nit: missing an empty space
public int[] getRequiredTokens() { return new int[]{ TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.LITERAL_THROW, TokenTypes.METHOD_DEF }; }
return new int[]{
public int[] getRequiredTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.LITERAL_THROW, TokenTypes.METHOD_DEF }; }
class is static private final Queue<Boolean> classStaticDeque = Collections.asLifoQueue(new ArrayDeque<>()); private final Queue<Boolean> methodStaticDeque = Collections.asLifoQueue(new ArrayDeque<>()); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
class is static private final Queue<Boolean> classStaticDeque = Collections.asLifoQueue(new ArrayDeque<>()); private final Queue<Boolean> methodStaticDeque = Collections.asLifoQueue(new ArrayDeque<>()); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
Done
public int[] getRequiredTokens() { return new int[]{ TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.LITERAL_THROW, TokenTypes.METHOD_DEF }; }
return new int[]{
public int[] getRequiredTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.LITERAL_THROW, TokenTypes.METHOD_DEF }; }
class is static private final Queue<Boolean> classStaticDeque = Collections.asLifoQueue(new ArrayDeque<>()); private final Queue<Boolean> methodStaticDeque = Collections.asLifoQueue(new ArrayDeque<>()); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
class is static private final Queue<Boolean> classStaticDeque = Collections.asLifoQueue(new ArrayDeque<>()); private final Queue<Boolean> methodStaticDeque = Collections.asLifoQueue(new ArrayDeque<>()); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
In track 2, we've named this as endpoint instead of `host`.
public StorageManagementClient buildClient() { if (host == null) { this.host = "https: } if (apiVersion == null) { this.apiVersion = "2019-06-01"; } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, host, apiVersion, subscriptionId); return client; }
this.host = "https:
public StorageManagementClient buildClient() { if (endpoint == null) { this.endpoint = "https: } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, subscriptionId, endpoint); return client; }
class StorageManagementClientBuilder { /* * The ID of the target subscription. */ private String subscriptionId; /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder subscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /* * server parameter */ private String host; /** * Sets server parameter. * * @param host the host value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder host(String host) { this.host = host; return this; } /* * Api Version */ private String apiVersion; /* * The environment to connect to */ private AzureEnvironment environment; /** * Sets The environment to connect to. * * @param environment the environment value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder environment(AzureEnvironment environment) { this.environment = environment; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of StorageManagementClient with the provided parameters. * * @return an instance of StorageManagementClient. */ }
class StorageManagementClientBuilder { /* * The ID of the target subscription. */ private String subscriptionId; /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder subscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /* * server parameter */ private String endpoint; /** * Sets server parameter. * * @param endpoint the endpoint value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * The environment to connect to */ private AzureEnvironment environment; /** * Sets The environment to connect to. * * @param environment the environment value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder environment(AzureEnvironment environment) { this.environment = environment; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of StorageManagementClient with the provided parameters. * * @return an instance of StorageManagementClient. */ }
Do you still need the null check for `apiVersion` now that the setter is removed?
public StorageManagementClient buildClient() { if (host == null) { this.host = "https: } if (apiVersion == null) { this.apiVersion = "2019-06-01"; } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, host, apiVersion, subscriptionId); return client; }
}
public StorageManagementClient buildClient() { if (endpoint == null) { this.endpoint = "https: } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, subscriptionId, endpoint); return client; }
class StorageManagementClientBuilder { /* * The ID of the target subscription. */ private String subscriptionId; /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder subscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /* * server parameter */ private String host; /** * Sets server parameter. * * @param host the host value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder host(String host) { this.host = host; return this; } /* * Api Version */ private String apiVersion; /* * The environment to connect to */ private AzureEnvironment environment; /** * Sets The environment to connect to. * * @param environment the environment value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder environment(AzureEnvironment environment) { this.environment = environment; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of StorageManagementClient with the provided parameters. * * @return an instance of StorageManagementClient. */ }
class StorageManagementClientBuilder { /* * The ID of the target subscription. */ private String subscriptionId; /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder subscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /* * server parameter */ private String endpoint; /** * Sets server parameter. * * @param endpoint the endpoint value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * The environment to connect to */ private AzureEnvironment environment; /** * Sets The environment to connect to. * * @param environment the environment value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder environment(AzureEnvironment environment) { this.environment = environment; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of StorageManagementClient with the provided parameters. * * @return an instance of StorageManagementClient. */ }
I guess it is in swagger as well https://github.com/Azure/azure-rest-api-specs/blob/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/blob.json#L8 I will see if I can rename it in generator for mgmt.
public StorageManagementClient buildClient() { if (host == null) { this.host = "https: } if (apiVersion == null) { this.apiVersion = "2019-06-01"; } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, host, apiVersion, subscriptionId); return client; }
this.host = "https:
public StorageManagementClient buildClient() { if (endpoint == null) { this.endpoint = "https: } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, subscriptionId, endpoint); return client; }
class StorageManagementClientBuilder { /* * The ID of the target subscription. */ private String subscriptionId; /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder subscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /* * server parameter */ private String host; /** * Sets server parameter. * * @param host the host value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder host(String host) { this.host = host; return this; } /* * Api Version */ private String apiVersion; /* * The environment to connect to */ private AzureEnvironment environment; /** * Sets The environment to connect to. * * @param environment the environment value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder environment(AzureEnvironment environment) { this.environment = environment; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of StorageManagementClient with the provided parameters. * * @return an instance of StorageManagementClient. */ }
class StorageManagementClientBuilder { /* * The ID of the target subscription. */ private String subscriptionId; /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder subscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /* * server parameter */ private String endpoint; /** * Sets server parameter. * * @param endpoint the endpoint value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * The environment to connect to */ private AzureEnvironment environment; /** * Sets The environment to connect to. * * @param environment the environment value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder environment(AzureEnvironment environment) { this.environment = environment; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of StorageManagementClient with the provided parameters. * * @return an instance of StorageManagementClient. */ }
I will try to address it when tweaking generator.
public StorageManagementClient buildClient() { if (host == null) { this.host = "https: } if (apiVersion == null) { this.apiVersion = "2019-06-01"; } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, host, apiVersion, subscriptionId); return client; }
}
public StorageManagementClient buildClient() { if (endpoint == null) { this.endpoint = "https: } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, subscriptionId, endpoint); return client; }
class StorageManagementClientBuilder { /* * The ID of the target subscription. */ private String subscriptionId; /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder subscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /* * server parameter */ private String host; /** * Sets server parameter. * * @param host the host value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder host(String host) { this.host = host; return this; } /* * Api Version */ private String apiVersion; /* * The environment to connect to */ private AzureEnvironment environment; /** * Sets The environment to connect to. * * @param environment the environment value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder environment(AzureEnvironment environment) { this.environment = environment; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of StorageManagementClient with the provided parameters. * * @return an instance of StorageManagementClient. */ }
class StorageManagementClientBuilder { /* * The ID of the target subscription. */ private String subscriptionId; /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder subscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /* * server parameter */ private String endpoint; /** * Sets server parameter. * * @param endpoint the endpoint value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /* * The environment to connect to */ private AzureEnvironment environment; /** * Sets The environment to connect to. * * @param environment the environment value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder environment(AzureEnvironment environment) { this.environment = environment; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the StorageManagementClientBuilder. */ public StorageManagementClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of StorageManagementClient with the provided parameters. * * @return an instance of StorageManagementClient. */ }
why?
public void queryDistinctDocuments() { List<String> queries = Arrays.asList( "SELECT %s VALUE null", "SELECT %s VALUE false", "SELECT %s VALUE true", "SELECT %s VALUE 1", "SELECT %s VALUE 'a'", "SELECT %s VALUE [null, true, false, 1, 'a']", "SELECT %s false AS p", "SELECT %s 1 AS p", "SELECT %s 'a' AS p", "SELECT %s VALUE null FROM c", "SELECT %s VALUE false FROM c", "SELECT %s VALUE 1 FROM c", "SELECT %s VALUE 'a' FROM c", "SELECT %s null AS p FROM c", "SELECT %s false AS p FROM c", "SELECT %s 1 AS p FROM c", "SELECT %s 'a' AS p FROM c", "SELECT %s VALUE c.income from c", "SELECT %s VALUE c.age from c", "SELECT %s c.income, c.income AS income2 from c", "SELECT %s c.income, c.age from c", "SELECT %s c.name from c", "SELECT %s VALUE c.city from c", "SELECT %s c.name, c.name AS name2 from c", "SELECT %s c.name, c.city from c", "SELECT %s c.children from c", "SELECT %s c.children, c.children AS children2 from c", "SELECT %s VALUE c.pet from c", "SELECT %s c.pet, c.pet AS pet2 from c", "SELECT %s VALUE ABS(c.age) FROM c", "SELECT %s VALUE LEFT(c.name, 1) FROM c", "SELECT %s VALUE c.name || ', ' || (c.city ?? '') FROM c", "SELECT %s VALUE ARRAY_LENGTH(c.children) FROM c", "SELECT %s VALUE IS_DEFINED(c.city) FROM c", "SELECT %s VALUE (c.children[0].age ?? 0) + (c.children[1].age ?? 0) FROM c", "SELECT %s c.name FROM c ORDER BY c.name ASC", "SELECT %s c.age FROM c ORDER BY c.age", "SELECT %s c.city FROM c ORDER BY c.city", "SELECT %s c.city FROM c ORDER BY c.age", "SELECT %s LEFT(c.name, 1) FROM c ORDER BY c.name", "SELECT %s TOP 2147483647 VALUE c.age FROM c", "SELECT %s TOP 2147483647 c.age FROM c ORDER BY c.age", "SELECT %s VALUE MAX(c.age) FROM c", "SELECT %s VALUE c.age FROM p JOIN c IN p.children", "SELECT %s p.age AS ParentAge, c.age ChildAge FROM p JOIN c IN p.children", "SELECT %s VALUE c.name FROM p JOIN c IN p.children", "SELECT %s p.name AS ParentName, c.name ChildName FROM p JOIN c IN p.children", "SELECT %s r.age, s FROM r JOIN (SELECT DISTINCT VALUE c FROM (SELECT 1 a) c) s WHERE r.age > 25", "SELECT %s p.name, p.age FROM (SELECT DISTINCT * FROM r) p WHERE p.age > 25", "SELECT %s p.name, (SELECT DISTINCT VALUE p.age) AS Age FROM p", "SELECT %s p.name, p.age FROM p WHERE (SELECT DISTINCT VALUE LEFT(p.name, 1)) > 'A' AND (SELECT " + "DISTINCT VALUE p.age) > 21", "SELECT %s p.name, (SELECT DISTINCT VALUE p.age) AS Age FROM p WHERE (SELECT DISTINCT VALUE p.name) >" + " 'A' OR (SELECT DISTINCT VALUE p.age) > 21", "SELECT %s * FROM c" ); for (String query : queries) { logger.info("Current distinct query: " + query); FeedOptions options = new FeedOptions(); options.setMaxDegreeOfParallelism(2); List<JsonNode> documentsFromWithDistinct = new ArrayList<>(); List<JsonNode> documentsFromWithoutDistinct = new ArrayList<>(); final String queryWithDistinct = String.format(query, "DISTINCT"); final String queryWithoutDistinct = String.format(query, ""); CosmosPagedFlux<JsonNode> queryObservable = createdCollection.queryItems(queryWithoutDistinct, options, JsonNode.class); Iterator<FeedResponse<JsonNode>> iterator = queryObservable.byPage().toIterable().iterator(); Utils.ValueHolder<String> outHash = new Utils.ValueHolder<>(); UnorderedDistinctMap distinctMap = new UnorderedDistinctMap(); /* while (iterator.hasNext()) { FeedResponse<JsonNode> next = iterator.next(); for (JsonNode document : next.getResults()) { if (distinctMap.add(document, outHash)) { documentsFromWithoutDistinct.add(document); } } } */ CosmosPagedFlux<JsonNode> queryObservableWithDistinct = createdCollection .queryItems(queryWithDistinct, options, JsonNode.class); iterator = queryObservableWithDistinct.byPage(5).toIterable().iterator(); while (iterator.hasNext()) { FeedResponse<JsonNode> next = iterator.next(); documentsFromWithDistinct.addAll(next.getResults()); } assertThat(documentsFromWithDistinct.size()).isGreaterThanOrEqualTo(1); } }
public void queryDistinctDocuments() { List<String> queries = Arrays.asList( "SELECT %s VALUE null", "SELECT %s VALUE false", "SELECT %s VALUE true", "SELECT %s VALUE 1", "SELECT %s VALUE 'a'", "SELECT %s VALUE [null, true, false, 1, 'a']", "SELECT %s false AS p", "SELECT %s 1 AS p", "SELECT %s 'a' AS p", "SELECT %s VALUE null FROM c", "SELECT %s VALUE false FROM c", "SELECT %s VALUE 1 FROM c", "SELECT %s VALUE 'a' FROM c", "SELECT %s null AS p FROM c", "SELECT %s false AS p FROM c", "SELECT %s 1 AS p FROM c", "SELECT %s 'a' AS p FROM c", "SELECT %s VALUE c.income from c", "SELECT %s VALUE c.age from c", "SELECT %s c.income, c.income AS income2 from c", "SELECT %s c.income, c.age from c", "SELECT %s c.name from c", "SELECT %s VALUE c.city from c", "SELECT %s c.name, c.name AS name2 from c", "SELECT %s c.name, c.city from c", "SELECT %s c.children from c", "SELECT %s c.children, c.children AS children2 from c", "SELECT %s VALUE c.pet from c", "SELECT %s c.pet, c.pet AS pet2 from c", "SELECT %s VALUE ABS(c.age) FROM c", "SELECT %s VALUE LEFT(c.name, 1) FROM c", "SELECT %s VALUE c.name || ', ' || (c.city ?? '') FROM c", "SELECT %s VALUE ARRAY_LENGTH(c.children) FROM c", "SELECT %s VALUE IS_DEFINED(c.city) FROM c", "SELECT %s VALUE (c.children[0].age ?? 0) + (c.children[1].age ?? 0) FROM c", "SELECT %s c.name FROM c ORDER BY c.name ASC", "SELECT %s c.age FROM c ORDER BY c.age", "SELECT %s c.city FROM c ORDER BY c.city", "SELECT %s c.city FROM c ORDER BY c.age", "SELECT %s LEFT(c.name, 1) FROM c ORDER BY c.name", "SELECT %s TOP 2147483647 VALUE c.age FROM c", "SELECT %s TOP 2147483647 c.age FROM c ORDER BY c.age", "SELECT %s VALUE MAX(c.age) FROM c", "SELECT %s VALUE c.age FROM p JOIN c IN p.children", "SELECT %s p.age AS ParentAge, c.age ChildAge FROM p JOIN c IN p.children", "SELECT %s VALUE c.name FROM p JOIN c IN p.children", "SELECT %s p.name AS ParentName, c.name ChildName FROM p JOIN c IN p.children", "SELECT %s r.age, s FROM r JOIN (SELECT DISTINCT VALUE c FROM (SELECT 1 a) c) s WHERE r.age > 25", "SELECT %s p.name, p.age FROM (SELECT DISTINCT * FROM r) p WHERE p.age > 25", "SELECT %s p.name, (SELECT DISTINCT VALUE p.age) AS Age FROM p", "SELECT %s p.name, p.age FROM p WHERE (SELECT DISTINCT VALUE LEFT(p.name, 1)) > 'A' AND (SELECT " + "DISTINCT VALUE p.age) > 21", "SELECT %s p.name, (SELECT DISTINCT VALUE p.age) AS Age FROM p WHERE (SELECT DISTINCT VALUE p.name) >" + " 'A' OR (SELECT DISTINCT VALUE p.age) > 21", "SELECT %s * FROM c" ); for (String query : queries) { logger.info("Current distinct query: " + query); FeedOptions options = new FeedOptions(); options.setMaxDegreeOfParallelism(2); List<JsonNode> documentsFromWithDistinct = new ArrayList<>(); List<JsonNode> documentsFromWithoutDistinct = new ArrayList<>(); final String queryWithDistinct = String.format(query, "DISTINCT"); final String queryWithoutDistinct = String.format(query, ""); CosmosPagedFlux<JsonNode> queryObservable = createdCollection.queryItems(queryWithoutDistinct, options, JsonNode.class); Iterator<FeedResponse<JsonNode>> iterator = queryObservable.byPage().toIterable().iterator(); Utils.ValueHolder<String> outHash = new Utils.ValueHolder<>(); UnorderedDistinctMap distinctMap = new UnorderedDistinctMap(); /* while (iterator.hasNext()) { FeedResponse<JsonNode> next = iterator.next(); for (JsonNode document : next.getResults()) { if (distinctMap.add(document, outHash)) { documentsFromWithoutDistinct.add(document); } } } */ CosmosPagedFlux<JsonNode> queryObservableWithDistinct = createdCollection .queryItems(queryWithDistinct, options, JsonNode.class); iterator = queryObservableWithDistinct.byPage(5).toIterable().iterator(); while (iterator.hasNext()) { FeedResponse<JsonNode> next = iterator.next(); documentsFromWithDistinct.addAll(next.getResults()); } assertThat(documentsFromWithDistinct.size()).isGreaterThanOrEqualTo(1); } }
class DistinctQueryTests extends TestSuiteBase { private final int TIMEOUT_120 = 120000; private final String FIELD = "name"; private CosmosAsyncContainer createdCollection; private ArrayList<CosmosItemProperties> docs = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuildersWithDirect") public DistinctQueryTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); } private static String getRandomName(Random rand) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("name_" + rand.nextInt(100)); return stringBuilder.toString(); } private static City getRandomCity(Random rand) { int index = rand.nextInt(3); switch (index) { case 0: return City.LOS_ANGELES; case 1: return City.NEW_YORK; case 2: return City.SEATTLE; } return City.LOS_ANGELES; } private static double getRandomIncome(Random rand) { return rand.nextDouble() * Double.MAX_VALUE; } private static int getRandomAge(Random rand) { return rand.nextInt(100); } @Test(groups = {"simple"}, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocuments(boolean qmEnabled) { String query = "SELECT DISTINCT c.name from c"; FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<CosmosItemProperties> queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); List<Object> nameList = docs.stream() .map(d -> ModelBridgeInternal.getObjectFromJsonSerializable(d, FIELD)) .collect(Collectors.toList()); List<Object> distinctNameList = nameList.stream().distinct().collect(Collectors.toList()); FeedResponseListValidator<CosmosItemProperties> validator = new FeedResponseListValidator.Builder<CosmosItemProperties>() .totalSize(distinctNameList.size()) .allPagesSatisfy(new FeedResponseValidator.Builder<CosmosItemProperties>() .requestChargeGreaterThanOrEqualTo(1.0) .build()) .hasValidQueryMetrics(qmEnabled) .build(); validateQuerySuccess(queryObservable.byPage(5), validator, TIMEOUT); } @Test(groups = {"simple"}, timeOut = TIMEOUT_120) @Test(groups = {"simple"}, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocumentsForDistinctIntValues(boolean qmEnabled) { String query = "SELECT DISTINCT c.intprop from c"; FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<CosmosItemProperties> queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); Iterator<FeedResponse<CosmosItemProperties>> iterator = queryObservable.byPage(5).collectList().single().block() .iterator(); List<CosmosItemProperties> itemPropertiesList = new ArrayList<>(); while (iterator.hasNext()) { FeedResponse<CosmosItemProperties> next = iterator.next(); itemPropertiesList.addAll(next.getResults()); } assertThat(itemPropertiesList.size()).isEqualTo(2); List<Object> intpropList = itemPropertiesList .stream() .map(cosmosItemProperties -> ModelBridgeInternal.getObjectFromJsonSerializable( cosmosItemProperties, "intprop")) .collect(Collectors.toList()); assertThat(intpropList).containsExactlyInAnyOrder(null, 5); } public void bulkInsert() { generateTestData(); voidBulkInsertBlocking(createdCollection, docs); } public void generateTestData() { Random rand = new Random(); ObjectMapper mapper = new ObjectMapper(); for (int i = 0; i < 40; i++) { Person person = getRandomPerson(rand); try { docs.add(new CosmosItemProperties(mapper.writeValueAsString(person))); } catch (JsonProcessingException e) { logger.error(e.getMessage()); } } String resourceJson = String.format("{ " + "\"id\": \"%s\", \"intprop\": %d }", UUID.randomUUID().toString(), 5); String resourceJson2 = String.format("{ " + "\"id\": \"%s\", \"intprop\": %f }", UUID.randomUUID().toString(), 5.0f); docs.add(new CosmosItemProperties(resourceJson)); docs.add(new CosmosItemProperties(resourceJson2)); } private Pet getRandomPet(Random rand) { String name = getRandomName(rand); int age = getRandomAge(rand); return new Pet(name, age); } public Person getRandomPerson(Random rand) { String name = getRandomName(rand); City city = getRandomCity(rand); double income = getRandomIncome(rand); List<Person> people = new ArrayList<Person>(); if (rand.nextInt(10) % 10 == 0) { for (int i = 0; i < rand.nextInt(5); i++) { people.add(getRandomPerson(rand)); } } int age = getRandomAge(rand); Pet pet = getRandomPet(rand); UUID guid = UUID.randomUUID(); Person p = new Person(name, city, income, people, age, pet, guid); return p; } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } @BeforeClass(groups = {"simple"}, timeOut = 3 * SETUP_TIMEOUT) public void beforeClass() throws Exception { client = this.getClientBuilder().buildAsyncClient(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); bulkInsert(); waitIfNeededForReplicasToCatchUp(this.getClientBuilder()); } public enum City { NEW_YORK, LOS_ANGELES, SEATTLE } public final class Pet extends JsonSerializable { @JsonProperty("name") public String name; @JsonProperty("age") public int age; public Pet(String name, int age) { this.name = name; this.age = age; } } public final class Person extends JsonSerializable { @JsonProperty("name") public String name; @JsonProperty("id") public String id; @JsonProperty("city") public City city; @JsonProperty("income") public double income; @JsonProperty("children") public List<Person> children; @JsonProperty("age") public int age; @JsonProperty("pet") public Pet pet; @JsonProperty("guid") public UUID guid; public Person(String name, City city, double income, List<Person> children, int age, Pet pet, UUID guid) { this.name = name; this.city = city; this.income = income; this.children = children; this.age = age; this.pet = pet; this.guid = guid; this.id = UUID.randomUUID().toString(); } } }
class DistinctQueryTests extends TestSuiteBase { private final int TIMEOUT_120 = 120000; private final String FIELD = "name"; private CosmosAsyncContainer createdCollection; private ArrayList<CosmosItemProperties> docs = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuildersWithDirect") public DistinctQueryTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); } private static String getRandomName(Random rand) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("name_" + rand.nextInt(100)); return stringBuilder.toString(); } private static City getRandomCity(Random rand) { int index = rand.nextInt(3); switch (index) { case 0: return City.LOS_ANGELES; case 1: return City.NEW_YORK; case 2: return City.SEATTLE; } return City.LOS_ANGELES; } private static double getRandomIncome(Random rand) { return rand.nextDouble() * Double.MAX_VALUE; } private static int getRandomAge(Random rand) { return rand.nextInt(100); } @Test(groups = {"simple"}, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocuments(boolean qmEnabled) { String query = "SELECT DISTINCT c.name from c"; FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<CosmosItemProperties> queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); List<Object> nameList = docs.stream() .map(d -> ModelBridgeInternal.getObjectFromJsonSerializable(d, FIELD)) .collect(Collectors.toList()); List<Object> distinctNameList = nameList.stream().distinct().collect(Collectors.toList()); FeedResponseListValidator<CosmosItemProperties> validator = new FeedResponseListValidator.Builder<CosmosItemProperties>() .totalSize(distinctNameList.size()) .allPagesSatisfy(new FeedResponseValidator.Builder<CosmosItemProperties>() .requestChargeGreaterThanOrEqualTo(1.0) .build()) .hasValidQueryMetrics(qmEnabled) .build(); validateQuerySuccess(queryObservable.byPage(5), validator, TIMEOUT); } @Test(groups = {"simple"}, timeOut = TIMEOUT_120) @Test(groups = {"simple"}, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocumentsForDistinctIntValues(boolean qmEnabled) { String query = "SELECT DISTINCT c.intprop from c"; FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<CosmosItemProperties> queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); Iterator<FeedResponse<CosmosItemProperties>> iterator = queryObservable.byPage(5).collectList().single().block() .iterator(); List<CosmosItemProperties> itemPropertiesList = new ArrayList<>(); while (iterator.hasNext()) { FeedResponse<CosmosItemProperties> next = iterator.next(); itemPropertiesList.addAll(next.getResults()); } assertThat(itemPropertiesList.size()).isEqualTo(2); List<Object> intpropList = itemPropertiesList .stream() .map(cosmosItemProperties -> ModelBridgeInternal.getObjectFromJsonSerializable( cosmosItemProperties, "intprop")) .collect(Collectors.toList()); assertThat(intpropList).containsExactlyInAnyOrder(null, 5); } public void bulkInsert() { generateTestData(); voidBulkInsertBlocking(createdCollection, docs); } public void generateTestData() { Random rand = new Random(); ObjectMapper mapper = new ObjectMapper(); for (int i = 0; i < 40; i++) { Person person = getRandomPerson(rand); try { docs.add(new CosmosItemProperties(mapper.writeValueAsString(person))); } catch (JsonProcessingException e) { logger.error(e.getMessage()); } } String resourceJson = String.format("{ " + "\"id\": \"%s\", \"intprop\": %d }", UUID.randomUUID().toString(), 5); String resourceJson2 = String.format("{ " + "\"id\": \"%s\", \"intprop\": %f }", UUID.randomUUID().toString(), 5.0f); docs.add(new CosmosItemProperties(resourceJson)); docs.add(new CosmosItemProperties(resourceJson2)); } private Pet getRandomPet(Random rand) { String name = getRandomName(rand); int age = getRandomAge(rand); return new Pet(name, age); } public Person getRandomPerson(Random rand) { String name = getRandomName(rand); City city = getRandomCity(rand); double income = getRandomIncome(rand); List<Person> people = new ArrayList<Person>(); if (rand.nextInt(10) % 10 == 0) { for (int i = 0; i < rand.nextInt(5); i++) { people.add(getRandomPerson(rand)); } } int age = getRandomAge(rand); Pet pet = getRandomPet(rand); UUID guid = UUID.randomUUID(); Person p = new Person(name, city, income, people, age, pet, guid); return p; } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } @BeforeClass(groups = {"simple"}, timeOut = 3 * SETUP_TIMEOUT) public void beforeClass() throws Exception { client = this.getClientBuilder().buildAsyncClient(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); bulkInsert(); waitIfNeededForReplicasToCatchUp(this.getClientBuilder()); } public enum City { NEW_YORK, LOS_ANGELES, SEATTLE } public final class Pet extends JsonSerializable { @JsonProperty("name") public String name; @JsonProperty("age") public int age; public Pet(String name, int age) { this.name = name; this.age = age; } } public final class Person extends JsonSerializable { @JsonProperty("name") public String name; @JsonProperty("id") public String id; @JsonProperty("city") public City city; @JsonProperty("income") public double income; @JsonProperty("children") public List<Person> children; @JsonProperty("age") public int age; @JsonProperty("pet") public Pet pet; @JsonProperty("guid") public UUID guid; public Person(String name, City city, double income, List<Person> children, int age, Pet pet, UUID guid) { this.name = name; this.city = city; this.income = income; this.children = children; this.age = age; this.pet = pet; this.guid = guid; this.id = UUID.randomUUID().toString(); } } }
since you're changing the name of layoutPageResults -> contentPageResults, I think it's a good idea to change recognizeLayoutPoller -> recognizeContentPoller
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/" + "forms/layout1.jpg"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<OperationResult, List<FormPage>> recognizeLayoutPoller = client.beginRecognizeContent(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG); List<FormPage> contentPageResults = recognizeLayoutPoller.getFinalResult(); for (int i = 0; i < contentPageResults.size(); i++) { final FormPage formPage = contentPageResults.get(i); System.out.printf("----Recognizing content for page %s ----", i); System.out.printf("Has width: %s and height: %s, measured with unit: %s%n", formPage.getWidth(), formPage.getHeight(), formPage.getUnit()); formPage.getTables().forEach(formTable -> { System.out.printf("Table has %s rows and %s columns.%n", formTable.getRowCount(), formTable.getColumnCount()); formTable.getCells().forEach(formTableCell -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formTableCell.getBoundingBox() != null) { formTableCell.getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Cell has text %s, within bounding box %s.%n", formTableCell.getText(), boundingBoxStr); }); System.out.println(); }); } }
List<FormPage> contentPageResults = recognizeLayoutPoller.getFinalResult();
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https: .buildClient(); File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/" + "forms/layout1.jpg"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<OperationResult, List<FormPage>> recognizeContentPoller = client.beginRecognizeContent(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG); List<FormPage> contentPageResults = recognizeContentPoller.getFinalResult(); for (int i = 0; i < contentPageResults.size(); i++) { final FormPage formPage = contentPageResults.get(i); System.out.printf("----Recognizing content for page %s ----", i); System.out.printf("Has width: %s and height: %s, measured with unit: %s%n", formPage.getWidth(), formPage.getHeight(), formPage.getUnit()); final List<FormTable> tables = formPage.getTables(); for (int i1 = 0; i1 < tables.size(); i1++) { final FormTable formTable = tables.get(i1); System.out.printf("Table %s has %s rows and %s columns.%n", i1, formTable.getRowCount(), formTable.getColumnCount()); formTable.getCells().forEach(formTableCell -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formTableCell.getBoundingBox() != null) { formTableCell.getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Cell has text %s, within bounding box %s.%n", formTableCell.getText(), boundingBoxStr); }); System.out.println(); } } }
class RecognizeContent { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
class RecognizeContent { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ }
I actually added the reason a bit above than this assert as to why I have to lower the checks. // Weakening validation in this PR as distinctMap has to be changed to accept types not extending from Resource. This will be enabled in a different PR which is already actively in wip. I will discuss in more detail offline.
public void queryDistinctDocuments() { List<String> queries = Arrays.asList( "SELECT %s VALUE null", "SELECT %s VALUE false", "SELECT %s VALUE true", "SELECT %s VALUE 1", "SELECT %s VALUE 'a'", "SELECT %s VALUE [null, true, false, 1, 'a']", "SELECT %s false AS p", "SELECT %s 1 AS p", "SELECT %s 'a' AS p", "SELECT %s VALUE null FROM c", "SELECT %s VALUE false FROM c", "SELECT %s VALUE 1 FROM c", "SELECT %s VALUE 'a' FROM c", "SELECT %s null AS p FROM c", "SELECT %s false AS p FROM c", "SELECT %s 1 AS p FROM c", "SELECT %s 'a' AS p FROM c", "SELECT %s VALUE c.income from c", "SELECT %s VALUE c.age from c", "SELECT %s c.income, c.income AS income2 from c", "SELECT %s c.income, c.age from c", "SELECT %s c.name from c", "SELECT %s VALUE c.city from c", "SELECT %s c.name, c.name AS name2 from c", "SELECT %s c.name, c.city from c", "SELECT %s c.children from c", "SELECT %s c.children, c.children AS children2 from c", "SELECT %s VALUE c.pet from c", "SELECT %s c.pet, c.pet AS pet2 from c", "SELECT %s VALUE ABS(c.age) FROM c", "SELECT %s VALUE LEFT(c.name, 1) FROM c", "SELECT %s VALUE c.name || ', ' || (c.city ?? '') FROM c", "SELECT %s VALUE ARRAY_LENGTH(c.children) FROM c", "SELECT %s VALUE IS_DEFINED(c.city) FROM c", "SELECT %s VALUE (c.children[0].age ?? 0) + (c.children[1].age ?? 0) FROM c", "SELECT %s c.name FROM c ORDER BY c.name ASC", "SELECT %s c.age FROM c ORDER BY c.age", "SELECT %s c.city FROM c ORDER BY c.city", "SELECT %s c.city FROM c ORDER BY c.age", "SELECT %s LEFT(c.name, 1) FROM c ORDER BY c.name", "SELECT %s TOP 2147483647 VALUE c.age FROM c", "SELECT %s TOP 2147483647 c.age FROM c ORDER BY c.age", "SELECT %s VALUE MAX(c.age) FROM c", "SELECT %s VALUE c.age FROM p JOIN c IN p.children", "SELECT %s p.age AS ParentAge, c.age ChildAge FROM p JOIN c IN p.children", "SELECT %s VALUE c.name FROM p JOIN c IN p.children", "SELECT %s p.name AS ParentName, c.name ChildName FROM p JOIN c IN p.children", "SELECT %s r.age, s FROM r JOIN (SELECT DISTINCT VALUE c FROM (SELECT 1 a) c) s WHERE r.age > 25", "SELECT %s p.name, p.age FROM (SELECT DISTINCT * FROM r) p WHERE p.age > 25", "SELECT %s p.name, (SELECT DISTINCT VALUE p.age) AS Age FROM p", "SELECT %s p.name, p.age FROM p WHERE (SELECT DISTINCT VALUE LEFT(p.name, 1)) > 'A' AND (SELECT " + "DISTINCT VALUE p.age) > 21", "SELECT %s p.name, (SELECT DISTINCT VALUE p.age) AS Age FROM p WHERE (SELECT DISTINCT VALUE p.name) >" + " 'A' OR (SELECT DISTINCT VALUE p.age) > 21", "SELECT %s * FROM c" ); for (String query : queries) { logger.info("Current distinct query: " + query); FeedOptions options = new FeedOptions(); options.setMaxDegreeOfParallelism(2); List<JsonNode> documentsFromWithDistinct = new ArrayList<>(); List<JsonNode> documentsFromWithoutDistinct = new ArrayList<>(); final String queryWithDistinct = String.format(query, "DISTINCT"); final String queryWithoutDistinct = String.format(query, ""); CosmosPagedFlux<JsonNode> queryObservable = createdCollection.queryItems(queryWithoutDistinct, options, JsonNode.class); Iterator<FeedResponse<JsonNode>> iterator = queryObservable.byPage().toIterable().iterator(); Utils.ValueHolder<String> outHash = new Utils.ValueHolder<>(); UnorderedDistinctMap distinctMap = new UnorderedDistinctMap(); /* while (iterator.hasNext()) { FeedResponse<JsonNode> next = iterator.next(); for (JsonNode document : next.getResults()) { if (distinctMap.add(document, outHash)) { documentsFromWithoutDistinct.add(document); } } } */ CosmosPagedFlux<JsonNode> queryObservableWithDistinct = createdCollection .queryItems(queryWithDistinct, options, JsonNode.class); iterator = queryObservableWithDistinct.byPage(5).toIterable().iterator(); while (iterator.hasNext()) { FeedResponse<JsonNode> next = iterator.next(); documentsFromWithDistinct.addAll(next.getResults()); } assertThat(documentsFromWithDistinct.size()).isGreaterThanOrEqualTo(1); } }
public void queryDistinctDocuments() { List<String> queries = Arrays.asList( "SELECT %s VALUE null", "SELECT %s VALUE false", "SELECT %s VALUE true", "SELECT %s VALUE 1", "SELECT %s VALUE 'a'", "SELECT %s VALUE [null, true, false, 1, 'a']", "SELECT %s false AS p", "SELECT %s 1 AS p", "SELECT %s 'a' AS p", "SELECT %s VALUE null FROM c", "SELECT %s VALUE false FROM c", "SELECT %s VALUE 1 FROM c", "SELECT %s VALUE 'a' FROM c", "SELECT %s null AS p FROM c", "SELECT %s false AS p FROM c", "SELECT %s 1 AS p FROM c", "SELECT %s 'a' AS p FROM c", "SELECT %s VALUE c.income from c", "SELECT %s VALUE c.age from c", "SELECT %s c.income, c.income AS income2 from c", "SELECT %s c.income, c.age from c", "SELECT %s c.name from c", "SELECT %s VALUE c.city from c", "SELECT %s c.name, c.name AS name2 from c", "SELECT %s c.name, c.city from c", "SELECT %s c.children from c", "SELECT %s c.children, c.children AS children2 from c", "SELECT %s VALUE c.pet from c", "SELECT %s c.pet, c.pet AS pet2 from c", "SELECT %s VALUE ABS(c.age) FROM c", "SELECT %s VALUE LEFT(c.name, 1) FROM c", "SELECT %s VALUE c.name || ', ' || (c.city ?? '') FROM c", "SELECT %s VALUE ARRAY_LENGTH(c.children) FROM c", "SELECT %s VALUE IS_DEFINED(c.city) FROM c", "SELECT %s VALUE (c.children[0].age ?? 0) + (c.children[1].age ?? 0) FROM c", "SELECT %s c.name FROM c ORDER BY c.name ASC", "SELECT %s c.age FROM c ORDER BY c.age", "SELECT %s c.city FROM c ORDER BY c.city", "SELECT %s c.city FROM c ORDER BY c.age", "SELECT %s LEFT(c.name, 1) FROM c ORDER BY c.name", "SELECT %s TOP 2147483647 VALUE c.age FROM c", "SELECT %s TOP 2147483647 c.age FROM c ORDER BY c.age", "SELECT %s VALUE MAX(c.age) FROM c", "SELECT %s VALUE c.age FROM p JOIN c IN p.children", "SELECT %s p.age AS ParentAge, c.age ChildAge FROM p JOIN c IN p.children", "SELECT %s VALUE c.name FROM p JOIN c IN p.children", "SELECT %s p.name AS ParentName, c.name ChildName FROM p JOIN c IN p.children", "SELECT %s r.age, s FROM r JOIN (SELECT DISTINCT VALUE c FROM (SELECT 1 a) c) s WHERE r.age > 25", "SELECT %s p.name, p.age FROM (SELECT DISTINCT * FROM r) p WHERE p.age > 25", "SELECT %s p.name, (SELECT DISTINCT VALUE p.age) AS Age FROM p", "SELECT %s p.name, p.age FROM p WHERE (SELECT DISTINCT VALUE LEFT(p.name, 1)) > 'A' AND (SELECT " + "DISTINCT VALUE p.age) > 21", "SELECT %s p.name, (SELECT DISTINCT VALUE p.age) AS Age FROM p WHERE (SELECT DISTINCT VALUE p.name) >" + " 'A' OR (SELECT DISTINCT VALUE p.age) > 21", "SELECT %s * FROM c" ); for (String query : queries) { logger.info("Current distinct query: " + query); FeedOptions options = new FeedOptions(); options.setMaxDegreeOfParallelism(2); List<JsonNode> documentsFromWithDistinct = new ArrayList<>(); List<JsonNode> documentsFromWithoutDistinct = new ArrayList<>(); final String queryWithDistinct = String.format(query, "DISTINCT"); final String queryWithoutDistinct = String.format(query, ""); CosmosPagedFlux<JsonNode> queryObservable = createdCollection.queryItems(queryWithoutDistinct, options, JsonNode.class); Iterator<FeedResponse<JsonNode>> iterator = queryObservable.byPage().toIterable().iterator(); Utils.ValueHolder<String> outHash = new Utils.ValueHolder<>(); UnorderedDistinctMap distinctMap = new UnorderedDistinctMap(); /* while (iterator.hasNext()) { FeedResponse<JsonNode> next = iterator.next(); for (JsonNode document : next.getResults()) { if (distinctMap.add(document, outHash)) { documentsFromWithoutDistinct.add(document); } } } */ CosmosPagedFlux<JsonNode> queryObservableWithDistinct = createdCollection .queryItems(queryWithDistinct, options, JsonNode.class); iterator = queryObservableWithDistinct.byPage(5).toIterable().iterator(); while (iterator.hasNext()) { FeedResponse<JsonNode> next = iterator.next(); documentsFromWithDistinct.addAll(next.getResults()); } assertThat(documentsFromWithDistinct.size()).isGreaterThanOrEqualTo(1); } }
class DistinctQueryTests extends TestSuiteBase { private final int TIMEOUT_120 = 120000; private final String FIELD = "name"; private CosmosAsyncContainer createdCollection; private ArrayList<CosmosItemProperties> docs = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuildersWithDirect") public DistinctQueryTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); } private static String getRandomName(Random rand) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("name_" + rand.nextInt(100)); return stringBuilder.toString(); } private static City getRandomCity(Random rand) { int index = rand.nextInt(3); switch (index) { case 0: return City.LOS_ANGELES; case 1: return City.NEW_YORK; case 2: return City.SEATTLE; } return City.LOS_ANGELES; } private static double getRandomIncome(Random rand) { return rand.nextDouble() * Double.MAX_VALUE; } private static int getRandomAge(Random rand) { return rand.nextInt(100); } @Test(groups = {"simple"}, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocuments(boolean qmEnabled) { String query = "SELECT DISTINCT c.name from c"; FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<CosmosItemProperties> queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); List<Object> nameList = docs.stream() .map(d -> ModelBridgeInternal.getObjectFromJsonSerializable(d, FIELD)) .collect(Collectors.toList()); List<Object> distinctNameList = nameList.stream().distinct().collect(Collectors.toList()); FeedResponseListValidator<CosmosItemProperties> validator = new FeedResponseListValidator.Builder<CosmosItemProperties>() .totalSize(distinctNameList.size()) .allPagesSatisfy(new FeedResponseValidator.Builder<CosmosItemProperties>() .requestChargeGreaterThanOrEqualTo(1.0) .build()) .hasValidQueryMetrics(qmEnabled) .build(); validateQuerySuccess(queryObservable.byPage(5), validator, TIMEOUT); } @Test(groups = {"simple"}, timeOut = TIMEOUT_120) @Test(groups = {"simple"}, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocumentsForDistinctIntValues(boolean qmEnabled) { String query = "SELECT DISTINCT c.intprop from c"; FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<CosmosItemProperties> queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); Iterator<FeedResponse<CosmosItemProperties>> iterator = queryObservable.byPage(5).collectList().single().block() .iterator(); List<CosmosItemProperties> itemPropertiesList = new ArrayList<>(); while (iterator.hasNext()) { FeedResponse<CosmosItemProperties> next = iterator.next(); itemPropertiesList.addAll(next.getResults()); } assertThat(itemPropertiesList.size()).isEqualTo(2); List<Object> intpropList = itemPropertiesList .stream() .map(cosmosItemProperties -> ModelBridgeInternal.getObjectFromJsonSerializable( cosmosItemProperties, "intprop")) .collect(Collectors.toList()); assertThat(intpropList).containsExactlyInAnyOrder(null, 5); } public void bulkInsert() { generateTestData(); voidBulkInsertBlocking(createdCollection, docs); } public void generateTestData() { Random rand = new Random(); ObjectMapper mapper = new ObjectMapper(); for (int i = 0; i < 40; i++) { Person person = getRandomPerson(rand); try { docs.add(new CosmosItemProperties(mapper.writeValueAsString(person))); } catch (JsonProcessingException e) { logger.error(e.getMessage()); } } String resourceJson = String.format("{ " + "\"id\": \"%s\", \"intprop\": %d }", UUID.randomUUID().toString(), 5); String resourceJson2 = String.format("{ " + "\"id\": \"%s\", \"intprop\": %f }", UUID.randomUUID().toString(), 5.0f); docs.add(new CosmosItemProperties(resourceJson)); docs.add(new CosmosItemProperties(resourceJson2)); } private Pet getRandomPet(Random rand) { String name = getRandomName(rand); int age = getRandomAge(rand); return new Pet(name, age); } public Person getRandomPerson(Random rand) { String name = getRandomName(rand); City city = getRandomCity(rand); double income = getRandomIncome(rand); List<Person> people = new ArrayList<Person>(); if (rand.nextInt(10) % 10 == 0) { for (int i = 0; i < rand.nextInt(5); i++) { people.add(getRandomPerson(rand)); } } int age = getRandomAge(rand); Pet pet = getRandomPet(rand); UUID guid = UUID.randomUUID(); Person p = new Person(name, city, income, people, age, pet, guid); return p; } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } @BeforeClass(groups = {"simple"}, timeOut = 3 * SETUP_TIMEOUT) public void beforeClass() throws Exception { client = this.getClientBuilder().buildAsyncClient(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); bulkInsert(); waitIfNeededForReplicasToCatchUp(this.getClientBuilder()); } public enum City { NEW_YORK, LOS_ANGELES, SEATTLE } public final class Pet extends JsonSerializable { @JsonProperty("name") public String name; @JsonProperty("age") public int age; public Pet(String name, int age) { this.name = name; this.age = age; } } public final class Person extends JsonSerializable { @JsonProperty("name") public String name; @JsonProperty("id") public String id; @JsonProperty("city") public City city; @JsonProperty("income") public double income; @JsonProperty("children") public List<Person> children; @JsonProperty("age") public int age; @JsonProperty("pet") public Pet pet; @JsonProperty("guid") public UUID guid; public Person(String name, City city, double income, List<Person> children, int age, Pet pet, UUID guid) { this.name = name; this.city = city; this.income = income; this.children = children; this.age = age; this.pet = pet; this.guid = guid; this.id = UUID.randomUUID().toString(); } } }
class DistinctQueryTests extends TestSuiteBase { private final int TIMEOUT_120 = 120000; private final String FIELD = "name"; private CosmosAsyncContainer createdCollection; private ArrayList<CosmosItemProperties> docs = new ArrayList<>(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuildersWithDirect") public DistinctQueryTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); } private static String getRandomName(Random rand) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("name_" + rand.nextInt(100)); return stringBuilder.toString(); } private static City getRandomCity(Random rand) { int index = rand.nextInt(3); switch (index) { case 0: return City.LOS_ANGELES; case 1: return City.NEW_YORK; case 2: return City.SEATTLE; } return City.LOS_ANGELES; } private static double getRandomIncome(Random rand) { return rand.nextDouble() * Double.MAX_VALUE; } private static int getRandomAge(Random rand) { return rand.nextInt(100); } @Test(groups = {"simple"}, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocuments(boolean qmEnabled) { String query = "SELECT DISTINCT c.name from c"; FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<CosmosItemProperties> queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); List<Object> nameList = docs.stream() .map(d -> ModelBridgeInternal.getObjectFromJsonSerializable(d, FIELD)) .collect(Collectors.toList()); List<Object> distinctNameList = nameList.stream().distinct().collect(Collectors.toList()); FeedResponseListValidator<CosmosItemProperties> validator = new FeedResponseListValidator.Builder<CosmosItemProperties>() .totalSize(distinctNameList.size()) .allPagesSatisfy(new FeedResponseValidator.Builder<CosmosItemProperties>() .requestChargeGreaterThanOrEqualTo(1.0) .build()) .hasValidQueryMetrics(qmEnabled) .build(); validateQuerySuccess(queryObservable.byPage(5), validator, TIMEOUT); } @Test(groups = {"simple"}, timeOut = TIMEOUT_120) @Test(groups = {"simple"}, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocumentsForDistinctIntValues(boolean qmEnabled) { String query = "SELECT DISTINCT c.intprop from c"; FeedOptions options = new FeedOptions(); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); CosmosPagedFlux<CosmosItemProperties> queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); Iterator<FeedResponse<CosmosItemProperties>> iterator = queryObservable.byPage(5).collectList().single().block() .iterator(); List<CosmosItemProperties> itemPropertiesList = new ArrayList<>(); while (iterator.hasNext()) { FeedResponse<CosmosItemProperties> next = iterator.next(); itemPropertiesList.addAll(next.getResults()); } assertThat(itemPropertiesList.size()).isEqualTo(2); List<Object> intpropList = itemPropertiesList .stream() .map(cosmosItemProperties -> ModelBridgeInternal.getObjectFromJsonSerializable( cosmosItemProperties, "intprop")) .collect(Collectors.toList()); assertThat(intpropList).containsExactlyInAnyOrder(null, 5); } public void bulkInsert() { generateTestData(); voidBulkInsertBlocking(createdCollection, docs); } public void generateTestData() { Random rand = new Random(); ObjectMapper mapper = new ObjectMapper(); for (int i = 0; i < 40; i++) { Person person = getRandomPerson(rand); try { docs.add(new CosmosItemProperties(mapper.writeValueAsString(person))); } catch (JsonProcessingException e) { logger.error(e.getMessage()); } } String resourceJson = String.format("{ " + "\"id\": \"%s\", \"intprop\": %d }", UUID.randomUUID().toString(), 5); String resourceJson2 = String.format("{ " + "\"id\": \"%s\", \"intprop\": %f }", UUID.randomUUID().toString(), 5.0f); docs.add(new CosmosItemProperties(resourceJson)); docs.add(new CosmosItemProperties(resourceJson2)); } private Pet getRandomPet(Random rand) { String name = getRandomName(rand); int age = getRandomAge(rand); return new Pet(name, age); } public Person getRandomPerson(Random rand) { String name = getRandomName(rand); City city = getRandomCity(rand); double income = getRandomIncome(rand); List<Person> people = new ArrayList<Person>(); if (rand.nextInt(10) % 10 == 0) { for (int i = 0; i < rand.nextInt(5); i++) { people.add(getRandomPerson(rand)); } } int age = getRandomAge(rand); Pet pet = getRandomPet(rand); UUID guid = UUID.randomUUID(); Person p = new Person(name, city, income, people, age, pet, guid); return p; } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } @BeforeClass(groups = {"simple"}, timeOut = 3 * SETUP_TIMEOUT) public void beforeClass() throws Exception { client = this.getClientBuilder().buildAsyncClient(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); bulkInsert(); waitIfNeededForReplicasToCatchUp(this.getClientBuilder()); } public enum City { NEW_YORK, LOS_ANGELES, SEATTLE } public final class Pet extends JsonSerializable { @JsonProperty("name") public String name; @JsonProperty("age") public int age; public Pet(String name, int age) { this.name = name; this.age = age; } } public final class Person extends JsonSerializable { @JsonProperty("name") public String name; @JsonProperty("id") public String id; @JsonProperty("city") public City city; @JsonProperty("income") public double income; @JsonProperty("children") public List<Person> children; @JsonProperty("age") public int age; @JsonProperty("pet") public Pet pet; @JsonProperty("guid") public UUID guid; public Person(String name, City city, double income, List<Person> children, int age, Pet pet, UUID guid) { this.name = name; this.city = city; this.income = income; this.children = children; this.age = age; this.pet = pet; this.guid = guid; this.id = UUID.randomUUID().toString(); } } }
Redundant null check that catched in the code quality process. [ERROR] Redundant nullcheck of documentSentimentLabel, which is known to be non-null in com.azure.ai.textanalytics.AnalyzeSentimentAsyncClient.convertToAnalyzeSentimentResult(DocumentSentiment) [com.azure.ai.textanalytics.AnalyzeSentimentAsyncClient] Redundant null check at AnalyzeSentimentAsyncClient.java:[line 147] RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE [ERROR] Redundant nullcheck of sentenceSentimentLabel, which is known to be non-null in com.azure.ai.textanalytics.AnalyzeSentimentAsyncClient.lambda$convertToAnalyzeSentimentResult$9(SentenceSentiment) [com.azure.ai.textanalytics.AnalyzeSentimentAsyncClient] Redundant null check at AnalyzeSentimentAsyncClient.java:[line 161] RCN_REDUNDANT_NULLCHECK_OF_NONNULL_
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment) { final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores(); final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream() .map(sentenceSentiment -> { final SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getConfidenceScores(); return new SentenceSentiment(sentenceSentiment.getText(), sentenceSentiment.getSentiment().toString(), new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(), confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive())); }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map( warning -> new TextAnalyticsWarning(warning.getCode().toString(), warning.getMessage())).collect(Collectors.toList()); return new AnalyzeSentimentResult( documentSentiment.getId(), documentSentiment.getStatistics() == null ? null : toTextDocumentStatistics(documentSentiment.getStatistics()), null, new com.azure.ai.textanalytics.models.DocumentSentiment( documentSentiment.getSentiment().toString(), new SentimentConfidenceScores( confidenceScorePerLabel.getNegative(), confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive()), new IterableStream<>(sentenceSentiments), new IterableStream<>(warnings))); }
sentenceSentiment.getSentiment().toString(),
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment) { final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores(); final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream() .map(sentenceSentiment -> { final SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getConfidenceScores(); final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment(); return new SentenceSentiment(sentenceSentiment.getText(), sentenceSentimentValue == null ? null : sentenceSentimentValue.toString(), new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(), confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive())); }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map( warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning(warningCodeValue == null ? null : warningCodeValue.toString(), warning.getMessage()); }).collect(Collectors.toList()); final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment(); return new AnalyzeSentimentResult( documentSentiment.getId(), documentSentiment.getStatistics() == null ? null : toTextDocumentStatistics(documentSentiment.getStatistics()), null, new com.azure.ai.textanalytics.models.DocumentSentiment( documentSentimentValue == null ? null : documentSentimentValue.toString(), new SentimentConfidenceScores( confidenceScorePerLabel.getNegative(), confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive()), new IterableStream<>(sentenceSentiments), new IterableStream<>(warnings))); }
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param service The proxy service used to perform REST calls. */ AnalyzeSentimentAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatch(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> withContext(context -> getAnalyzedSentimentResponseInPage(documents, options, context)).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return The {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> getAnalyzedSentimentResponseInPage(documents, options, context).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper method to convert the service response of {@link SentimentResponse} to {@link TextAnalyticsPagedResponse} * of {@link AnalyzeSentimentResult}. * * @param response The {@link SimpleResponse} of {@link SentimentResponse} returned by the service. * * @return The {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult} returned by the SDK. */ private TextAnalyticsPagedResponse<AnalyzeSentimentResult> toTextAnalyticsPagedResponse( SimpleResponse<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment)); } for (DocumentError documentError : sentimentResponse.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new TextAnalyticsPagedResponse<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), analyzeSentimentResults, null, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics())); } /** * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. * * @param documentSentiment The {@link DocumentSentiment} returned by the service. * * @return The {@link AnalyzeSentimentResult} to be returned by the SDK. */ /** * Call the service with REST response, convert to a {@link Mono} of {@link TextAnalyticsPagedResponse} of * {@link AnalyzeSentimentResult} from a {@link SimpleResponse} of {@link SentimentResponse}. * * @param documents A list of documents to be analyzed. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A {@link Mono} of {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult}. */ private Mono<TextAnalyticsPagedResponse<AnalyzeSentimentResult>> getAnalyzedSentimentResponseInPage( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.sentimentWithResponseAsync( new MultiLanguageBatchInput().setDocuments(Transforms.toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Analyzed sentiment for a batch of documents - {}", response)) .doOnError(error -> logger.warning("Failed to analyze sentiment - {}", error)) .map(this::toTextAnalyticsPagedResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param service The proxy service used to perform REST calls. */ AnalyzeSentimentAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatch(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> withContext(context -> getAnalyzedSentimentResponseInPage(documents, options, context)).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return The {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> getAnalyzedSentimentResponseInPage(documents, options, context).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper method to convert the service response of {@link SentimentResponse} to {@link TextAnalyticsPagedResponse} * of {@link AnalyzeSentimentResult}. * * @param response The {@link SimpleResponse} of {@link SentimentResponse} returned by the service. * * @return The {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult} returned by the SDK. */ private TextAnalyticsPagedResponse<AnalyzeSentimentResult> toTextAnalyticsPagedResponse( SimpleResponse<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment)); } for (DocumentError documentError : sentimentResponse.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new TextAnalyticsPagedResponse<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), analyzeSentimentResults, null, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics())); } /** * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. * * @param documentSentiment The {@link DocumentSentiment} returned by the service. * * @return The {@link AnalyzeSentimentResult} to be returned by the SDK. */ /** * Call the service with REST response, convert to a {@link Mono} of {@link TextAnalyticsPagedResponse} of * {@link AnalyzeSentimentResult} from a {@link SimpleResponse} of {@link SentimentResponse}. * * @param documents A list of documents to be analyzed. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A {@link Mono} of {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult}. */ private Mono<TextAnalyticsPagedResponse<AnalyzeSentimentResult>> getAnalyzedSentimentResponseInPage( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.sentimentWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Analyzed sentiment for a batch of documents - {}", response)) .doOnError(error -> logger.warning("Failed to analyze sentiment - {}", error)) .map(this::toTextAnalyticsPagedResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
This started coming up from the current change?
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment) { final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores(); final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream() .map(sentenceSentiment -> { final SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getConfidenceScores(); return new SentenceSentiment(sentenceSentiment.getText(), sentenceSentiment.getSentiment().toString(), new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(), confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive())); }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map( warning -> new TextAnalyticsWarning(warning.getCode().toString(), warning.getMessage())).collect(Collectors.toList()); return new AnalyzeSentimentResult( documentSentiment.getId(), documentSentiment.getStatistics() == null ? null : toTextDocumentStatistics(documentSentiment.getStatistics()), null, new com.azure.ai.textanalytics.models.DocumentSentiment( documentSentiment.getSentiment().toString(), new SentimentConfidenceScores( confidenceScorePerLabel.getNegative(), confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive()), new IterableStream<>(sentenceSentiments), new IterableStream<>(warnings))); }
sentenceSentiment.getSentiment().toString(),
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment) { final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores(); final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream() .map(sentenceSentiment -> { final SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getConfidenceScores(); final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment(); return new SentenceSentiment(sentenceSentiment.getText(), sentenceSentimentValue == null ? null : sentenceSentimentValue.toString(), new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(), confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive())); }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map( warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning(warningCodeValue == null ? null : warningCodeValue.toString(), warning.getMessage()); }).collect(Collectors.toList()); final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment(); return new AnalyzeSentimentResult( documentSentiment.getId(), documentSentiment.getStatistics() == null ? null : toTextDocumentStatistics(documentSentiment.getStatistics()), null, new com.azure.ai.textanalytics.models.DocumentSentiment( documentSentimentValue == null ? null : documentSentimentValue.toString(), new SentimentConfidenceScores( confidenceScorePerLabel.getNegative(), confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive()), new IterableStream<>(sentenceSentiments), new IterableStream<>(warnings))); }
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param service The proxy service used to perform REST calls. */ AnalyzeSentimentAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatch(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> withContext(context -> getAnalyzedSentimentResponseInPage(documents, options, context)).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return The {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> getAnalyzedSentimentResponseInPage(documents, options, context).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper method to convert the service response of {@link SentimentResponse} to {@link TextAnalyticsPagedResponse} * of {@link AnalyzeSentimentResult}. * * @param response The {@link SimpleResponse} of {@link SentimentResponse} returned by the service. * * @return The {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult} returned by the SDK. */ private TextAnalyticsPagedResponse<AnalyzeSentimentResult> toTextAnalyticsPagedResponse( SimpleResponse<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment)); } for (DocumentError documentError : sentimentResponse.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new TextAnalyticsPagedResponse<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), analyzeSentimentResults, null, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics())); } /** * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. * * @param documentSentiment The {@link DocumentSentiment} returned by the service. * * @return The {@link AnalyzeSentimentResult} to be returned by the SDK. */ /** * Call the service with REST response, convert to a {@link Mono} of {@link TextAnalyticsPagedResponse} of * {@link AnalyzeSentimentResult} from a {@link SimpleResponse} of {@link SentimentResponse}. * * @param documents A list of documents to be analyzed. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A {@link Mono} of {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult}. */ private Mono<TextAnalyticsPagedResponse<AnalyzeSentimentResult>> getAnalyzedSentimentResponseInPage( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.sentimentWithResponseAsync( new MultiLanguageBatchInput().setDocuments(Transforms.toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Analyzed sentiment for a batch of documents - {}", response)) .doOnError(error -> logger.warning("Failed to analyze sentiment - {}", error)) .map(this::toTextAnalyticsPagedResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param service The proxy service used to perform REST calls. */ AnalyzeSentimentAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatch(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> withContext(context -> getAnalyzedSentimentResponseInPage(documents, options, context)).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return The {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> getAnalyzedSentimentResponseInPage(documents, options, context).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper method to convert the service response of {@link SentimentResponse} to {@link TextAnalyticsPagedResponse} * of {@link AnalyzeSentimentResult}. * * @param response The {@link SimpleResponse} of {@link SentimentResponse} returned by the service. * * @return The {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult} returned by the SDK. */ private TextAnalyticsPagedResponse<AnalyzeSentimentResult> toTextAnalyticsPagedResponse( SimpleResponse<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment)); } for (DocumentError documentError : sentimentResponse.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new TextAnalyticsPagedResponse<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), analyzeSentimentResults, null, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics())); } /** * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. * * @param documentSentiment The {@link DocumentSentiment} returned by the service. * * @return The {@link AnalyzeSentimentResult} to be returned by the SDK. */ /** * Call the service with REST response, convert to a {@link Mono} of {@link TextAnalyticsPagedResponse} of * {@link AnalyzeSentimentResult} from a {@link SimpleResponse} of {@link SentimentResponse}. * * @param documents A list of documents to be analyzed. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A {@link Mono} of {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult}. */ private Mono<TextAnalyticsPagedResponse<AnalyzeSentimentResult>> getAnalyzedSentimentResponseInPage( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.sentimentWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Analyzed sentiment for a batch of documents - {}", response)) .doOnError(error -> logger.warning("Failed to analyze sentiment - {}", error)) .map(this::toTextAnalyticsPagedResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
Yes. Null checking here is an redundant check. As the error message explained here.
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment) { final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores(); final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream() .map(sentenceSentiment -> { final SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getConfidenceScores(); return new SentenceSentiment(sentenceSentiment.getText(), sentenceSentiment.getSentiment().toString(), new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(), confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive())); }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map( warning -> new TextAnalyticsWarning(warning.getCode().toString(), warning.getMessage())).collect(Collectors.toList()); return new AnalyzeSentimentResult( documentSentiment.getId(), documentSentiment.getStatistics() == null ? null : toTextDocumentStatistics(documentSentiment.getStatistics()), null, new com.azure.ai.textanalytics.models.DocumentSentiment( documentSentiment.getSentiment().toString(), new SentimentConfidenceScores( confidenceScorePerLabel.getNegative(), confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive()), new IterableStream<>(sentenceSentiments), new IterableStream<>(warnings))); }
sentenceSentiment.getSentiment().toString(),
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(DocumentSentiment documentSentiment) { final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getConfidenceScores(); final List<SentenceSentiment> sentenceSentiments = documentSentiment.getSentences().stream() .map(sentenceSentiment -> { final SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getConfidenceScores(); final SentenceSentimentValue sentenceSentimentValue = sentenceSentiment.getSentiment(); return new SentenceSentiment(sentenceSentiment.getText(), sentenceSentimentValue == null ? null : sentenceSentimentValue.toString(), new SentimentConfidenceScores(confidenceScorePerSentence.getNegative(), confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive())); }).collect(Collectors.toList()); final List<TextAnalyticsWarning> warnings = documentSentiment.getWarnings().stream().map( warning -> { final WarningCodeValue warningCodeValue = warning.getCode(); return new TextAnalyticsWarning(warningCodeValue == null ? null : warningCodeValue.toString(), warning.getMessage()); }).collect(Collectors.toList()); final DocumentSentimentValue documentSentimentValue = documentSentiment.getSentiment(); return new AnalyzeSentimentResult( documentSentiment.getId(), documentSentiment.getStatistics() == null ? null : toTextDocumentStatistics(documentSentiment.getStatistics()), null, new com.azure.ai.textanalytics.models.DocumentSentiment( documentSentimentValue == null ? null : documentSentimentValue.toString(), new SentimentConfidenceScores( confidenceScorePerLabel.getNegative(), confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive()), new IterableStream<>(sentenceSentiments), new IterableStream<>(warnings))); }
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param service The proxy service used to perform REST calls. */ AnalyzeSentimentAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatch(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> withContext(context -> getAnalyzedSentimentResponseInPage(documents, options, context)).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return The {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> getAnalyzedSentimentResponseInPage(documents, options, context).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper method to convert the service response of {@link SentimentResponse} to {@link TextAnalyticsPagedResponse} * of {@link AnalyzeSentimentResult}. * * @param response The {@link SimpleResponse} of {@link SentimentResponse} returned by the service. * * @return The {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult} returned by the SDK. */ private TextAnalyticsPagedResponse<AnalyzeSentimentResult> toTextAnalyticsPagedResponse( SimpleResponse<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment)); } for (DocumentError documentError : sentimentResponse.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new TextAnalyticsPagedResponse<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), analyzeSentimentResults, null, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics())); } /** * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. * * @param documentSentiment The {@link DocumentSentiment} returned by the service. * * @return The {@link AnalyzeSentimentResult} to be returned by the SDK. */ /** * Call the service with REST response, convert to a {@link Mono} of {@link TextAnalyticsPagedResponse} of * {@link AnalyzeSentimentResult} from a {@link SimpleResponse} of {@link SentimentResponse}. * * @param documents A list of documents to be analyzed. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A {@link Mono} of {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult}. */ private Mono<TextAnalyticsPagedResponse<AnalyzeSentimentResult>> getAnalyzedSentimentResponseInPage( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.sentimentWithResponseAsync( new MultiLanguageBatchInput().setDocuments(Transforms.toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Analyzed sentiment for a batch of documents - {}", response)) .doOnError(error -> logger.warning("Failed to analyze sentiment - {}", error)) .map(this::toTextAnalyticsPagedResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create an {@link AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param service The proxy service used to perform REST calls. */ AnalyzeSentimentAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * * @return {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatch(Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> withContext(context -> getAnalyzedSentimentResponseInPage(documents, options, context)).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper function for calling service with max overloaded parameters that a returns {@link TextAnalyticsPagedFlux} * which is a paged flux that contains {@link AnalyzeSentimentResult}. * * @param documents The list of documents to analyze sentiments for. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return The {@link TextAnalyticsPagedFlux} of {@link AnalyzeSentimentResult}. */ TextAnalyticsPagedFlux<AnalyzeSentimentResult> analyzeSentimentBatchWithContext( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { try { inputDocumentsValidation(documents); return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> getAnalyzedSentimentResponseInPage(documents, options, context).flux()); } catch (RuntimeException ex) { return new TextAnalyticsPagedFlux<>(() -> (continuationToken, pageSize) -> fluxError(logger, ex)); } } /** * Helper method to convert the service response of {@link SentimentResponse} to {@link TextAnalyticsPagedResponse} * of {@link AnalyzeSentimentResult}. * * @param response The {@link SimpleResponse} of {@link SentimentResponse} returned by the service. * * @return The {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult} returned by the SDK. */ private TextAnalyticsPagedResponse<AnalyzeSentimentResult> toTextAnalyticsPagedResponse( SimpleResponse<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment)); } for (DocumentError documentError : sentimentResponse.getErrors()) { /* * TODO: Remove this after service update to throw exception. * Currently, service sets max limit of document size to 5, if the input documents size > 5, it will * have an id = "", empty id. In the future, they will remove this and throw HttpResponseException. */ if (documentError.getId().isEmpty()) { throw logger.logExceptionAsError( new HttpResponseException(documentError.getError().getInnererror().getMessage(), getEmptyErrorIdHttpResponse(response), documentError.getError().getInnererror().getCode())); } analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new TextAnalyticsPagedResponse<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), analyzeSentimentResults, null, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics())); } /** * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. * * @param documentSentiment The {@link DocumentSentiment} returned by the service. * * @return The {@link AnalyzeSentimentResult} to be returned by the SDK. */ /** * Call the service with REST response, convert to a {@link Mono} of {@link TextAnalyticsPagedResponse} of * {@link AnalyzeSentimentResult} from a {@link SimpleResponse} of {@link SentimentResponse}. * * @param documents A list of documents to be analyzed. * @param options The {@link TextAnalyticsRequestOptions} request options. * @param context Additional context that is passed through the Http pipeline during the service call. * * @return A {@link Mono} of {@link TextAnalyticsPagedResponse} of {@link AnalyzeSentimentResult}. */ private Mono<TextAnalyticsPagedResponse<AnalyzeSentimentResult>> getAnalyzedSentimentResponseInPage( Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) { return service.sentimentWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics()) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Analyzed sentiment for a batch of documents - {}", response)) .doOnError(error -> logger.warning("Failed to analyze sentiment - {}", error)) .map(this::toTextAnalyticsPagedResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); } }
@srnagar Is this the same thing that management SDK's are doing too? And you had some opinions to have a new model type for the exception rather than doing it this way?
public static Throwable mapToHttpResponseExceptionIfExist(Throwable throwable) { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), toTextAnalyticsError(errorException.getValue())); } return throwable; }
toTextAnalyticsError(errorException.getValue()));
public static Throwable mapToHttpResponseExceptionIfExist(Throwable throwable) { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), toTextAnalyticsError(errorException.getValue())); } return throwable; }
class Utility { private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is {@code null}. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Get a mock {@link HttpResponse} that only return status code 400. * * @param response A {@link SimpleResponse} with any type * @return A mock {@link HttpResponse} that only return status code 400. */ public static HttpResponse getEmptyErrorIdHttpResponse(SimpleResponse<?> response) { return new HttpResponse(response.getRequest()) { @Override public int getStatusCode() { return 400; } @Override public String getHeaderValue(String s) { return null; } @Override public HttpHeaders getHeaders() { return null; } @Override public Flux<ByteBuffer> getBody() { return null; } @Override public Mono<byte[]> getBodyAsByteArray() { return null; } @Override public Mono<String> getBodyAsString() { return null; } @Override public Mono<String> getBodyAsString(Charset charset) { return null; } }; } /** * Mapping a {@link TextAnalyticsErrorException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link TextAnalyticsError inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { final InnerError innerError = textAnalyticsError.getInnererror(); if (innerError == null) { final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode().toString(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } }
class Utility { private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is {@code null}. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Get a mock {@link HttpResponse} that only return status code 400. * * @param response A {@link SimpleResponse} with any type * @return A mock {@link HttpResponse} that only return status code 400. */ public static HttpResponse getEmptyErrorIdHttpResponse(SimpleResponse<?> response) { return new HttpResponse(response.getRequest()) { @Override public int getStatusCode() { return 400; } @Override public String getHeaderValue(String s) { return null; } @Override public HttpHeaders getHeaders() { return null; } @Override public Flux<ByteBuffer> getBody() { return null; } @Override public Mono<byte[]> getBodyAsByteArray() { return null; } @Override public Mono<String> getBodyAsString() { return null; } @Override public Mono<String> getBodyAsString(Charset charset) { return null; } }; } /** * Mapping a {@link TextAnalyticsErrorException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link TextAnalyticsError inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { final InnerError innerError = textAnalyticsError.getInnererror(); if (innerError == null) { final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode().toString(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } }
as discussion in the TA meeting, this change looks good.
public static Throwable mapToHttpResponseExceptionIfExist(Throwable throwable) { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), toTextAnalyticsError(errorException.getValue())); } return throwable; }
toTextAnalyticsError(errorException.getValue()));
public static Throwable mapToHttpResponseExceptionIfExist(Throwable throwable) { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), toTextAnalyticsError(errorException.getValue())); } return throwable; }
class Utility { private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is {@code null}. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Get a mock {@link HttpResponse} that only return status code 400. * * @param response A {@link SimpleResponse} with any type * @return A mock {@link HttpResponse} that only return status code 400. */ public static HttpResponse getEmptyErrorIdHttpResponse(SimpleResponse<?> response) { return new HttpResponse(response.getRequest()) { @Override public int getStatusCode() { return 400; } @Override public String getHeaderValue(String s) { return null; } @Override public HttpHeaders getHeaders() { return null; } @Override public Flux<ByteBuffer> getBody() { return null; } @Override public Mono<byte[]> getBodyAsByteArray() { return null; } @Override public Mono<String> getBodyAsString() { return null; } @Override public Mono<String> getBodyAsString(Charset charset) { return null; } }; } /** * Mapping a {@link TextAnalyticsErrorException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link TextAnalyticsError inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { final InnerError innerError = textAnalyticsError.getInnererror(); if (innerError == null) { final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode().toString(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } }
class Utility { private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is {@code null}. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Get a mock {@link HttpResponse} that only return status code 400. * * @param response A {@link SimpleResponse} with any type * @return A mock {@link HttpResponse} that only return status code 400. */ public static HttpResponse getEmptyErrorIdHttpResponse(SimpleResponse<?> response) { return new HttpResponse(response.getRequest()) { @Override public int getStatusCode() { return 400; } @Override public String getHeaderValue(String s) { return null; } @Override public HttpHeaders getHeaders() { return null; } @Override public Flux<ByteBuffer> getBody() { return null; } @Override public Mono<byte[]> getBodyAsByteArray() { return null; } @Override public Mono<String> getBodyAsString() { return null; } @Override public Mono<String> getBodyAsString(Charset charset) { return null; } }; } /** * Mapping a {@link TextAnalyticsErrorException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link TextAnalyticsError inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { final InnerError innerError = textAnalyticsError.getInnererror(); if (innerError == null) { final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode().toString(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } }
In `toTextAnalyticsError` .NET is using the top-level error to form the exception, but here we are using the innerError value if present.
public static Throwable mapToHttpResponseExceptionIfExist(Throwable throwable) { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), toTextAnalyticsError(errorException.getValue())); } return throwable; }
toTextAnalyticsError(errorException.getValue()));
public static Throwable mapToHttpResponseExceptionIfExist(Throwable throwable) { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), toTextAnalyticsError(errorException.getValue())); } return throwable; }
class Utility { private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is {@code null}. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Get a mock {@link HttpResponse} that only return status code 400. * * @param response A {@link SimpleResponse} with any type * @return A mock {@link HttpResponse} that only return status code 400. */ public static HttpResponse getEmptyErrorIdHttpResponse(SimpleResponse<?> response) { return new HttpResponse(response.getRequest()) { @Override public int getStatusCode() { return 400; } @Override public String getHeaderValue(String s) { return null; } @Override public HttpHeaders getHeaders() { return null; } @Override public Flux<ByteBuffer> getBody() { return null; } @Override public Mono<byte[]> getBodyAsByteArray() { return null; } @Override public Mono<String> getBodyAsString() { return null; } @Override public Mono<String> getBodyAsString(Charset charset) { return null; } }; } /** * Mapping a {@link TextAnalyticsErrorException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link TextAnalyticsError inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { final InnerError innerError = textAnalyticsError.getInnererror(); if (innerError == null) { final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode().toString(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } }
class Utility { private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is {@code null}. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Get a mock {@link HttpResponse} that only return status code 400. * * @param response A {@link SimpleResponse} with any type * @return A mock {@link HttpResponse} that only return status code 400. */ public static HttpResponse getEmptyErrorIdHttpResponse(SimpleResponse<?> response) { return new HttpResponse(response.getRequest()) { @Override public int getStatusCode() { return 400; } @Override public String getHeaderValue(String s) { return null; } @Override public HttpHeaders getHeaders() { return null; } @Override public Flux<ByteBuffer> getBody() { return null; } @Override public Mono<byte[]> getBodyAsByteArray() { return null; } @Override public Mono<String> getBodyAsString() { return null; } @Override public Mono<String> getBodyAsString(Charset charset) { return null; } }; } /** * Mapping a {@link TextAnalyticsErrorException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link TextAnalyticsError inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { final InnerError innerError = textAnalyticsError.getInnererror(); if (innerError == null) { final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode().toString(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } }
This is what python used to use innerError https://github.com/Azure/azure-sdk-for-python/pull/11155/files#diff-6814e3aaeba6362738bfde592d65bd9bR64
public static Throwable mapToHttpResponseExceptionIfExist(Throwable throwable) { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), toTextAnalyticsError(errorException.getValue())); } return throwable; }
toTextAnalyticsError(errorException.getValue()));
public static Throwable mapToHttpResponseExceptionIfExist(Throwable throwable) { if (throwable instanceof TextAnalyticsErrorException) { TextAnalyticsErrorException errorException = (TextAnalyticsErrorException) throwable; return new HttpResponseException(errorException.getMessage(), errorException.getResponse(), toTextAnalyticsError(errorException.getValue())); } return throwable; }
class Utility { private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is {@code null}. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Get a mock {@link HttpResponse} that only return status code 400. * * @param response A {@link SimpleResponse} with any type * @return A mock {@link HttpResponse} that only return status code 400. */ public static HttpResponse getEmptyErrorIdHttpResponse(SimpleResponse<?> response) { return new HttpResponse(response.getRequest()) { @Override public int getStatusCode() { return 400; } @Override public String getHeaderValue(String s) { return null; } @Override public HttpHeaders getHeaders() { return null; } @Override public Flux<ByteBuffer> getBody() { return null; } @Override public Mono<byte[]> getBodyAsByteArray() { return null; } @Override public Mono<String> getBodyAsString() { return null; } @Override public Mono<String> getBodyAsString(Charset charset) { return null; } }; } /** * Mapping a {@link TextAnalyticsErrorException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link TextAnalyticsError inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { final InnerError innerError = textAnalyticsError.getInnererror(); if (innerError == null) { final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode().toString(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } }
class Utility { private Utility() { } /** * Verify that list of documents are not null or empty. Otherwise, throw exception. * * @param documents A list of documents. * * @throws NullPointerException if {@code documents} is {@code null}. * @throws IllegalArgumentException if {@code documents} is empty. */ public static void inputDocumentsValidation(Iterable<?> documents) { Objects.requireNonNull(documents, "'documents' cannot be null."); final Iterator<?> iterator = documents.iterator(); if (!iterator.hasNext()) { throw new IllegalArgumentException("'documents' cannot be empty."); } } /** * Get a mock {@link HttpResponse} that only return status code 400. * * @param response A {@link SimpleResponse} with any type * @return A mock {@link HttpResponse} that only return status code 400. */ public static HttpResponse getEmptyErrorIdHttpResponse(SimpleResponse<?> response) { return new HttpResponse(response.getRequest()) { @Override public int getStatusCode() { return 400; } @Override public String getHeaderValue(String s) { return null; } @Override public HttpHeaders getHeaders() { return null; } @Override public Flux<ByteBuffer> getBody() { return null; } @Override public Mono<byte[]> getBodyAsByteArray() { return null; } @Override public Mono<String> getBodyAsString() { return null; } @Override public Mono<String> getBodyAsString(Charset charset) { return null; } }; } /** * Mapping a {@link TextAnalyticsErrorException} to {@link HttpResponseException} if exist. Otherwise, return * original {@link Throwable}. * * @param throwable A {@link Throwable}. * @return A {@link HttpResponseException} or the original throwable type. */ /** * Given a list of documents will apply the indexing function to it and return the updated list. * * @param documents the inputs to apply the mapping function to. * @param mappingFunction the function which applies the index to the incoming input value. * @param <T> the type of items being returned in the list. * @return The list holding all the generic items combined. */ public static <T> List<T> mapByIndex(Iterable<String> documents, BiFunction<String, String, T> mappingFunction) { Objects.requireNonNull(documents, "'documents' cannot be null."); AtomicInteger i = new AtomicInteger(0); List<T> result = new ArrayList<>(); documents.forEach(document -> result.add(mappingFunction.apply(String.valueOf(i.getAndIncrement()), document)) ); return result; } /** * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} * * @param statistics the {@link DocumentStatistics} provided by the service. * @return the {@link TextDocumentStatistics} returned by the SDK. */ public static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); } /** * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} * * @param statistics the {@link RequestStatistics} provided by the service. * @return the {@link TextDocumentBatchStatistics} returned by the SDK. */ public static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); } /** * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * This function maps the service returned {@link TextAnalyticsError inner error} to the top level * {@link com.azure.ai.textanalytics.models.TextAnalyticsError error}, if inner error present. * * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. */ public static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { final InnerError innerError = textAnalyticsError.getInnererror(); if (innerError == null) { final ErrorCodeValue errorCodeValue = textAnalyticsError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(errorCodeValue == null ? null : errorCodeValue.toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } final InnerErrorCodeValue innerErrorCodeValue = innerError.getCode(); return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(innerErrorCodeValue == null ? null : innerErrorCodeValue.toString()), innerError.getMessage(), innerError.getTarget()); } /** * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. * * @param documents the user provided input in {@link TextDocumentInput} * @return the service required input {@link MultiLanguageInput} */ public static List<MultiLanguageInput> toMultiLanguageInput(Iterable<TextDocumentInput> documents) { List<MultiLanguageInput> multiLanguageInputs = new ArrayList<>(); for (TextDocumentInput textDocumentInput : documents) { multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); } return multiLanguageInputs; } /** * Convert the incoming input {@link com.azure.ai.textanalytics.models.TextAnalyticsError} * to a {@link TextAnalyticsException}. * * @param error the {@link com.azure.ai.textanalytics.models.TextAnalyticsError}. * @return the {@link TextAnalyticsException} to be thrown. */ public static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getErrorCode().toString(), error.getTarget()); } /** * Convert to a list of {@link LanguageInput} from {@link DetectLanguageInput}. * * @param documents The list of documents to detect languages for. * * @return a list of {@link LanguageInput}. */ public static List<LanguageInput> toLanguageInput(Iterable<DetectLanguageInput> documents) { final List<LanguageInput> multiLanguageInputs = new ArrayList<>(); documents.forEach(textDocumentInput -> multiLanguageInputs.add(new LanguageInput() .setId(textDocumentInput.getId()) .setText(textDocumentInput.getText()) .setCountryHint(textDocumentInput.getCountryHint()))); return multiLanguageInputs; } }
can this be updated to use the public apis for setting precision.
DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<IncludedPath> includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); includedPath.setPath("/*"); List<Index> indexes = new ArrayList<>(); Index stringIndex = Index.range(DataType.STRING); BridgeInternal.setProperty(ModelBridgeInternal.getJsonSerializable(stringIndex), "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.range(DataType.NUMBER); BridgeInternal.setProperty(ModelBridgeInternal.getJsonSerializable(numberIndex), "getPrecision", -1); indexes.add(numberIndex); includedPath.setIndexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setIndexingPolicy(indexingPolicy); collectionDefinition.setId(UUID.randomUUID().toString()); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; }
BridgeInternal.setProperty(ModelBridgeInternal.getJsonSerializable(stringIndex), "precision", -1);
DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<IncludedPath> includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath("/*"); List<Index> indexes = new ArrayList<>(); indexes.add(Index.range(DataType.STRING, -1)); indexes.add(Index.range(DataType.NUMBER, -1)); includedPath.setIndexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setIndexingPolicy(indexingPolicy); collectionDefinition.setId(UUID.randomUUID().toString()); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; }
class ReadMyWritesConsistencyTest { private final static Logger logger = LoggerFactory.getLogger(ReadMyWritesConsistencyTest.class); private final AtomicBoolean collectionScaleUpFailed = new AtomicBoolean(false); private final Duration defaultMaxRunningTime = Duration.ofMinutes(45); private final int delayForInitiationCollectionScaleUpInSeconds = 60; private final String desiredConsistency = System.getProperty("DESIRED_CONSISTENCY", StringUtils.defaultString(Strings.emptyToNull( System.getenv().get("DESIRED_CONSISTENCY")), "Session")); private final int initialCollectionThroughput = 10_000; private final String maxRunningTime = System.getProperty("MAX_RUNNING_TIME", StringUtils.defaultString(Strings.emptyToNull( System.getenv().get("MAX_RUNNING_TIME")), defaultMaxRunningTime.toString())); private final int newCollectionThroughput = 100_000; private final String numberOfOperationsAsString = System.getProperty("NUMBER_OF_OPERATIONS", StringUtils.defaultString(Strings.emptyToNull( System.getenv().get("NUMBER_OF_OPERATIONS")), "-1")); private DocumentCollection collection; private Database database; @AfterClass(groups = "e2e") public void afterClass() { AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); Utils.safeCleanDatabases(housekeepingClient); Utils.safeClean(housekeepingClient, database); Utils.safeClose(housekeepingClient); } @BeforeClass(groups = "e2e") public void before_ReadMyWritesConsistencyTest() { RequestOptions options = new RequestOptions(); options.setOfferThroughput(initialCollectionThroughput); AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); database = Utils.createDatabaseForTest(housekeepingClient); collection = housekeepingClient.createCollection("dbs/" + database.getId(), getCollectionDefinitionWithRangeRangeIndex(), options).single().block().getResource(); housekeepingClient.close(); } @DataProvider(name = "collectionLinkTypeArgProvider") public Object[][] collectionLinkTypeArgProvider() { return new Object[][] { { true }, }; } @Test(dataProvider = "collectionLinkTypeArgProvider", groups = "e2e") public void readMyWrites(boolean useNameLink) throws Exception { int concurrency = 5; String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s" + " -collectionId %s" + " -consistencyLevel %s" + " -concurrency %s" + " -numberOfOperations %s" + " -maxRunningTimeDuration %s" + " -operation ReadMyWrites" + " -connectionMode Direct" + " -numberOfPreCreatedDocuments 100" + " -printingInterval 60" + "%s"; String cmd = lenientFormat(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, database.getId(), collection.getId(), desiredConsistency, concurrency, numberOfOperationsAsString, maxRunningTime, (useNameLink ? " -useNameLink" : "")); Configuration cfg = new Configuration(); new JCommander(cfg, StringUtils.split(cmd)); AtomicInteger success = new AtomicInteger(); AtomicInteger error = new AtomicInteger(); ReadMyWriteWorkflow wf = new ReadMyWriteWorkflow(cfg) { @Override protected void onError(Throwable throwable) { logger.error("Error occurred in ReadMyWriteWorkflow", throwable); error.incrementAndGet(); } @Override protected void onSuccess() { success.incrementAndGet(); } }; scheduleScaleUp(delayForInitiationCollectionScaleUpInSeconds, newCollectionThroughput); wf.run(); wf.shutdown(); int numberOfOperations = Integer.parseInt(numberOfOperationsAsString); assertThat(error).hasValue(0); assertThat(collectionScaleUpFailed).isFalse(); if (numberOfOperations > 0) { assertThat(success).hasValue(numberOfOperations); } } private void scheduleScaleUp(int delayStartInSeconds, int newThroughput) { AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); Flux.just(0L).delayElements(Duration.ofSeconds(delayStartInSeconds), Schedulers.newSingle("ScaleUpThread")).flatMap(aVoid -> { return housekeepingClient.queryOffers( String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", collection.getResourceId()) , null).flatMap(page -> Flux.fromIterable(page.getResults())) .take(1).flatMap(offer -> { logger.info("going to scale up collection, newThroughput {}", newThroughput); offer.setThroughput(newThroughput); return housekeepingClient.replaceOffer(offer); }); }).doOnTerminate(housekeepingClient::close) .subscribe(aVoid -> { }, e -> { logger.error("collectionScaleUpFailed to scale up collection", e); collectionScaleUpFailed.set(true); }, () -> { logger.info("Collection Scale up request sent to the service"); } ); } }
class ReadMyWritesConsistencyTest { private final static Logger logger = LoggerFactory.getLogger(ReadMyWritesConsistencyTest.class); private final AtomicBoolean collectionScaleUpFailed = new AtomicBoolean(false); private final Duration defaultMaxRunningTime = Duration.ofMinutes(45); private final int delayForInitiationCollectionScaleUpInSeconds = 60; private final String desiredConsistency = System.getProperty("DESIRED_CONSISTENCY", StringUtils.defaultString(Strings.emptyToNull( System.getenv().get("DESIRED_CONSISTENCY")), "Session")); private final int initialCollectionThroughput = 10_000; private final String maxRunningTime = System.getProperty("MAX_RUNNING_TIME", StringUtils.defaultString(Strings.emptyToNull( System.getenv().get("MAX_RUNNING_TIME")), defaultMaxRunningTime.toString())); private final int newCollectionThroughput = 100_000; private final String numberOfOperationsAsString = System.getProperty("NUMBER_OF_OPERATIONS", StringUtils.defaultString(Strings.emptyToNull( System.getenv().get("NUMBER_OF_OPERATIONS")), "-1")); private DocumentCollection collection; private Database database; @AfterClass(groups = "e2e") public void afterClass() { AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); Utils.safeCleanDatabases(housekeepingClient); Utils.safeClean(housekeepingClient, database); Utils.safeClose(housekeepingClient); } @BeforeClass(groups = "e2e") public void before_ReadMyWritesConsistencyTest() { RequestOptions options = new RequestOptions(); options.setOfferThroughput(initialCollectionThroughput); AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); database = Utils.createDatabaseForTest(housekeepingClient); collection = housekeepingClient.createCollection("dbs/" + database.getId(), getCollectionDefinitionWithRangeRangeIndex(), options).single().block().getResource(); housekeepingClient.close(); } @DataProvider(name = "collectionLinkTypeArgProvider") public Object[][] collectionLinkTypeArgProvider() { return new Object[][] { { true }, }; } @Test(dataProvider = "collectionLinkTypeArgProvider", groups = "e2e") public void readMyWrites(boolean useNameLink) throws Exception { int concurrency = 5; String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s" + " -collectionId %s" + " -consistencyLevel %s" + " -concurrency %s" + " -numberOfOperations %s" + " -maxRunningTimeDuration %s" + " -operation ReadMyWrites" + " -connectionMode Direct" + " -numberOfPreCreatedDocuments 100" + " -printingInterval 60" + "%s"; String cmd = lenientFormat(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, database.getId(), collection.getId(), desiredConsistency, concurrency, numberOfOperationsAsString, maxRunningTime, (useNameLink ? " -useNameLink" : "")); Configuration cfg = new Configuration(); new JCommander(cfg, StringUtils.split(cmd)); AtomicInteger success = new AtomicInteger(); AtomicInteger error = new AtomicInteger(); ReadMyWriteWorkflow wf = new ReadMyWriteWorkflow(cfg) { @Override protected void onError(Throwable throwable) { logger.error("Error occurred in ReadMyWriteWorkflow", throwable); error.incrementAndGet(); } @Override protected void onSuccess() { success.incrementAndGet(); } }; scheduleScaleUp(delayForInitiationCollectionScaleUpInSeconds, newCollectionThroughput); wf.run(); wf.shutdown(); int numberOfOperations = Integer.parseInt(numberOfOperationsAsString); assertThat(error).hasValue(0); assertThat(collectionScaleUpFailed).isFalse(); if (numberOfOperations > 0) { assertThat(success).hasValue(numberOfOperations); } } private void scheduleScaleUp(int delayStartInSeconds, int newThroughput) { AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); Flux.just(0L).delayElements(Duration.ofSeconds(delayStartInSeconds), Schedulers.newSingle("ScaleUpThread")).flatMap(aVoid -> { return housekeepingClient.queryOffers( String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", collection.getResourceId()) , null).flatMap(page -> Flux.fromIterable(page.getResults())) .take(1).flatMap(offer -> { logger.info("going to scale up collection, newThroughput {}", newThroughput); offer.setThroughput(newThroughput); return housekeepingClient.replaceOffer(offer); }); }).doOnTerminate(housekeepingClient::close) .subscribe(aVoid -> { }, e -> { logger.error("collectionScaleUpFailed to scale up collection", e); collectionScaleUpFailed.set(true); }, () -> { logger.info("Collection Scale up request sent to the service"); } ); } }