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
That's true. My opinion is to leave insensitive data over there as Json file is also a good and quick reference of what the request and response are composed of. It is cheap to have the information over there. However, I am flexible of making change to replace all.
private void redactedAccountName(UrlBuilder urlBuilder) { String[] hostParts = urlBuilder.getHost().split("\\."); hostParts[0] = "REDACTED"; urlBuilder.setHost(String.join(".", hostParts)); }
hostParts[0] = "REDACTED";
private void redactedAccountName(UrlBuilder urlBuilder) { String[] hostParts = urlBuilder.getHost().split("\\."); hostParts[0] = "REDACTED"; urlBuilder.setHost(String.join(".", hostParts)); }
class RecordNetworkCallPolicy implements HttpPipelinePolicy { private static final int DEFAULT_BUFFER_LENGTH = 1024; private static final String CONTENT_TYPE = "Content-Type"; private static final String CONTENT_ENCODING = "Content-Encoding"; private static final String CONTENT_LENGTH = "Content-Length"; 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 static final String X_MS_VERSION = "x-ms-version"; private static final String USER_AGENT = "User-Agent"; private static final String STATUS_CODE = "StatusCode"; private static final String BODY = "Body"; private static final String SIG = "sig"; private static final Pattern DELEGATIONKEY_KEY_PATTERN = Pattern.compile("(?:<Value>)(.*)(?:</Value>)"); private static final Pattern DELEGATIONKEY_CLIENTID_PATTERN = Pattern.compile("(?:<SignedOid>)(.*)(?:</SignedOid>)"); private static final Pattern DELEGATIONKEY_TENANTID_PATTERN = Pattern.compile("(?:<SignedTid>)(.*)(?:</SignedTid>)"); private final ClientLogger logger = new ClientLogger(RecordNetworkCallPolicy.class); private final RecordedData recordedData; /** * Creates a policy that records network calls into {@code recordedData}. * * @param recordedData The record to persist network calls into. */ public RecordNetworkCallPolicy(RecordedData recordedData) { Objects.requireNonNull(recordedData, "'recordedData' cannot be null."); this.recordedData = recordedData; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final NetworkCallRecord networkCallRecord = new NetworkCallRecord(); Map<String, String> headers = new HashMap<>(); captureRequestHeaders(context.getHttpRequest().getHeaders(), headers, X_MS_CLIENT_REQUEST_ID, CONTENT_TYPE, X_MS_VERSION, USER_AGENT); networkCallRecord.setHeaders(headers); networkCallRecord.setMethod(context.getHttpRequest().getHttpMethod().toString()); UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); redactedAccountName(urlBuilder); if (urlBuilder.getQuery().containsKey(SIG)) { urlBuilder.setQueryParameter(SIG, "REDACTED"); } networkCallRecord.setUri(urlBuilder.toString().replaceAll("\\?$", "")); return next.process() .doOnError(throwable -> { networkCallRecord.setException(new NetworkCallError(throwable)); recordedData.addNetworkCall(networkCallRecord); throw logger.logExceptionAsWarning(Exceptions.propagate(throwable)); }).flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); return extractResponseData(bufferedResponse).map(responseData -> { networkCallRecord.setResponse(responseData); String body = responseData.get(BODY); if (body != null && body.contains("<Status>InProgress</Status>") || Integer.parseInt(responseData.get(STATUS_CODE)) == HttpURLConnection.HTTP_MOVED_TEMP) { logger.info("Waiting for a response or redirection."); } else { recordedData.addNetworkCall(networkCallRecord); } return bufferedResponse; }); }); } private void captureRequestHeaders(HttpHeaders requestHeaders, Map<String, String> captureHeaders, String... headerNames) { for (String headerName : headerNames) { if (requestHeaders.getValue(headerName) != null) { captureHeaders.put(headerName, requestHeaders.getValue(headerName)); } } } private Mono<Map<String, String>> extractResponseData(final HttpResponse response) { final Map<String, String> responseData = new HashMap<>(); responseData.put(STATUS_CODE, Integer.toString(response.getStatusCode())); boolean addedRetryAfter = false; for (HttpHeader header : response.getHeaders()) { String headerValueToStore = header.getValue(); if (header.getName().equalsIgnoreCase("retry-after")) { headerValueToStore = "0"; addedRetryAfter = true; } else if (header.getName().equalsIgnoreCase(X_MS_ENCRYPTION_KEY_SHA256)) { headerValueToStore = "REDACTED"; } responseData.put(header.getName(), headerValueToStore); } if (!addedRetryAfter) { responseData.put("retry-after", "0"); } String contentType = response.getHeaderValue(CONTENT_TYPE); if (contentType == null) { return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> { if (bytes.length == 0) { return responseData; } String content = new String(bytes, StandardCharsets.UTF_8); responseData.put(CONTENT_LENGTH, Integer.toString(content.length())); responseData.put(BODY, content); return responseData; }); } else if (contentType.equalsIgnoreCase("application/octet-stream")) { return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> { if (bytes.length == 0) { return responseData; } responseData.put(BODY, Arrays.toString(bytes)); return responseData; }); } else if (contentType.contains("json") || response.getHeaderValue(CONTENT_ENCODING) == null) { return response.getBodyAsString(StandardCharsets.UTF_8).switchIfEmpty(Mono.just("")).map(content -> { responseData.put(BODY, redactUserDelegationKey(content)); return responseData; }); } else { return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> { if (bytes.length == 0) { return responseData; } String content; if ("gzip".equalsIgnoreCase(response.getHeaderValue(CONTENT_ENCODING))) { try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes)); ByteArrayOutputStream output = new ByteArrayOutputStream()) { byte[] buffer = new byte[DEFAULT_BUFFER_LENGTH]; int position = 0; int bytesRead = gis.read(buffer, position, buffer.length); while (bytesRead != -1) { output.write(buffer, 0, bytesRead); position += bytesRead; bytesRead = gis.read(buffer, position, buffer.length); } content = new String(output.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { throw logger.logExceptionAsWarning(Exceptions.propagate(e)); } } else { content = new String(bytes, StandardCharsets.UTF_8); } responseData.remove(CONTENT_ENCODING); responseData.put(CONTENT_LENGTH, Integer.toString(content.length())); responseData.put(BODY, content); return responseData; }); } } private String redactUserDelegationKey(String content) { if (!content.contains("UserDelegationKey")) { return content; } content = redactionReplacement(content, DELEGATIONKEY_KEY_PATTERN.matcher(content), Base64.getEncoder().encodeToString("REDACTED".getBytes(StandardCharsets.UTF_8))); content = redactionReplacement(content, DELEGATIONKEY_CLIENTID_PATTERN.matcher(content), UUID.randomUUID().toString()); content = redactionReplacement(content, DELEGATIONKEY_TENANTID_PATTERN.matcher(content), UUID.randomUUID().toString()); return content; } private String redactionReplacement(String content, Matcher matcher, String replacement) { while (matcher.find()) { content = content.replace(matcher.group(1), replacement); } return content; } }
class RecordNetworkCallPolicy implements HttpPipelinePolicy { private static final int DEFAULT_BUFFER_LENGTH = 1024; private static final String CONTENT_TYPE = "Content-Type"; private static final String CONTENT_ENCODING = "Content-Encoding"; private static final String CONTENT_LENGTH = "Content-Length"; 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 static final String X_MS_VERSION = "x-ms-version"; private static final String USER_AGENT = "User-Agent"; private static final String STATUS_CODE = "StatusCode"; private static final String BODY = "Body"; private static final String SIG = "sig"; private static final Pattern DELEGATIONKEY_KEY_PATTERN = Pattern.compile("(?:<Value>)(.*)(?:</Value>)"); private static final Pattern DELEGATIONKEY_CLIENTID_PATTERN = Pattern.compile("(?:<SignedOid>)(.*)(?:</SignedOid>)"); private static final Pattern DELEGATIONKEY_TENANTID_PATTERN = Pattern.compile("(?:<SignedTid>)(.*)(?:</SignedTid>)"); private final ClientLogger logger = new ClientLogger(RecordNetworkCallPolicy.class); private final RecordedData recordedData; /** * Creates a policy that records network calls into {@code recordedData}. * * @param recordedData The record to persist network calls into. */ public RecordNetworkCallPolicy(RecordedData recordedData) { Objects.requireNonNull(recordedData, "'recordedData' cannot be null."); this.recordedData = recordedData; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final NetworkCallRecord networkCallRecord = new NetworkCallRecord(); Map<String, String> headers = new HashMap<>(); captureRequestHeaders(context.getHttpRequest().getHeaders(), headers, X_MS_CLIENT_REQUEST_ID, CONTENT_TYPE, X_MS_VERSION, USER_AGENT); networkCallRecord.setHeaders(headers); networkCallRecord.setMethod(context.getHttpRequest().getHttpMethod().toString()); UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); redactedAccountName(urlBuilder); if (urlBuilder.getQuery().containsKey(SIG)) { urlBuilder.setQueryParameter(SIG, "REDACTED"); } networkCallRecord.setUri(urlBuilder.toString().replaceAll("\\?$", "")); return next.process() .doOnError(throwable -> { networkCallRecord.setException(new NetworkCallError(throwable)); recordedData.addNetworkCall(networkCallRecord); throw logger.logExceptionAsWarning(Exceptions.propagate(throwable)); }).flatMap(httpResponse -> { final HttpResponse bufferedResponse = httpResponse.buffer(); return extractResponseData(bufferedResponse).map(responseData -> { networkCallRecord.setResponse(responseData); String body = responseData.get(BODY); if (body != null && body.contains("<Status>InProgress</Status>") || Integer.parseInt(responseData.get(STATUS_CODE)) == HttpURLConnection.HTTP_MOVED_TEMP) { logger.info("Waiting for a response or redirection."); } else { recordedData.addNetworkCall(networkCallRecord); } return bufferedResponse; }); }); } private void captureRequestHeaders(HttpHeaders requestHeaders, Map<String, String> captureHeaders, String... headerNames) { for (String headerName : headerNames) { if (requestHeaders.getValue(headerName) != null) { captureHeaders.put(headerName, requestHeaders.getValue(headerName)); } } } private Mono<Map<String, String>> extractResponseData(final HttpResponse response) { final Map<String, String> responseData = new HashMap<>(); responseData.put(STATUS_CODE, Integer.toString(response.getStatusCode())); boolean addedRetryAfter = false; for (HttpHeader header : response.getHeaders()) { String headerValueToStore = header.getValue(); if (header.getName().equalsIgnoreCase("retry-after")) { headerValueToStore = "0"; addedRetryAfter = true; } else if (header.getName().equalsIgnoreCase(X_MS_ENCRYPTION_KEY_SHA256)) { headerValueToStore = "REDACTED"; } responseData.put(header.getName(), headerValueToStore); } if (!addedRetryAfter) { responseData.put("retry-after", "0"); } String contentType = response.getHeaderValue(CONTENT_TYPE); if (contentType == null) { return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> { if (bytes.length == 0) { return responseData; } String content = new String(bytes, StandardCharsets.UTF_8); responseData.put(CONTENT_LENGTH, Integer.toString(content.length())); responseData.put(BODY, content); return responseData; }); } else if (contentType.equalsIgnoreCase("application/octet-stream")) { return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> { if (bytes.length == 0) { return responseData; } responseData.put(BODY, Arrays.toString(bytes)); return responseData; }); } else if (contentType.contains("json") || response.getHeaderValue(CONTENT_ENCODING) == null) { return response.getBodyAsString(StandardCharsets.UTF_8).switchIfEmpty(Mono.just("")).map(content -> { responseData.put(BODY, redactUserDelegationKey(content)); return responseData; }); } else { return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> { if (bytes.length == 0) { return responseData; } String content; if ("gzip".equalsIgnoreCase(response.getHeaderValue(CONTENT_ENCODING))) { try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes)); ByteArrayOutputStream output = new ByteArrayOutputStream()) { byte[] buffer = new byte[DEFAULT_BUFFER_LENGTH]; int position = 0; int bytesRead = gis.read(buffer, position, buffer.length); while (bytesRead != -1) { output.write(buffer, 0, bytesRead); position += bytesRead; bytesRead = gis.read(buffer, position, buffer.length); } content = new String(output.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { throw logger.logExceptionAsWarning(Exceptions.propagate(e)); } } else { content = new String(bytes, StandardCharsets.UTF_8); } responseData.remove(CONTENT_ENCODING); responseData.put(CONTENT_LENGTH, Integer.toString(content.length())); responseData.put(BODY, content); return responseData; }); } } private String redactUserDelegationKey(String content) { if (!content.contains("UserDelegationKey")) { return content; } content = redactionReplacement(content, DELEGATIONKEY_KEY_PATTERN.matcher(content), Base64.getEncoder().encodeToString("REDACTED".getBytes(StandardCharsets.UTF_8))); content = redactionReplacement(content, DELEGATIONKEY_CLIENTID_PATTERN.matcher(content), UUID.randomUUID().toString()); content = redactionReplacement(content, DELEGATIONKEY_TENANTID_PATTERN.matcher(content), UUID.randomUUID().toString()); return content; } private String redactionReplacement(String content, Matcher matcher, String replacement) { while (matcher.find()) { content = content.replace(matcher.group(1), replacement); } return content; } }
Any reason why we look for only these 3 charsets and not others? Adding a comment here to explain that would be good.
public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(bytes -> { if (bytes.length >= 3 && bytes[0] == (byte) 239 && bytes[1] == (byte) 187 && bytes[2] == (byte) 191) { return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8); } else if (bytes.length >= 2 && bytes[0] == (byte) 254 && bytes[1] == (byte) 255) { return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16BE); } else if (bytes.length >= 2 && bytes[0] == (byte) 255 && bytes[1] == (byte) 254) { return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE); } else { /* * Attempt to retrieve the default charset from the 'Content-Encoding' header, if the value isn't * present or invalid fallback to 'UTF-8' for the default charset. */ Charset charset; try { String contentEncoding = headers.getValue("Content-Encoding"); charset = (contentEncoding != null) ? Charset.forName(contentEncoding) : StandardCharsets.UTF_8; } catch (RuntimeException ex) { charset = StandardCharsets.UTF_8; } return new String(bytes, charset); } }); }
return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE);
public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(bytes -> CoreUtils.bomAwareToString(bytes, headers.getValue("Content-Type"))); }
class JdkHttpResponse extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private final Flux<ByteBuffer> contentFlux; private volatile boolean disposed = false; protected JdkHttpResponse(final HttpRequest request, java.net.http.HttpResponse<Flow.Publisher<List<ByteBuffer>>> innerResponse) { super(request); this.statusCode = innerResponse.statusCode(); this.headers = fromJdkHttpHeaders(innerResponse.headers()); this.contentFlux = JdkFlowAdapter.flowPublisherToFlux(innerResponse.body()) .flatMapSequential(Flux::fromIterable); } @Override public int getStatusCode() { return this.statusCode; } @Override public String getHeaderValue(String name) { return this.headers.getValue(name); } @Override public HttpHeaders getHeaders() { return this.headers; } @Override public Flux<ByteBuffer> getBody() { return this.contentFlux .doFinally(signalType -> disposed = true); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesInByteBufferStream(getBody()) .flatMap(bytes -> bytes.length == 0 ? Mono.empty() : Mono.just(bytes)); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override public void close() { if (!this.disposed) { this.disposed = true; this.contentFlux .subscribe() .dispose(); } } /** * Converts the given JDK Http headers to azure-core Http header. * * @param headers the JDK Http headers * @return the azure-core Http headers */ private static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) { final HttpHeaders httpHeaders = new HttpHeaders(); for (final String key : headers.map().keySet()) { final List<String> values = headers.allValues(key); if (CoreUtils.isNullOrEmpty(values)) { continue; } else if (values.size() == 1) { httpHeaders.put(key, values.get(0)); } else { httpHeaders.put(key, String.join(",", values)); } } return httpHeaders; } }
class JdkHttpResponse extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private final Flux<ByteBuffer> contentFlux; private volatile boolean disposed = false; protected JdkHttpResponse(final HttpRequest request, java.net.http.HttpResponse<Flow.Publisher<List<ByteBuffer>>> innerResponse) { super(request); this.statusCode = innerResponse.statusCode(); this.headers = fromJdkHttpHeaders(innerResponse.headers()); this.contentFlux = JdkFlowAdapter.flowPublisherToFlux(innerResponse.body()) .flatMapSequential(Flux::fromIterable); } @Override public int getStatusCode() { return this.statusCode; } @Override public String getHeaderValue(String name) { return this.headers.getValue(name); } @Override public HttpHeaders getHeaders() { return this.headers; } @Override public Flux<ByteBuffer> getBody() { return this.contentFlux .doFinally(signalType -> disposed = true); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesInByteBufferStream(getBody()) .flatMap(bytes -> bytes.length == 0 ? Mono.empty() : Mono.just(bytes)); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override public void close() { if (!this.disposed) { this.disposed = true; this.contentFlux .subscribe() .dispose(); } } /** * Converts the given JDK Http headers to azure-core Http header. * * @param headers the JDK Http headers * @return the azure-core Http headers */ private static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) { final HttpHeaders httpHeaders = new HttpHeaders(); for (final String key : headers.map().keySet()) { final List<String> values = headers.allValues(key); if (CoreUtils.isNullOrEmpty(values)) { continue; } else if (values.size() == 1) { httpHeaders.put(key, values.get(0)); } else { httpHeaders.put(key, String.join(",", values)); } } return httpHeaders; } }
Both JDK client and Netty client have to do the same logic for converting response byte array to string. It would be better to put this in Core utils somewhere to reduce duplication and if there are any fixes or updates to this logic, we don't need to update in two places.
public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(bytes -> { if (bytes.length >= 3 && bytes[0] == (byte) 239 && bytes[1] == (byte) 187 && bytes[2] == (byte) 191) { return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8); } else if (bytes.length >= 2 && bytes[0] == (byte) 254 && bytes[1] == (byte) 255) { return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16BE); } else if (bytes.length >= 2 && bytes[0] == (byte) 255 && bytes[1] == (byte) 254) { return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE); } else { /* * Attempt to retrieve the default charset from the 'Content-Encoding' header, if the value isn't * present or invalid fallback to 'UTF-8' for the default charset. */ try { String contentType = reactorNettyResponse.responseHeaders() .get("Content-Type", "charset=UTF-8"); Matcher charsetMatcher = CHARSET_PATTERN.matcher(contentType); if (charsetMatcher.find()) { return new String(bytes, Charset.forName(charsetMatcher.group(1))); } else { return new String(bytes, StandardCharsets.UTF_8); } } catch (IllegalCharsetNameException | UnsupportedCharsetException ex) { return new String(bytes, StandardCharsets.UTF_8); } } }); }
return getBodyAsByteArray().map(bytes -> {
public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(bytes -> CoreUtils.bomAwareToString(bytes, reactorNettyResponse.responseHeaders().get("Content-Type"))); }
class ReactorNettyHttpResponse extends HttpResponse { private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection, HttpRequest httpRequest, boolean disableBufferCopy) { super(httpRequest); this.reactorNettyResponse = reactorNettyResponse; this.reactorNettyConnection = reactorNettyConnection; this.disableBufferCopy = disableBufferCopy; } @Override public int getStatusCode() { return reactorNettyResponse.status().code(); } @Override public String getHeaderValue(String name) { return reactorNettyResponse.responseHeaders().get(name); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); reactorNettyResponse.responseHeaders().forEach(e -> headers.put(e.getKey(), e.getValue())); return headers; } @Override public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> this.disableBufferCopy ? byteBuf.nioBuffer() : deepCopyBuffer(byteBuf)); } @Override public Mono<byte[]> getBodyAsByteArray() { return bodyIntern().aggregate().asByteArray().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return bodyIntern().aggregate().asString(charset).doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }); } @Override public void close() { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } } private ByteBufFlux bodyIntern() { return reactorNettyConnection.inbound().receive(); } Connection internConnection() { return reactorNettyConnection; } private static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.readBytes(buffer); buffer.rewind(); return buffer; } }
class ReactorNettyHttpResponse extends HttpResponse { private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection, HttpRequest httpRequest, boolean disableBufferCopy) { super(httpRequest); this.reactorNettyResponse = reactorNettyResponse; this.reactorNettyConnection = reactorNettyConnection; this.disableBufferCopy = disableBufferCopy; } @Override public int getStatusCode() { return reactorNettyResponse.status().code(); } @Override public String getHeaderValue(String name) { return reactorNettyResponse.responseHeaders().get(name); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); reactorNettyResponse.responseHeaders().forEach(e -> headers.put(e.getKey(), e.getValue())); return headers; } @Override public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> this.disableBufferCopy ? byteBuf.nioBuffer() : deepCopyBuffer(byteBuf)); } @Override public Mono<byte[]> getBodyAsByteArray() { return bodyIntern().aggregate().asByteArray().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return bodyIntern().aggregate().asString(charset).doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }); } @Override public void close() { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } } private ByteBufFlux bodyIntern() { return reactorNettyConnection.inbound().receive(); } Connection internConnection() { return reactorNettyConnection; } private static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.readBytes(buffer); buffer.rewind(); return buffer; } }
Yeah I was thinking about that, also would give the opportunity to test is more directly and thoroughly.
public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(bytes -> { if (bytes.length >= 3 && bytes[0] == (byte) 239 && bytes[1] == (byte) 187 && bytes[2] == (byte) 191) { return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8); } else if (bytes.length >= 2 && bytes[0] == (byte) 254 && bytes[1] == (byte) 255) { return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16BE); } else if (bytes.length >= 2 && bytes[0] == (byte) 255 && bytes[1] == (byte) 254) { return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE); } else { /* * Attempt to retrieve the default charset from the 'Content-Encoding' header, if the value isn't * present or invalid fallback to 'UTF-8' for the default charset. */ try { String contentType = reactorNettyResponse.responseHeaders() .get("Content-Type", "charset=UTF-8"); Matcher charsetMatcher = CHARSET_PATTERN.matcher(contentType); if (charsetMatcher.find()) { return new String(bytes, Charset.forName(charsetMatcher.group(1))); } else { return new String(bytes, StandardCharsets.UTF_8); } } catch (IllegalCharsetNameException | UnsupportedCharsetException ex) { return new String(bytes, StandardCharsets.UTF_8); } } }); }
return getBodyAsByteArray().map(bytes -> {
public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(bytes -> CoreUtils.bomAwareToString(bytes, reactorNettyResponse.responseHeaders().get("Content-Type"))); }
class ReactorNettyHttpResponse extends HttpResponse { private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection, HttpRequest httpRequest, boolean disableBufferCopy) { super(httpRequest); this.reactorNettyResponse = reactorNettyResponse; this.reactorNettyConnection = reactorNettyConnection; this.disableBufferCopy = disableBufferCopy; } @Override public int getStatusCode() { return reactorNettyResponse.status().code(); } @Override public String getHeaderValue(String name) { return reactorNettyResponse.responseHeaders().get(name); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); reactorNettyResponse.responseHeaders().forEach(e -> headers.put(e.getKey(), e.getValue())); return headers; } @Override public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> this.disableBufferCopy ? byteBuf.nioBuffer() : deepCopyBuffer(byteBuf)); } @Override public Mono<byte[]> getBodyAsByteArray() { return bodyIntern().aggregate().asByteArray().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return bodyIntern().aggregate().asString(charset).doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }); } @Override public void close() { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } } private ByteBufFlux bodyIntern() { return reactorNettyConnection.inbound().receive(); } Connection internConnection() { return reactorNettyConnection; } private static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.readBytes(buffer); buffer.rewind(); return buffer; } }
class ReactorNettyHttpResponse extends HttpResponse { private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection, HttpRequest httpRequest, boolean disableBufferCopy) { super(httpRequest); this.reactorNettyResponse = reactorNettyResponse; this.reactorNettyConnection = reactorNettyConnection; this.disableBufferCopy = disableBufferCopy; } @Override public int getStatusCode() { return reactorNettyResponse.status().code(); } @Override public String getHeaderValue(String name) { return reactorNettyResponse.responseHeaders().get(name); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); reactorNettyResponse.responseHeaders().forEach(e -> headers.put(e.getKey(), e.getValue())); return headers; } @Override public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> this.disableBufferCopy ? byteBuf.nioBuffer() : deepCopyBuffer(byteBuf)); } @Override public Mono<byte[]> getBodyAsByteArray() { return bodyIntern().aggregate().asByteArray().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return bodyIntern().aggregate().asString(charset).doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }); } @Override public void close() { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } } private ByteBufFlux bodyIntern() { return reactorNettyConnection.inbound().receive(); } Connection internConnection() { return reactorNettyConnection; } private static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.readBytes(buffer); buffer.rewind(); return buffer; } }
Added support for `UTF-32BE` and `UTF-32LE`
public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(bytes -> { if (bytes.length >= 3 && bytes[0] == (byte) 239 && bytes[1] == (byte) 187 && bytes[2] == (byte) 191) { return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8); } else if (bytes.length >= 2 && bytes[0] == (byte) 254 && bytes[1] == (byte) 255) { return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16BE); } else if (bytes.length >= 2 && bytes[0] == (byte) 255 && bytes[1] == (byte) 254) { return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE); } else { /* * Attempt to retrieve the default charset from the 'Content-Encoding' header, if the value isn't * present or invalid fallback to 'UTF-8' for the default charset. */ Charset charset; try { String contentEncoding = headers.getValue("Content-Encoding"); charset = (contentEncoding != null) ? Charset.forName(contentEncoding) : StandardCharsets.UTF_8; } catch (RuntimeException ex) { charset = StandardCharsets.UTF_8; } return new String(bytes, charset); } }); }
return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE);
public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(bytes -> CoreUtils.bomAwareToString(bytes, headers.getValue("Content-Type"))); }
class JdkHttpResponse extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private final Flux<ByteBuffer> contentFlux; private volatile boolean disposed = false; protected JdkHttpResponse(final HttpRequest request, java.net.http.HttpResponse<Flow.Publisher<List<ByteBuffer>>> innerResponse) { super(request); this.statusCode = innerResponse.statusCode(); this.headers = fromJdkHttpHeaders(innerResponse.headers()); this.contentFlux = JdkFlowAdapter.flowPublisherToFlux(innerResponse.body()) .flatMapSequential(Flux::fromIterable); } @Override public int getStatusCode() { return this.statusCode; } @Override public String getHeaderValue(String name) { return this.headers.getValue(name); } @Override public HttpHeaders getHeaders() { return this.headers; } @Override public Flux<ByteBuffer> getBody() { return this.contentFlux .doFinally(signalType -> disposed = true); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesInByteBufferStream(getBody()) .flatMap(bytes -> bytes.length == 0 ? Mono.empty() : Mono.just(bytes)); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override public void close() { if (!this.disposed) { this.disposed = true; this.contentFlux .subscribe() .dispose(); } } /** * Converts the given JDK Http headers to azure-core Http header. * * @param headers the JDK Http headers * @return the azure-core Http headers */ private static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) { final HttpHeaders httpHeaders = new HttpHeaders(); for (final String key : headers.map().keySet()) { final List<String> values = headers.allValues(key); if (CoreUtils.isNullOrEmpty(values)) { continue; } else if (values.size() == 1) { httpHeaders.put(key, values.get(0)); } else { httpHeaders.put(key, String.join(",", values)); } } return httpHeaders; } }
class JdkHttpResponse extends HttpResponse { private final int statusCode; private final HttpHeaders headers; private final Flux<ByteBuffer> contentFlux; private volatile boolean disposed = false; protected JdkHttpResponse(final HttpRequest request, java.net.http.HttpResponse<Flow.Publisher<List<ByteBuffer>>> innerResponse) { super(request); this.statusCode = innerResponse.statusCode(); this.headers = fromJdkHttpHeaders(innerResponse.headers()); this.contentFlux = JdkFlowAdapter.flowPublisherToFlux(innerResponse.body()) .flatMapSequential(Flux::fromIterable); } @Override public int getStatusCode() { return this.statusCode; } @Override public String getHeaderValue(String name) { return this.headers.getValue(name); } @Override public HttpHeaders getHeaders() { return this.headers; } @Override public Flux<ByteBuffer> getBody() { return this.contentFlux .doFinally(signalType -> disposed = true); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesInByteBufferStream(getBody()) .flatMap(bytes -> bytes.length == 0 ? Mono.empty() : Mono.just(bytes)); } @Override @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override public void close() { if (!this.disposed) { this.disposed = true; this.contentFlux .subscribe() .dispose(); } } /** * Converts the given JDK Http headers to azure-core Http header. * * @param headers the JDK Http headers * @return the azure-core Http headers */ private static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) { final HttpHeaders httpHeaders = new HttpHeaders(); for (final String key : headers.map().keySet()) { final List<String> values = headers.allValues(key); if (CoreUtils.isNullOrEmpty(values)) { continue; } else if (values.size() == 1) { httpHeaders.put(key, values.get(0)); } else { httpHeaders.put(key, String.join(",", values)); } } return httpHeaders; } }
Done, also resolved another TODO
public void canPostDeploymentWhatIfOnResourceGroup() throws Exception { final String dpName = "dpA" + testId; resourceClient.deployments() .define(dpName) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .create(); PagedIterable<Deployment> deployments = resourceClient.deployments().listByResourceGroup(rgName); boolean found = false; for (Deployment deployment : deployments) { if (deployment.name().equals(dpName)) { found = true; } } Assertions.assertTrue(found); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dpName); Assertions.assertNotNull(deployment); Assertions.assertEquals("Succeeded", deployment.provisioningState()); WhatIfOperationResult result = deployment.prepareWhatIf() .withIncrementalMode() .withWhatIfTemplateLink(templateUri, contentVersion) .whatIf(); Assertions.assertEquals("Succeeded", result.status()); resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15"); }
public void canPostDeploymentWhatIfOnResourceGroup() throws Exception { final String dpName = "dpA" + testId; resourceClient.deployments() .define(dpName) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .create(); PagedIterable<Deployment> deployments = resourceClient.deployments().listByResourceGroup(rgName); boolean found = false; for (Deployment deployment : deployments) { if (deployment.name().equals(dpName)) { found = true; } } Assertions.assertTrue(found); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dpName); Assertions.assertNotNull(deployment); Assertions.assertEquals("Succeeded", deployment.provisioningState()); WhatIfOperationResult result = deployment.prepareWhatIf() .withIncrementalMode() .withWhatIfTemplateLink(templateUri, contentVersion) .whatIf(); Assertions.assertEquals("Succeeded", result.status()); Assertions.assertEquals(3, result.changes().size()); resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15"); }
class DeploymentsTests extends ResourceManagerTestBase { private ResourceGroups resourceGroups; private ResourceGroup resourceGroup; private String testId; private String rgName; private static String templateUri = "https: private static String blankTemplateUri = "https: private static String parametersUri = "https: private static String updateTemplate = "{\"$schema\":\"https: private static String updateParameters = "{\"vnetAddressPrefix\":{\"value\":\"10.0.0.0/16\"},\"subnet1Name\":{\"value\":\"Subnet1\"},\"subnet1Prefix\":{\"value\":\"10.0.0.0/24\"}}"; private static String contentVersion = "1.0.0.0"; @Override protected void initializeClients(RestClient restClient, String defaultSubscription, String domain) { super.initializeClients(restClient, defaultSubscription, domain); testId = sdkContext.randomResourceName("", 9); resourceGroups = resourceClient.resourceGroups(); rgName = "rg" + testId; resourceGroup = resourceGroups.define(rgName) .withRegion(Region.US_SOUTH_CENTRAL) .create(); } @Override protected void cleanUpResources() { resourceGroups.beginDeleteByName(rgName); } @Test public void canDeployVirtualNetwork() throws Exception { final String dpName = "dpA" + testId; resourceClient.deployments() .define(dpName) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .create(); PagedIterable<Deployment> deployments = resourceClient.deployments().listByResourceGroup(rgName); boolean found = false; for (Deployment deployment : deployments) { if (deployment.name().equals(dpName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertTrue(resourceClient.deployments().checkExistence(rgName, dpName)); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dpName); Assertions.assertNotNull(deployment); Assertions.assertEquals("Succeeded", deployment.provisioningState()); GenericResource generic = resourceClient.genericResources().get(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15"); Assertions.assertNotNull(generic); Assertions.assertNotNull(deployment.exportTemplate().templateAsJson()); Assertions.assertNotNull(resourceGroup.exportTemplate(ResourceGroupExportTemplateOptions.INCLUDE_BOTH)); PagedIterable<DeploymentOperation> operations = deployment.deploymentOperations().list(); Assertions.assertEquals(4, TestUtilities.getSize(operations)); DeploymentOperation op = deployment.deploymentOperations().getById(operations.iterator().next().operationId()); Assertions.assertNotNull(op); resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15"); } @Test @Test public void canPostDeploymentWhatIfOnSubscription() throws Exception { final String dpName = "dpA" + testId; resourceClient.deployments() .define(dpName) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .create(); PagedIterable<Deployment> deployments = resourceClient.deployments().listByResourceGroup(rgName); boolean found = false; for (Deployment deployment : deployments) { if (deployment.name().equals(dpName)) { found = true; } } Assertions.assertTrue(found); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dpName); Assertions.assertNotNull(deployment); Assertions.assertEquals("Succeeded", deployment.provisioningState()); WhatIfOperationResult result = deployment.prepareWhatIf() .withLocation("westus") .withIncrementalMode() .withWhatIfTemplateLink(blankTemplateUri, contentVersion) .whatIfAtSubscriptionScope(); Assertions.assertEquals("Succeeded", result.status()); resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15"); } @Test @Disabled("deployment.cancel() doesn't throw but provisining state says Running not Cancelled...") public void canCancelVirtualNetworkDeployment() throws Exception { final String dp = "dpB" + testId; resourceClient.deployments() .define(dp) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .beginCreate(); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals(dp, deployment.name()); deployment.cancel(); deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals("Canceled", deployment.provisioningState()); Assertions.assertFalse(resourceClient.genericResources().checkExistence(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15")); } @Test public void canUpdateVirtualNetworkDeployment() throws Exception { final String dp = "dpC" + testId; Deployment createdDeployment = resourceClient.deployments() .define(dp) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .beginCreate(); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals(createdDeployment.correlationId(), deployment.correlationId()); Assertions.assertEquals(dp, deployment.name()); deployment.cancel(); deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals("Canceled", deployment.provisioningState()); deployment.update() .withTemplate(updateTemplate) .withParameters(updateParameters) .withMode(DeploymentMode.INCREMENTAL) .apply(); deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals(DeploymentMode.INCREMENTAL, deployment.mode()); Assertions.assertEquals("Succeeded", deployment.provisioningState()); GenericResource genericVnet = resourceClient.genericResources().get(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet2", "2015-06-15"); Assertions.assertNotNull(genericVnet); resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet2", "2015-06-15"); } }
class DeploymentsTests extends ResourceManagerTestBase { private ResourceGroups resourceGroups; private ResourceGroup resourceGroup; private String testId; private String rgName; private static String templateUri = "https: private static String blankTemplateUri = "https: private static String parametersUri = "https: private static String updateTemplate = "{\"$schema\":\"https: private static String updateParameters = "{\"vnetAddressPrefix\":{\"value\":\"10.0.0.0/16\"},\"subnet1Name\":{\"value\":\"Subnet1\"},\"subnet1Prefix\":{\"value\":\"10.0.0.0/24\"}}"; private static String contentVersion = "1.0.0.0"; @Override protected void initializeClients(RestClient restClient, String defaultSubscription, String domain) { super.initializeClients(restClient, defaultSubscription, domain); testId = sdkContext.randomResourceName("", 9); resourceGroups = resourceClient.resourceGroups(); rgName = "rg" + testId; resourceGroup = resourceGroups.define(rgName) .withRegion(Region.US_SOUTH_CENTRAL) .create(); } @Override protected void cleanUpResources() { resourceGroups.beginDeleteByName(rgName); } @Test public void canDeployVirtualNetwork() throws Exception { final String dpName = "dpA" + testId; resourceClient.deployments() .define(dpName) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .create(); PagedIterable<Deployment> deployments = resourceClient.deployments().listByResourceGroup(rgName); boolean found = false; for (Deployment deployment : deployments) { if (deployment.name().equals(dpName)) { found = true; } } Assertions.assertTrue(found); Assertions.assertTrue(resourceClient.deployments().checkExistence(rgName, dpName)); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dpName); Assertions.assertNotNull(deployment); Assertions.assertEquals("Succeeded", deployment.provisioningState()); GenericResource generic = resourceClient.genericResources().get(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15"); Assertions.assertNotNull(generic); Assertions.assertNotNull(deployment.exportTemplate().templateAsJson()); Assertions.assertNotNull(resourceGroup.exportTemplate(ResourceGroupExportTemplateOptions.INCLUDE_BOTH)); PagedIterable<DeploymentOperation> operations = deployment.deploymentOperations().list(); Assertions.assertEquals(4, TestUtilities.getSize(operations)); DeploymentOperation op = deployment.deploymentOperations().getById(operations.iterator().next().operationId()); Assertions.assertNotNull(op); resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15"); } @Test @Test public void canPostDeploymentWhatIfOnSubscription() throws Exception { final String dpName = "dpA" + testId; resourceClient.deployments() .define(dpName) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .create(); PagedIterable<Deployment> deployments = resourceClient.deployments().listByResourceGroup(rgName); boolean found = false; for (Deployment deployment : deployments) { if (deployment.name().equals(dpName)) { found = true; } } Assertions.assertTrue(found); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dpName); Assertions.assertNotNull(deployment); Assertions.assertEquals("Succeeded", deployment.provisioningState()); WhatIfOperationResult result = deployment.prepareWhatIf() .withLocation("westus") .withIncrementalMode() .withWhatIfTemplateLink(blankTemplateUri, contentVersion) .whatIfAtSubscriptionScope(); Assertions.assertEquals("Succeeded", result.status()); Assertions.assertEquals(0, result.changes().size()); resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15"); } @Test @Disabled("deployment.cancel() doesn't throw but provisining state says Running not Cancelled...") public void canCancelVirtualNetworkDeployment() throws Exception { final String dp = "dpB" + testId; resourceClient.deployments() .define(dp) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .beginCreate(); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals(dp, deployment.name()); deployment.cancel(); deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals("Canceled", deployment.provisioningState()); Assertions.assertFalse(resourceClient.genericResources().checkExistence(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet1", "2015-06-15")); } @Test public void canUpdateVirtualNetworkDeployment() throws Exception { final String dp = "dpC" + testId; Deployment createdDeployment = resourceClient.deployments() .define(dp) .withExistingResourceGroup(rgName) .withTemplateLink(templateUri, contentVersion) .withParametersLink(parametersUri, contentVersion) .withMode(DeploymentMode.COMPLETE) .beginCreate(); Deployment deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals(createdDeployment.correlationId(), deployment.correlationId()); Assertions.assertEquals(dp, deployment.name()); deployment.cancel(); deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals("Canceled", deployment.provisioningState()); deployment.update() .withTemplate(updateTemplate) .withParameters(updateParameters) .withMode(DeploymentMode.INCREMENTAL) .apply(); deployment = resourceClient.deployments().getByResourceGroup(rgName, dp); Assertions.assertEquals(DeploymentMode.INCREMENTAL, deployment.mode()); Assertions.assertEquals("Succeeded", deployment.provisioningState()); GenericResource genericVnet = resourceClient.genericResources().get(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet2", "2015-06-15"); Assertions.assertNotNull(genericVnet); resourceClient.genericResources().delete(rgName, "Microsoft.Network", "", "virtualnetworks", "VNet2", "2015-06-15"); } }
You need to change the set part? e.g. `withPublicAccess`
public Mono<BlobContainer> createResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner()) .map(innerToFluentMap(this)); }
.createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner())
public Mono<BlobContainer> createResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner().withPublicAccess(cpublicAccess).withMetadata(cmetadata)) .map(innerToFluentMap(this)); }
class BlobContainerImpl extends CreatableUpdatableImpl<BlobContainer, BlobContainerInner, BlobContainerImpl> implements BlobContainer, BlobContainer.Definition, BlobContainer.Update { private final StorageManager manager; private String resourceGroupName; private String accountName; private String containerName; private PublicAccess cpublicAccess; private Map<String, String> cmetadata; private PublicAccess upublicAccess; private Map<String, String> umetadata; BlobContainerImpl(String name, StorageManager manager) { super(name, new BlobContainerInner()); this.manager = manager; this.containerName = name; } BlobContainerImpl(BlobContainerInner inner, StorageManager manager) { super(inner.getName(), inner); this.manager = manager; this.containerName = inner.getName(); this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.getId(), "resourceGroups"); this.accountName = IdParsingUtils.getValueFromIdByName(inner.getId(), "storageAccounts"); this.containerName = IdParsingUtils.getValueFromIdByName(inner.getId(), "containers"); } @Override public StorageManager manager() { return this.manager; } @Override @Override public Mono<BlobContainer> updateResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .updateAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner()) .map(innerToFluentMap(this)); } @Override protected Mono<BlobContainerInner> getInnerAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return null; } @Override public boolean isInCreateMode() { return this.inner().getId() == null; } @Override public String etag() { return this.inner().etag(); } @Override public Boolean hasImmutabilityPolicy() { return this.inner().hasImmutabilityPolicy(); } @Override public Boolean hasLegalHold() { return this.inner().hasLegalHold(); } @Override public String id() { return this.inner().getId(); } @Override public ImmutabilityPolicyProperties immutabilityPolicy() { return this.inner().immutabilityPolicy(); } @Override public OffsetDateTime lastModifiedTime() { return this.inner().lastModifiedTime(); } @Override public LeaseDuration leaseDuration() { return this.inner().leaseDuration(); } @Override public LeaseState leaseState() { return this.inner().leaseState(); } @Override public LeaseStatus leaseStatus() { return this.inner().leaseStatus(); } @Override public LegalHoldProperties legalHold() { return this.inner().legalHold(); } @Override public Map<String, String> metadata() { return this.inner().metadata(); } @Override public String name() { return this.inner().getName(); } @Override public PublicAccess publicAccess() { return this.inner().publicAccess(); } @Override public String type() { return this.inner().getType(); } @Override public BlobContainerImpl withExistingBlobService(String resourceGroupName, String accountName) { this.resourceGroupName = resourceGroupName; this.accountName = accountName; return this; } @Override public BlobContainerImpl withPublicAccess(PublicAccess publicAccess) { if (isInCreateMode()) { this.cpublicAccess = publicAccess; } else { this.upublicAccess = publicAccess; } return this; } @Override public BlobContainerImpl withMetadata(Map<String, String> metadata) { if (isInCreateMode()) { this.cmetadata = metadata; } else { this.umetadata = metadata; } return this; } @Override public BlobContainerImpl withMetadata(String name, String value) { if (isInCreateMode()) { if (this.cmetadata == null) { this.cmetadata = new HashMap<>(); } this.cmetadata.put(name, value); } else { if (this.umetadata == null) { this.umetadata = new HashMap<>(); } this.umetadata.put(name, value); } return this; } }
class BlobContainerImpl extends CreatableUpdatableImpl<BlobContainer, BlobContainerInner, BlobContainerImpl> implements BlobContainer, BlobContainer.Definition, BlobContainer.Update { private final StorageManager manager; private String resourceGroupName; private String accountName; private String containerName; private PublicAccess cpublicAccess; private Map<String, String> cmetadata; private PublicAccess upublicAccess; private Map<String, String> umetadata; BlobContainerImpl(String name, StorageManager manager) { super(name, new BlobContainerInner()); this.manager = manager; this.containerName = name; } BlobContainerImpl(BlobContainerInner inner, StorageManager manager) { super(inner.getName(), inner); this.manager = manager; this.containerName = inner.getName(); this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.getId(), "resourceGroups"); this.accountName = IdParsingUtils.getValueFromIdByName(inner.getId(), "storageAccounts"); this.containerName = IdParsingUtils.getValueFromIdByName(inner.getId(), "containers"); } @Override public StorageManager manager() { return this.manager; } @Override @Override public Mono<BlobContainer> updateResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .updateAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner().withPublicAccess(upublicAccess).withMetadata(umetadata)) .map(innerToFluentMap(this)); } @Override protected Mono<BlobContainerInner> getInnerAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return null; } @Override public boolean isInCreateMode() { return this.inner().getId() == null; } @Override public String etag() { return this.inner().etag(); } @Override public Boolean hasImmutabilityPolicy() { return this.inner().hasImmutabilityPolicy(); } @Override public Boolean hasLegalHold() { return this.inner().hasLegalHold(); } @Override public String id() { return this.inner().getId(); } @Override public ImmutabilityPolicyProperties immutabilityPolicy() { return this.inner().immutabilityPolicy(); } @Override public OffsetDateTime lastModifiedTime() { return this.inner().lastModifiedTime(); } @Override public LeaseDuration leaseDuration() { return this.inner().leaseDuration(); } @Override public LeaseState leaseState() { return this.inner().leaseState(); } @Override public LeaseStatus leaseStatus() { return this.inner().leaseStatus(); } @Override public LegalHoldProperties legalHold() { return this.inner().legalHold(); } @Override public Map<String, String> metadata() { return this.inner().metadata(); } @Override public String name() { return this.inner().getName(); } @Override public PublicAccess publicAccess() { return this.inner().publicAccess(); } @Override public String type() { return this.inner().getType(); } @Override public BlobContainerImpl withExistingBlobService(String resourceGroupName, String accountName) { this.resourceGroupName = resourceGroupName; this.accountName = accountName; return this; } @Override public BlobContainerImpl withPublicAccess(PublicAccess publicAccess) { if (isInCreateMode()) { this.cpublicAccess = publicAccess; } else { this.upublicAccess = publicAccess; } return this; } @Override public BlobContainerImpl withMetadata(Map<String, String> metadata) { if (isInCreateMode()) { this.cmetadata = metadata; } else { this.umetadata = metadata; } return this; } @Override public BlobContainerImpl withMetadata(String name, String value) { if (isInCreateMode()) { if (this.cmetadata == null) { this.cmetadata = new HashMap<>(); } this.cmetadata.put(name, value); } else { if (this.umetadata == null) { this.umetadata = new HashMap<>(); } this.umetadata.put(name, value); } return this; } }
I'll take a look.
public Mono<BlobContainer> createResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner()) .map(innerToFluentMap(this)); }
.createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner())
public Mono<BlobContainer> createResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner().withPublicAccess(cpublicAccess).withMetadata(cmetadata)) .map(innerToFluentMap(this)); }
class BlobContainerImpl extends CreatableUpdatableImpl<BlobContainer, BlobContainerInner, BlobContainerImpl> implements BlobContainer, BlobContainer.Definition, BlobContainer.Update { private final StorageManager manager; private String resourceGroupName; private String accountName; private String containerName; private PublicAccess cpublicAccess; private Map<String, String> cmetadata; private PublicAccess upublicAccess; private Map<String, String> umetadata; BlobContainerImpl(String name, StorageManager manager) { super(name, new BlobContainerInner()); this.manager = manager; this.containerName = name; } BlobContainerImpl(BlobContainerInner inner, StorageManager manager) { super(inner.getName(), inner); this.manager = manager; this.containerName = inner.getName(); this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.getId(), "resourceGroups"); this.accountName = IdParsingUtils.getValueFromIdByName(inner.getId(), "storageAccounts"); this.containerName = IdParsingUtils.getValueFromIdByName(inner.getId(), "containers"); } @Override public StorageManager manager() { return this.manager; } @Override @Override public Mono<BlobContainer> updateResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .updateAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner()) .map(innerToFluentMap(this)); } @Override protected Mono<BlobContainerInner> getInnerAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return null; } @Override public boolean isInCreateMode() { return this.inner().getId() == null; } @Override public String etag() { return this.inner().etag(); } @Override public Boolean hasImmutabilityPolicy() { return this.inner().hasImmutabilityPolicy(); } @Override public Boolean hasLegalHold() { return this.inner().hasLegalHold(); } @Override public String id() { return this.inner().getId(); } @Override public ImmutabilityPolicyProperties immutabilityPolicy() { return this.inner().immutabilityPolicy(); } @Override public OffsetDateTime lastModifiedTime() { return this.inner().lastModifiedTime(); } @Override public LeaseDuration leaseDuration() { return this.inner().leaseDuration(); } @Override public LeaseState leaseState() { return this.inner().leaseState(); } @Override public LeaseStatus leaseStatus() { return this.inner().leaseStatus(); } @Override public LegalHoldProperties legalHold() { return this.inner().legalHold(); } @Override public Map<String, String> metadata() { return this.inner().metadata(); } @Override public String name() { return this.inner().getName(); } @Override public PublicAccess publicAccess() { return this.inner().publicAccess(); } @Override public String type() { return this.inner().getType(); } @Override public BlobContainerImpl withExistingBlobService(String resourceGroupName, String accountName) { this.resourceGroupName = resourceGroupName; this.accountName = accountName; return this; } @Override public BlobContainerImpl withPublicAccess(PublicAccess publicAccess) { if (isInCreateMode()) { this.cpublicAccess = publicAccess; } else { this.upublicAccess = publicAccess; } return this; } @Override public BlobContainerImpl withMetadata(Map<String, String> metadata) { if (isInCreateMode()) { this.cmetadata = metadata; } else { this.umetadata = metadata; } return this; } @Override public BlobContainerImpl withMetadata(String name, String value) { if (isInCreateMode()) { if (this.cmetadata == null) { this.cmetadata = new HashMap<>(); } this.cmetadata.put(name, value); } else { if (this.umetadata == null) { this.umetadata = new HashMap<>(); } this.umetadata.put(name, value); } return this; } }
class BlobContainerImpl extends CreatableUpdatableImpl<BlobContainer, BlobContainerInner, BlobContainerImpl> implements BlobContainer, BlobContainer.Definition, BlobContainer.Update { private final StorageManager manager; private String resourceGroupName; private String accountName; private String containerName; private PublicAccess cpublicAccess; private Map<String, String> cmetadata; private PublicAccess upublicAccess; private Map<String, String> umetadata; BlobContainerImpl(String name, StorageManager manager) { super(name, new BlobContainerInner()); this.manager = manager; this.containerName = name; } BlobContainerImpl(BlobContainerInner inner, StorageManager manager) { super(inner.getName(), inner); this.manager = manager; this.containerName = inner.getName(); this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.getId(), "resourceGroups"); this.accountName = IdParsingUtils.getValueFromIdByName(inner.getId(), "storageAccounts"); this.containerName = IdParsingUtils.getValueFromIdByName(inner.getId(), "containers"); } @Override public StorageManager manager() { return this.manager; } @Override @Override public Mono<BlobContainer> updateResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .updateAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner().withPublicAccess(upublicAccess).withMetadata(umetadata)) .map(innerToFluentMap(this)); } @Override protected Mono<BlobContainerInner> getInnerAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return null; } @Override public boolean isInCreateMode() { return this.inner().getId() == null; } @Override public String etag() { return this.inner().etag(); } @Override public Boolean hasImmutabilityPolicy() { return this.inner().hasImmutabilityPolicy(); } @Override public Boolean hasLegalHold() { return this.inner().hasLegalHold(); } @Override public String id() { return this.inner().getId(); } @Override public ImmutabilityPolicyProperties immutabilityPolicy() { return this.inner().immutabilityPolicy(); } @Override public OffsetDateTime lastModifiedTime() { return this.inner().lastModifiedTime(); } @Override public LeaseDuration leaseDuration() { return this.inner().leaseDuration(); } @Override public LeaseState leaseState() { return this.inner().leaseState(); } @Override public LeaseStatus leaseStatus() { return this.inner().leaseStatus(); } @Override public LegalHoldProperties legalHold() { return this.inner().legalHold(); } @Override public Map<String, String> metadata() { return this.inner().metadata(); } @Override public String name() { return this.inner().getName(); } @Override public PublicAccess publicAccess() { return this.inner().publicAccess(); } @Override public String type() { return this.inner().getType(); } @Override public BlobContainerImpl withExistingBlobService(String resourceGroupName, String accountName) { this.resourceGroupName = resourceGroupName; this.accountName = accountName; return this; } @Override public BlobContainerImpl withPublicAccess(PublicAccess publicAccess) { if (isInCreateMode()) { this.cpublicAccess = publicAccess; } else { this.upublicAccess = publicAccess; } return this; } @Override public BlobContainerImpl withMetadata(Map<String, String> metadata) { if (isInCreateMode()) { this.cmetadata = metadata; } else { this.umetadata = metadata; } return this; } @Override public BlobContainerImpl withMetadata(String name, String value) { if (isInCreateMode()) { if (this.cmetadata == null) { this.cmetadata = new HashMap<>(); } this.cmetadata.put(name, value); } else { if (this.umetadata == null) { this.umetadata = new HashMap<>(); } this.umetadata.put(name, value); } return this; } }
Add parameter done.
public Mono<BlobContainer> createResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner()) .map(innerToFluentMap(this)); }
.createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner())
public Mono<BlobContainer> createResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .createAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner().withPublicAccess(cpublicAccess).withMetadata(cmetadata)) .map(innerToFluentMap(this)); }
class BlobContainerImpl extends CreatableUpdatableImpl<BlobContainer, BlobContainerInner, BlobContainerImpl> implements BlobContainer, BlobContainer.Definition, BlobContainer.Update { private final StorageManager manager; private String resourceGroupName; private String accountName; private String containerName; private PublicAccess cpublicAccess; private Map<String, String> cmetadata; private PublicAccess upublicAccess; private Map<String, String> umetadata; BlobContainerImpl(String name, StorageManager manager) { super(name, new BlobContainerInner()); this.manager = manager; this.containerName = name; } BlobContainerImpl(BlobContainerInner inner, StorageManager manager) { super(inner.getName(), inner); this.manager = manager; this.containerName = inner.getName(); this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.getId(), "resourceGroups"); this.accountName = IdParsingUtils.getValueFromIdByName(inner.getId(), "storageAccounts"); this.containerName = IdParsingUtils.getValueFromIdByName(inner.getId(), "containers"); } @Override public StorageManager manager() { return this.manager; } @Override @Override public Mono<BlobContainer> updateResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .updateAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner()) .map(innerToFluentMap(this)); } @Override protected Mono<BlobContainerInner> getInnerAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return null; } @Override public boolean isInCreateMode() { return this.inner().getId() == null; } @Override public String etag() { return this.inner().etag(); } @Override public Boolean hasImmutabilityPolicy() { return this.inner().hasImmutabilityPolicy(); } @Override public Boolean hasLegalHold() { return this.inner().hasLegalHold(); } @Override public String id() { return this.inner().getId(); } @Override public ImmutabilityPolicyProperties immutabilityPolicy() { return this.inner().immutabilityPolicy(); } @Override public OffsetDateTime lastModifiedTime() { return this.inner().lastModifiedTime(); } @Override public LeaseDuration leaseDuration() { return this.inner().leaseDuration(); } @Override public LeaseState leaseState() { return this.inner().leaseState(); } @Override public LeaseStatus leaseStatus() { return this.inner().leaseStatus(); } @Override public LegalHoldProperties legalHold() { return this.inner().legalHold(); } @Override public Map<String, String> metadata() { return this.inner().metadata(); } @Override public String name() { return this.inner().getName(); } @Override public PublicAccess publicAccess() { return this.inner().publicAccess(); } @Override public String type() { return this.inner().getType(); } @Override public BlobContainerImpl withExistingBlobService(String resourceGroupName, String accountName) { this.resourceGroupName = resourceGroupName; this.accountName = accountName; return this; } @Override public BlobContainerImpl withPublicAccess(PublicAccess publicAccess) { if (isInCreateMode()) { this.cpublicAccess = publicAccess; } else { this.upublicAccess = publicAccess; } return this; } @Override public BlobContainerImpl withMetadata(Map<String, String> metadata) { if (isInCreateMode()) { this.cmetadata = metadata; } else { this.umetadata = metadata; } return this; } @Override public BlobContainerImpl withMetadata(String name, String value) { if (isInCreateMode()) { if (this.cmetadata == null) { this.cmetadata = new HashMap<>(); } this.cmetadata.put(name, value); } else { if (this.umetadata == null) { this.umetadata = new HashMap<>(); } this.umetadata.put(name, value); } return this; } }
class BlobContainerImpl extends CreatableUpdatableImpl<BlobContainer, BlobContainerInner, BlobContainerImpl> implements BlobContainer, BlobContainer.Definition, BlobContainer.Update { private final StorageManager manager; private String resourceGroupName; private String accountName; private String containerName; private PublicAccess cpublicAccess; private Map<String, String> cmetadata; private PublicAccess upublicAccess; private Map<String, String> umetadata; BlobContainerImpl(String name, StorageManager manager) { super(name, new BlobContainerInner()); this.manager = manager; this.containerName = name; } BlobContainerImpl(BlobContainerInner inner, StorageManager manager) { super(inner.getName(), inner); this.manager = manager; this.containerName = inner.getName(); this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.getId(), "resourceGroups"); this.accountName = IdParsingUtils.getValueFromIdByName(inner.getId(), "storageAccounts"); this.containerName = IdParsingUtils.getValueFromIdByName(inner.getId(), "containers"); } @Override public StorageManager manager() { return this.manager; } @Override @Override public Mono<BlobContainer> updateResourceAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return client .updateAsync(this.resourceGroupName, this.accountName, this.containerName, this.inner().withPublicAccess(upublicAccess).withMetadata(umetadata)) .map(innerToFluentMap(this)); } @Override protected Mono<BlobContainerInner> getInnerAsync() { BlobContainersInner client = this.manager().inner().blobContainers(); return null; } @Override public boolean isInCreateMode() { return this.inner().getId() == null; } @Override public String etag() { return this.inner().etag(); } @Override public Boolean hasImmutabilityPolicy() { return this.inner().hasImmutabilityPolicy(); } @Override public Boolean hasLegalHold() { return this.inner().hasLegalHold(); } @Override public String id() { return this.inner().getId(); } @Override public ImmutabilityPolicyProperties immutabilityPolicy() { return this.inner().immutabilityPolicy(); } @Override public OffsetDateTime lastModifiedTime() { return this.inner().lastModifiedTime(); } @Override public LeaseDuration leaseDuration() { return this.inner().leaseDuration(); } @Override public LeaseState leaseState() { return this.inner().leaseState(); } @Override public LeaseStatus leaseStatus() { return this.inner().leaseStatus(); } @Override public LegalHoldProperties legalHold() { return this.inner().legalHold(); } @Override public Map<String, String> metadata() { return this.inner().metadata(); } @Override public String name() { return this.inner().getName(); } @Override public PublicAccess publicAccess() { return this.inner().publicAccess(); } @Override public String type() { return this.inner().getType(); } @Override public BlobContainerImpl withExistingBlobService(String resourceGroupName, String accountName) { this.resourceGroupName = resourceGroupName; this.accountName = accountName; return this; } @Override public BlobContainerImpl withPublicAccess(PublicAccess publicAccess) { if (isInCreateMode()) { this.cpublicAccess = publicAccess; } else { this.upublicAccess = publicAccess; } return this; } @Override public BlobContainerImpl withMetadata(Map<String, String> metadata) { if (isInCreateMode()) { this.cmetadata = metadata; } else { this.umetadata = metadata; } return this; } @Override public BlobContainerImpl withMetadata(String name, String value) { if (isInCreateMode()) { if (this.cmetadata == null) { this.cmetadata = new HashMap<>(); } this.cmetadata.put(name, value); } else { if (this.umetadata == null) { this.umetadata = new HashMap<>(); } this.umetadata.put(name, value); } return this; } }
Better still use the enum
public NetworkSecurityRuleImpl withAnyProtocol() { return this.withProtocol(SecurityRuleProtocol.fromString("*")); }
return this.withProtocol(SecurityRuleProtocol.fromString("*"));
public NetworkSecurityRuleImpl withAnyProtocol() { return this.withProtocol(SecurityRuleProtocol.STAR); }
class NetworkSecurityRuleImpl extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup> implements NetworkSecurityRule, NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>, NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>, NetworkSecurityRule.Update { private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>(); private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>(); NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) { super(inner, parent); if (inner.sourceApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) { sourceAsgs.put(asg.getId(), asg); } } if (inner.destinationApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) { destinationAsgs.put(asg.getId(), asg); } } } @Override public String name() { return this.inner().name(); } @Override public SecurityRuleDirection direction() { return this.inner().direction(); } @Override public SecurityRuleProtocol protocol() { return this.inner().protocol(); } @Override public SecurityRuleAccess access() { return this.inner().access(); } @Override public String sourceAddressPrefix() { return this.inner().sourceAddressPrefix(); } @Override public List<String> sourceAddressPrefixes() { return Collections.unmodifiableList(this.inner().sourceAddressPrefixes()); } @Override public String sourcePortRange() { return this.inner().sourcePortRange(); } @Override public List<String> sourcePortRanges() { return Collections.unmodifiableList(inner().sourcePortRanges()); } @Override public String destinationAddressPrefix() { return this.inner().destinationAddressPrefix(); } @Override public List<String> destinationAddressPrefixes() { return Collections.unmodifiableList(this.inner().destinationAddressPrefixes()); } @Override public String destinationPortRange() { return this.inner().destinationPortRange(); } @Override public List<String> destinationPortRanges() { return Collections.unmodifiableList(inner().destinationPortRanges()); } @Override public int priority() { return Utils.toPrimitiveInt(this.inner().priority()); } @Override public Set<String> sourceApplicationSecurityGroupIds() { return Collections.unmodifiableSet(sourceAsgs.keySet()); } @Override public Set<String> destinationApplicationSecurityGroupIds() { return Collections.unmodifiableSet(destinationAsgs.keySet()); } @Override public NetworkSecurityRuleImpl allowInbound() { return this .withDirection(SecurityRuleDirection.INBOUND) .withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl allowOutbound() { return this .withDirection(SecurityRuleDirection.OUTBOUND) .withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl denyInbound() { return this .withDirection(SecurityRuleDirection.INBOUND) .withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl denyOutbound() { return this .withDirection(SecurityRuleDirection.OUTBOUND) .withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) { this.inner().withProtocol(protocol); return this; } @Override @Override public NetworkSecurityRuleImpl fromAddress(String cidr) { this.inner().withSourceAddressPrefix(cidr); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyAddress() { this.inner().withSourceAddressPrefix("*"); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAddresses(String... addresses) { this.inner().withSourceAddressPrefixes(Arrays.asList(addresses)); this.inner().withSourceAddressPrefix(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromPort(int port) { this.inner().withSourcePortRange(String.valueOf(port)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyPort() { this.inner().withSourcePortRange("*"); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRange(int from, int to) { this.inner().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRanges(String... ranges) { this.inner().withSourcePortRanges(Arrays.asList(ranges)); this.inner().withSourcePortRange(null); return this; } @Override public NetworkSecurityRuleImpl toAddress(String cidr) { this.inner().withDestinationAddressPrefix(cidr); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAddresses(String... addresses) { this.inner().withDestinationAddressPrefixes(Arrays.asList(addresses)); this.inner().withDestinationAddressPrefix(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAnyAddress() { this.inner().withDestinationAddressPrefix("*"); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toPort(int port) { this.inner().withDestinationPortRange(String.valueOf(port)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toAnyPort() { this.inner().withDestinationPortRange("*"); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRange(int from, int to) { this.inner().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRanges(String... ranges) { this.inner().withDestinationPortRanges(Arrays.asList(ranges)); this.inner().withDestinationPortRange(null); return this; } @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { throw new IllegalArgumentException("The priority number of a network security rule must be between 100 and 4096."); } this.inner().withPriority(priority); return this; } @Override public NetworkSecurityRuleImpl withDescription(String description) { this.inner().withDescription(description); return this; } @Override public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) { sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withSourceAddressPrefix(null); inner().withSourceAddressPrefixes(null); return this; } @Override public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) { destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withDestinationAddressPrefix(null); inner().withDestinationAddressPrefixes(null); return this; } private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) { this.inner().withDirection(direction); return this; } private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) { this.inner().withAccess(permission); return this; } @Override public NetworkSecurityGroupImpl attach() { inner().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values())); inner().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values())); return this.parent().withRule(this); } @Override public String description() { return this.inner().description(); } }
class NetworkSecurityRuleImpl extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup> implements NetworkSecurityRule, NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>, NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>, NetworkSecurityRule.Update { private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>(); private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>(); private final ClientLogger logger = new ClientLogger(getClass()); NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) { super(inner, parent); if (inner.sourceApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) { sourceAsgs.put(asg.getId(), asg); } } if (inner.destinationApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) { destinationAsgs.put(asg.getId(), asg); } } } @Override public String name() { return this.inner().name(); } @Override public SecurityRuleDirection direction() { return this.inner().direction(); } @Override public SecurityRuleProtocol protocol() { return this.inner().protocol(); } @Override public SecurityRuleAccess access() { return this.inner().access(); } @Override public String sourceAddressPrefix() { return this.inner().sourceAddressPrefix(); } @Override public List<String> sourceAddressPrefixes() { return Collections.unmodifiableList(this.inner().sourceAddressPrefixes()); } @Override public String sourcePortRange() { return this.inner().sourcePortRange(); } @Override public List<String> sourcePortRanges() { return Collections.unmodifiableList(inner().sourcePortRanges()); } @Override public String destinationAddressPrefix() { return this.inner().destinationAddressPrefix(); } @Override public List<String> destinationAddressPrefixes() { return Collections.unmodifiableList(this.inner().destinationAddressPrefixes()); } @Override public String destinationPortRange() { return this.inner().destinationPortRange(); } @Override public List<String> destinationPortRanges() { return Collections.unmodifiableList(inner().destinationPortRanges()); } @Override public int priority() { return Utils.toPrimitiveInt(this.inner().priority()); } @Override public Set<String> sourceApplicationSecurityGroupIds() { return Collections.unmodifiableSet(sourceAsgs.keySet()); } @Override public Set<String> destinationApplicationSecurityGroupIds() { return Collections.unmodifiableSet(destinationAsgs.keySet()); } @Override public NetworkSecurityRuleImpl allowInbound() { return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl allowOutbound() { return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl denyInbound() { return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl denyOutbound() { return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) { this.inner().withProtocol(protocol); return this; } @Override @Override public NetworkSecurityRuleImpl fromAddress(String cidr) { this.inner().withSourceAddressPrefix(cidr); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyAddress() { this.inner().withSourceAddressPrefix("*"); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAddresses(String... addresses) { this.inner().withSourceAddressPrefixes(Arrays.asList(addresses)); this.inner().withSourceAddressPrefix(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromPort(int port) { this.inner().withSourcePortRange(String.valueOf(port)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyPort() { this.inner().withSourcePortRange("*"); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRange(int from, int to) { this.inner().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRanges(String... ranges) { this.inner().withSourcePortRanges(Arrays.asList(ranges)); this.inner().withSourcePortRange(null); return this; } @Override public NetworkSecurityRuleImpl toAddress(String cidr) { this.inner().withDestinationAddressPrefix(cidr); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAddresses(String... addresses) { this.inner().withDestinationAddressPrefixes(Arrays.asList(addresses)); this.inner().withDestinationAddressPrefix(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAnyAddress() { this.inner().withDestinationAddressPrefix("*"); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toPort(int port) { this.inner().withDestinationPortRange(String.valueOf(port)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toAnyPort() { this.inner().withDestinationPortRange("*"); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRange(int from, int to) { this.inner().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRanges(String... ranges) { this.inner().withDestinationPortRanges(Arrays.asList(ranges)); this.inner().withDestinationPortRange(null); return this; } @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { throw logger.logExceptionAsError(new IllegalArgumentException( "The priority number of a network security rule must be between 100 and 4096.")); } this.inner().withPriority(priority); return this; } @Override public NetworkSecurityRuleImpl withDescription(String description) { this.inner().withDescription(description); return this; } @Override public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) { sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withSourceAddressPrefix(null); inner().withSourceAddressPrefixes(null); return this; } @Override public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) { destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withDestinationAddressPrefix(null); inner().withDestinationAddressPrefixes(null); return this; } private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) { this.inner().withDirection(direction); return this; } private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) { this.inner().withAccess(permission); return this; } @Override public NetworkSecurityGroupImpl attach() { inner().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values())); inner().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values())); return this.parent().withRule(this); } @Override public String description() { return this.inner().description(); } }
This TODO can be solved now
protected Mono<NetworkInterfaceInner> getInnerAsync() { return this .manager() .inner() .networkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name(), null); }
protected Mono<NetworkInterfaceInner> getInnerAsync() { return this .manager() .inner() .networkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); }
class NetworkInterfaceImpl extends GroupableParentResourceWithTagsImpl< NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { /** the name of the network interface. */ private final String nicName; /** used to generate unique name for any dependency resources. */ protected final ResourceNamer namer; /** references to all ip configuration. */ private Map<String, NicIPConfiguration> nicIPConfigurations; /** unique key of a creatable network security group to be associated with the network interface. */ private String creatableNetworkSecurityGroupKey; /** reference to an network security group to be associated with the network interface. */ private NetworkSecurityGroup existingNetworkSecurityGroupToAssociate; /** cached related resources. */ private NetworkSecurityGroup networkSecurityGroup; NetworkInterfaceImpl(String name, NetworkInterfaceInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.nicName = name; this.namer = this.manager().getSdkContext().getResourceNamerFactory().createResourceNamer(this.nicName); initializeChildrenFromInner(); } @Override public Mono<NetworkInterface> refreshAsync() { return super .refreshAsync() .map( networkInterface -> { NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; impl.clearCachedRelatedResources(); impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkInterfaceInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkInterfaces() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public NetworkInterfaceImpl withAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(true); return this; } @Override public NetworkInterfaceImpl withoutAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(false); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(Creatable<Network> creatable) { this.primaryIPConfiguration().withNewNetwork(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String name, String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(name, addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryNetwork(Network network) { this.primaryIPConfiguration().withExistingNetwork(network); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) { this.primaryIPConfiguration().withNewPublicIPAddress(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress() { this.primaryIPConfiguration().withNewPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { this.primaryIPConfiguration().withNewPublicIPAddress(leafDnsLabel); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBalancer, String backendName) { this.primaryIPConfiguration().withExistingLoadBalancerBackend(loadBalancer, backendName); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( LoadBalancer loadBalancer, String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @Override public Update withoutLoadBalancerBackends() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerBackends(); } return this; } @Override public Update withoutLoadBalancerInboundNatRules() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerInboundNatRules(); } return this; } @Override public NetworkInterfaceImpl withoutPrimaryPublicIPAddress() { this.primaryIPConfiguration().withoutPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) { this.primaryIPConfiguration().withExistingPublicIPAddress(publicIPAddress); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressDynamic() { this.primaryIPConfiguration().withPrivateIPAddressDynamic(); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { this.primaryIPConfiguration().withPrivateIPAddressStatic(staticPrivateIPAddress); return this; } @Override public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) { if (this.creatableNetworkSecurityGroupKey == null) { this.creatableNetworkSecurityGroupKey = this.addDependency(creatable); } return this; } @Override public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) { this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup; return this; } @Override public NetworkInterfaceImpl withoutNetworkSecurityGroup() { this.inner().withNetworkSecurityGroup(null); return this; } @Override public NicIPConfigurationImpl defineSecondaryIPConfiguration(String name) { return prepareNewNicIPConfiguration(name); } @Override public NicIPConfigurationImpl updateIPConfiguration(String name) { return (NicIPConfigurationImpl) this.nicIPConfigurations.get(name); } @Override public NetworkInterfaceImpl withIPForwarding() { this.inner().withEnableIPForwarding(true); return this; } @Override public NetworkInterfaceImpl withoutIPConfiguration(String name) { this.nicIPConfigurations.remove(name); return this; } @Override public NetworkInterfaceImpl withoutIPForwarding() { this.inner().withEnableIPForwarding(false); return this; } @Override public NetworkInterfaceImpl withDnsServer(String ipAddress) { this.dnsServerIPs().add(ipAddress); return this; } @Override public NetworkInterfaceImpl withoutDnsServer(String ipAddress) { this.dnsServerIPs().remove(ipAddress); return this; } @Override public NetworkInterfaceImpl withAzureDnsServer() { this.dnsServerIPs().clear(); return this; } @Override public NetworkInterfaceImpl withSubnet(String name) { this.primaryIPConfiguration().withSubnet(name); return this; } @Override public NetworkInterfaceImpl withInternalDnsNameLabel(String dnsNameLabel) { this.inner().dnsSettings().withInternalDnsNameLabel(dnsNameLabel); return this; } @Override public boolean isAcceleratedNetworkingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableAcceleratedNetworking()); } @Override public String virtualMachineId() { if (this.inner().virtualMachine() != null) { return this.inner().virtualMachine().getId(); } else { return null; } } @Override public boolean isIPForwardingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableIPForwarding()); } @Override public String macAddress() { return this.inner().macAddress(); } @Override public String internalDnsNameLabel() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDnsNameLabel() : null; } @Override public String internalDomainNameSuffix() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDomainNameSuffix() : null; } @Override public List<String> appliedDnsServers() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return Collections.unmodifiableList(dnsServers); } else if (this.inner().dnsSettings().appliedDnsServers() == null) { return Collections.unmodifiableList(dnsServers); } else { return Collections.unmodifiableList(this.inner().dnsSettings().appliedDnsServers()); } } @Override public String internalFqdn() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalFqdn() : null; } @Override public List<String> dnsServers() { return this.dnsServerIPs(); } @Override public String primaryPrivateIP() { return this.primaryIPConfiguration().privateIPAddress(); } @Override public IPAllocationMethod primaryPrivateIPAllocationMethod() { return this.primaryIPConfiguration().privateIPAllocationMethod(); } @Override public Map<String, NicIPConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.nicIPConfigurations); } @Override public String networkSecurityGroupId() { return (this.inner().networkSecurityGroup() != null) ? this.inner().networkSecurityGroup().getId() : null; } @Override public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); this.networkSecurityGroup = super .myManager .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } /** @return the primary IP configuration of the network interface */ @Override public NicIPConfigurationImpl primaryIPConfiguration() { NicIPConfigurationImpl primaryIPConfig = null; if (this.nicIPConfigurations.size() == 0) { primaryIPConfig = prepareNewNicIPConfiguration("primary"); primaryIPConfig.inner().withPrimary(true); withIPConfiguration(primaryIPConfig); } else if (this.nicIPConfigurations.size() == 1) { primaryIPConfig = (NicIPConfigurationImpl) this.nicIPConfigurations.values().iterator().next(); } else { for (NicIPConfiguration ipConfig : this.nicIPConfigurations.values()) { if (ipConfig.isPrimary()) { primaryIPConfig = (NicIPConfigurationImpl) ipConfig; break; } } } return primaryIPConfig; } /** @return the list of DNS server IPs from the DNS settings */ private List<String> dnsServerIPs() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return dnsServers; } else if (this.inner().dnsSettings().dnsServers() == null) { return dnsServers; } else { return this.inner().dnsSettings().dnsServers(); } } @Override protected void initializeChildrenFromInner() { this.nicIPConfigurations = new TreeMap<>(); List<NetworkInterfaceIPConfigurationInner> inners = this.inner().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIPConfigurationInner inner : inners) { NicIPConfigurationImpl nicIPConfiguration = new NicIPConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } } /** * Gets a new IP configuration child resource {@link NicIPConfiguration} wrapping {@link * NetworkInterfaceIPConfigurationInner}. * * @param name the name for the new ip configuration * @return {@link NicIPConfiguration} */ private NicIPConfigurationImpl prepareNewNicIPConfiguration(String name) { NicIPConfigurationImpl nicIPConfiguration = NicIPConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } private void clearCachedRelatedResources() { this.networkSecurityGroup = null; } NetworkInterfaceImpl withIPConfiguration(NicIPConfigurationImpl nicIPConfiguration) { this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); return this; } void addToCreatableDependencies(Creatable<? extends Resource> creatableResource) { this.addDependency(creatableResource); } Resource createdDependencyResource(String key) { return this.<Resource>taskResult(key); } Creatable<ResourceGroup> newGroup() { return this.creatableGroup; } @Override protected Mono<NetworkInterfaceInner> createInner() { return this .manager() .inner() .networkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override protected void afterCreating() { clearCachedRelatedResources(); } @Override protected void beforeCreating() { NetworkSecurityGroup networkSecurityGroup = null; if (creatableNetworkSecurityGroupKey != null) { networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey); } else if (existingNetworkSecurityGroupToAssociate != null) { networkSecurityGroup = existingNetworkSecurityGroupToAssociate; } if (networkSecurityGroup != null) { this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values()); this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values())); } }
class NetworkInterfaceImpl extends GroupableParentResourceWithTagsImpl< NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { /** the name of the network interface. */ private final String nicName; /** used to generate unique name for any dependency resources. */ protected final ResourceNamer namer; /** references to all ip configuration. */ private Map<String, NicIPConfiguration> nicIPConfigurations; /** unique key of a creatable network security group to be associated with the network interface. */ private String creatableNetworkSecurityGroupKey; /** reference to an network security group to be associated with the network interface. */ private NetworkSecurityGroup existingNetworkSecurityGroupToAssociate; /** cached related resources. */ private NetworkSecurityGroup networkSecurityGroup; NetworkInterfaceImpl(String name, NetworkInterfaceInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.nicName = name; this.namer = this.manager().getSdkContext().getResourceNamerFactory().createResourceNamer(this.nicName); initializeChildrenFromInner(); } @Override public Mono<NetworkInterface> refreshAsync() { return super .refreshAsync() .map( networkInterface -> { NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; impl.clearCachedRelatedResources(); impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkInterfaceInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkInterfaces() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public NetworkInterfaceImpl withAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(true); return this; } @Override public NetworkInterfaceImpl withoutAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(false); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(Creatable<Network> creatable) { this.primaryIPConfiguration().withNewNetwork(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String name, String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(name, addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryNetwork(Network network) { this.primaryIPConfiguration().withExistingNetwork(network); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) { this.primaryIPConfiguration().withNewPublicIPAddress(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress() { this.primaryIPConfiguration().withNewPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { this.primaryIPConfiguration().withNewPublicIPAddress(leafDnsLabel); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBalancer, String backendName) { this.primaryIPConfiguration().withExistingLoadBalancerBackend(loadBalancer, backendName); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( LoadBalancer loadBalancer, String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @Override public Update withoutLoadBalancerBackends() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerBackends(); } return this; } @Override public Update withoutLoadBalancerInboundNatRules() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerInboundNatRules(); } return this; } @Override public NetworkInterfaceImpl withoutPrimaryPublicIPAddress() { this.primaryIPConfiguration().withoutPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) { this.primaryIPConfiguration().withExistingPublicIPAddress(publicIPAddress); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressDynamic() { this.primaryIPConfiguration().withPrivateIPAddressDynamic(); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { this.primaryIPConfiguration().withPrivateIPAddressStatic(staticPrivateIPAddress); return this; } @Override public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) { if (this.creatableNetworkSecurityGroupKey == null) { this.creatableNetworkSecurityGroupKey = this.addDependency(creatable); } return this; } @Override public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) { this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup; return this; } @Override public NetworkInterfaceImpl withoutNetworkSecurityGroup() { this.inner().withNetworkSecurityGroup(null); return this; } @Override public NicIPConfigurationImpl defineSecondaryIPConfiguration(String name) { return prepareNewNicIPConfiguration(name); } @Override public NicIPConfigurationImpl updateIPConfiguration(String name) { return (NicIPConfigurationImpl) this.nicIPConfigurations.get(name); } @Override public NetworkInterfaceImpl withIPForwarding() { this.inner().withEnableIPForwarding(true); return this; } @Override public NetworkInterfaceImpl withoutIPConfiguration(String name) { this.nicIPConfigurations.remove(name); return this; } @Override public NetworkInterfaceImpl withoutIPForwarding() { this.inner().withEnableIPForwarding(false); return this; } @Override public NetworkInterfaceImpl withDnsServer(String ipAddress) { this.dnsServerIPs().add(ipAddress); return this; } @Override public NetworkInterfaceImpl withoutDnsServer(String ipAddress) { this.dnsServerIPs().remove(ipAddress); return this; } @Override public NetworkInterfaceImpl withAzureDnsServer() { this.dnsServerIPs().clear(); return this; } @Override public NetworkInterfaceImpl withSubnet(String name) { this.primaryIPConfiguration().withSubnet(name); return this; } @Override public NetworkInterfaceImpl withInternalDnsNameLabel(String dnsNameLabel) { this.inner().dnsSettings().withInternalDnsNameLabel(dnsNameLabel); return this; } @Override public boolean isAcceleratedNetworkingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableAcceleratedNetworking()); } @Override public String virtualMachineId() { if (this.inner().virtualMachine() != null) { return this.inner().virtualMachine().getId(); } else { return null; } } @Override public boolean isIPForwardingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableIPForwarding()); } @Override public String macAddress() { return this.inner().macAddress(); } @Override public String internalDnsNameLabel() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDnsNameLabel() : null; } @Override public String internalDomainNameSuffix() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDomainNameSuffix() : null; } @Override public List<String> appliedDnsServers() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return Collections.unmodifiableList(dnsServers); } else if (this.inner().dnsSettings().appliedDnsServers() == null) { return Collections.unmodifiableList(dnsServers); } else { return Collections.unmodifiableList(this.inner().dnsSettings().appliedDnsServers()); } } @Override public String internalFqdn() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalFqdn() : null; } @Override public List<String> dnsServers() { return this.dnsServerIPs(); } @Override public String primaryPrivateIP() { return this.primaryIPConfiguration().privateIPAddress(); } @Override public IPAllocationMethod primaryPrivateIPAllocationMethod() { return this.primaryIPConfiguration().privateIPAllocationMethod(); } @Override public Map<String, NicIPConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.nicIPConfigurations); } @Override public String networkSecurityGroupId() { return (this.inner().networkSecurityGroup() != null) ? this.inner().networkSecurityGroup().getId() : null; } @Override public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); this.networkSecurityGroup = super .myManager .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } /** @return the primary IP configuration of the network interface */ @Override public NicIPConfigurationImpl primaryIPConfiguration() { NicIPConfigurationImpl primaryIPConfig = null; if (this.nicIPConfigurations.size() == 0) { primaryIPConfig = prepareNewNicIPConfiguration("primary"); primaryIPConfig.inner().withPrimary(true); withIPConfiguration(primaryIPConfig); } else if (this.nicIPConfigurations.size() == 1) { primaryIPConfig = (NicIPConfigurationImpl) this.nicIPConfigurations.values().iterator().next(); } else { for (NicIPConfiguration ipConfig : this.nicIPConfigurations.values()) { if (ipConfig.isPrimary()) { primaryIPConfig = (NicIPConfigurationImpl) ipConfig; break; } } } return primaryIPConfig; } /** @return the list of DNS server IPs from the DNS settings */ private List<String> dnsServerIPs() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return dnsServers; } else if (this.inner().dnsSettings().dnsServers() == null) { return dnsServers; } else { return this.inner().dnsSettings().dnsServers(); } } @Override protected void initializeChildrenFromInner() { this.nicIPConfigurations = new TreeMap<>(); List<NetworkInterfaceIPConfigurationInner> inners = this.inner().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIPConfigurationInner inner : inners) { NicIPConfigurationImpl nicIPConfiguration = new NicIPConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } } /** * Gets a new IP configuration child resource {@link NicIPConfiguration} wrapping {@link * NetworkInterfaceIPConfigurationInner}. * * @param name the name for the new ip configuration * @return {@link NicIPConfiguration} */ private NicIPConfigurationImpl prepareNewNicIPConfiguration(String name) { NicIPConfigurationImpl nicIPConfiguration = NicIPConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } private void clearCachedRelatedResources() { this.networkSecurityGroup = null; } NetworkInterfaceImpl withIPConfiguration(NicIPConfigurationImpl nicIPConfiguration) { this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); return this; } void addToCreatableDependencies(Creatable<? extends Resource> creatableResource) { this.addDependency(creatableResource); } Resource createdDependencyResource(String key) { return this.<Resource>taskResult(key); } Creatable<ResourceGroup> newGroup() { return this.creatableGroup; } @Override protected Mono<NetworkInterfaceInner> createInner() { return this .manager() .inner() .networkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override protected void afterCreating() { clearCachedRelatedResources(); } @Override protected void beforeCreating() { NetworkSecurityGroup networkSecurityGroup = null; if (creatableNetworkSecurityGroupKey != null) { networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey); } else if (existingNetworkSecurityGroupToAssociate != null) { networkSecurityGroup = existingNetworkSecurityGroupToAssociate; } if (networkSecurityGroup != null) { this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values()); this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values())); } }
I think from string will not change at all. Instead, the enum name is still not ready after discussed.
public NetworkSecurityRuleImpl withAnyProtocol() { return this.withProtocol(SecurityRuleProtocol.fromString("*")); }
return this.withProtocol(SecurityRuleProtocol.fromString("*"));
public NetworkSecurityRuleImpl withAnyProtocol() { return this.withProtocol(SecurityRuleProtocol.STAR); }
class NetworkSecurityRuleImpl extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup> implements NetworkSecurityRule, NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>, NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>, NetworkSecurityRule.Update { private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>(); private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>(); NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) { super(inner, parent); if (inner.sourceApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) { sourceAsgs.put(asg.getId(), asg); } } if (inner.destinationApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) { destinationAsgs.put(asg.getId(), asg); } } } @Override public String name() { return this.inner().name(); } @Override public SecurityRuleDirection direction() { return this.inner().direction(); } @Override public SecurityRuleProtocol protocol() { return this.inner().protocol(); } @Override public SecurityRuleAccess access() { return this.inner().access(); } @Override public String sourceAddressPrefix() { return this.inner().sourceAddressPrefix(); } @Override public List<String> sourceAddressPrefixes() { return Collections.unmodifiableList(this.inner().sourceAddressPrefixes()); } @Override public String sourcePortRange() { return this.inner().sourcePortRange(); } @Override public List<String> sourcePortRanges() { return Collections.unmodifiableList(inner().sourcePortRanges()); } @Override public String destinationAddressPrefix() { return this.inner().destinationAddressPrefix(); } @Override public List<String> destinationAddressPrefixes() { return Collections.unmodifiableList(this.inner().destinationAddressPrefixes()); } @Override public String destinationPortRange() { return this.inner().destinationPortRange(); } @Override public List<String> destinationPortRanges() { return Collections.unmodifiableList(inner().destinationPortRanges()); } @Override public int priority() { return Utils.toPrimitiveInt(this.inner().priority()); } @Override public Set<String> sourceApplicationSecurityGroupIds() { return Collections.unmodifiableSet(sourceAsgs.keySet()); } @Override public Set<String> destinationApplicationSecurityGroupIds() { return Collections.unmodifiableSet(destinationAsgs.keySet()); } @Override public NetworkSecurityRuleImpl allowInbound() { return this .withDirection(SecurityRuleDirection.INBOUND) .withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl allowOutbound() { return this .withDirection(SecurityRuleDirection.OUTBOUND) .withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl denyInbound() { return this .withDirection(SecurityRuleDirection.INBOUND) .withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl denyOutbound() { return this .withDirection(SecurityRuleDirection.OUTBOUND) .withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) { this.inner().withProtocol(protocol); return this; } @Override @Override public NetworkSecurityRuleImpl fromAddress(String cidr) { this.inner().withSourceAddressPrefix(cidr); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyAddress() { this.inner().withSourceAddressPrefix("*"); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAddresses(String... addresses) { this.inner().withSourceAddressPrefixes(Arrays.asList(addresses)); this.inner().withSourceAddressPrefix(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromPort(int port) { this.inner().withSourcePortRange(String.valueOf(port)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyPort() { this.inner().withSourcePortRange("*"); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRange(int from, int to) { this.inner().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRanges(String... ranges) { this.inner().withSourcePortRanges(Arrays.asList(ranges)); this.inner().withSourcePortRange(null); return this; } @Override public NetworkSecurityRuleImpl toAddress(String cidr) { this.inner().withDestinationAddressPrefix(cidr); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAddresses(String... addresses) { this.inner().withDestinationAddressPrefixes(Arrays.asList(addresses)); this.inner().withDestinationAddressPrefix(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAnyAddress() { this.inner().withDestinationAddressPrefix("*"); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toPort(int port) { this.inner().withDestinationPortRange(String.valueOf(port)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toAnyPort() { this.inner().withDestinationPortRange("*"); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRange(int from, int to) { this.inner().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRanges(String... ranges) { this.inner().withDestinationPortRanges(Arrays.asList(ranges)); this.inner().withDestinationPortRange(null); return this; } @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { throw new IllegalArgumentException("The priority number of a network security rule must be between 100 and 4096."); } this.inner().withPriority(priority); return this; } @Override public NetworkSecurityRuleImpl withDescription(String description) { this.inner().withDescription(description); return this; } @Override public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) { sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withSourceAddressPrefix(null); inner().withSourceAddressPrefixes(null); return this; } @Override public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) { destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withDestinationAddressPrefix(null); inner().withDestinationAddressPrefixes(null); return this; } private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) { this.inner().withDirection(direction); return this; } private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) { this.inner().withAccess(permission); return this; } @Override public NetworkSecurityGroupImpl attach() { inner().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values())); inner().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values())); return this.parent().withRule(this); } @Override public String description() { return this.inner().description(); } }
class NetworkSecurityRuleImpl extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup> implements NetworkSecurityRule, NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>, NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>, NetworkSecurityRule.Update { private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>(); private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>(); private final ClientLogger logger = new ClientLogger(getClass()); NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) { super(inner, parent); if (inner.sourceApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) { sourceAsgs.put(asg.getId(), asg); } } if (inner.destinationApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) { destinationAsgs.put(asg.getId(), asg); } } } @Override public String name() { return this.inner().name(); } @Override public SecurityRuleDirection direction() { return this.inner().direction(); } @Override public SecurityRuleProtocol protocol() { return this.inner().protocol(); } @Override public SecurityRuleAccess access() { return this.inner().access(); } @Override public String sourceAddressPrefix() { return this.inner().sourceAddressPrefix(); } @Override public List<String> sourceAddressPrefixes() { return Collections.unmodifiableList(this.inner().sourceAddressPrefixes()); } @Override public String sourcePortRange() { return this.inner().sourcePortRange(); } @Override public List<String> sourcePortRanges() { return Collections.unmodifiableList(inner().sourcePortRanges()); } @Override public String destinationAddressPrefix() { return this.inner().destinationAddressPrefix(); } @Override public List<String> destinationAddressPrefixes() { return Collections.unmodifiableList(this.inner().destinationAddressPrefixes()); } @Override public String destinationPortRange() { return this.inner().destinationPortRange(); } @Override public List<String> destinationPortRanges() { return Collections.unmodifiableList(inner().destinationPortRanges()); } @Override public int priority() { return Utils.toPrimitiveInt(this.inner().priority()); } @Override public Set<String> sourceApplicationSecurityGroupIds() { return Collections.unmodifiableSet(sourceAsgs.keySet()); } @Override public Set<String> destinationApplicationSecurityGroupIds() { return Collections.unmodifiableSet(destinationAsgs.keySet()); } @Override public NetworkSecurityRuleImpl allowInbound() { return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl allowOutbound() { return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl denyInbound() { return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl denyOutbound() { return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) { this.inner().withProtocol(protocol); return this; } @Override @Override public NetworkSecurityRuleImpl fromAddress(String cidr) { this.inner().withSourceAddressPrefix(cidr); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyAddress() { this.inner().withSourceAddressPrefix("*"); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAddresses(String... addresses) { this.inner().withSourceAddressPrefixes(Arrays.asList(addresses)); this.inner().withSourceAddressPrefix(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromPort(int port) { this.inner().withSourcePortRange(String.valueOf(port)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyPort() { this.inner().withSourcePortRange("*"); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRange(int from, int to) { this.inner().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRanges(String... ranges) { this.inner().withSourcePortRanges(Arrays.asList(ranges)); this.inner().withSourcePortRange(null); return this; } @Override public NetworkSecurityRuleImpl toAddress(String cidr) { this.inner().withDestinationAddressPrefix(cidr); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAddresses(String... addresses) { this.inner().withDestinationAddressPrefixes(Arrays.asList(addresses)); this.inner().withDestinationAddressPrefix(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAnyAddress() { this.inner().withDestinationAddressPrefix("*"); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toPort(int port) { this.inner().withDestinationPortRange(String.valueOf(port)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toAnyPort() { this.inner().withDestinationPortRange("*"); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRange(int from, int to) { this.inner().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRanges(String... ranges) { this.inner().withDestinationPortRanges(Arrays.asList(ranges)); this.inner().withDestinationPortRange(null); return this; } @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { throw logger.logExceptionAsError(new IllegalArgumentException( "The priority number of a network security rule must be between 100 and 4096.")); } this.inner().withPriority(priority); return this; } @Override public NetworkSecurityRuleImpl withDescription(String description) { this.inner().withDescription(description); return this; } @Override public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) { sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withSourceAddressPrefix(null); inner().withSourceAddressPrefixes(null); return this; } @Override public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) { destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withDestinationAddressPrefix(null); inner().withDestinationAddressPrefixes(null); return this; } private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) { this.inner().withDirection(direction); return this; } private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) { this.inner().withAccess(permission); return this; } @Override public NetworkSecurityGroupImpl attach() { inner().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values())); inner().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values())); return this.parent().withRule(this); } @Override public String description() { return this.inner().description(); } }
Should be solved.
protected Mono<NetworkSecurityGroupInner> getInnerAsync() { return this .manager() .inner() .networkSecurityGroups() .getByResourceGroupAsync(this.resourceGroupName(), this.name(), null); }
protected Mono<NetworkSecurityGroupInner> getInnerAsync() { return this .manager() .inner() .networkSecurityGroups() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); }
class NetworkSecurityGroupImpl extends GroupableParentResourceWithTagsImpl< NetworkSecurityGroup, NetworkSecurityGroupInner, NetworkSecurityGroupImpl, NetworkManager> implements NetworkSecurityGroup, NetworkSecurityGroup.Definition, NetworkSecurityGroup.Update { private Map<String, NetworkSecurityRule> rules; private Map<String, NetworkSecurityRule> defaultRules; NetworkSecurityGroupImpl( final String name, final NetworkSecurityGroupInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected void initializeChildrenFromInner() { this.rules = new TreeMap<>(); List<SecurityRuleInner> inners = this.inner().securityRules(); if (inners != null) { for (SecurityRuleInner inner : inners) { this.rules.put(inner.name(), new NetworkSecurityRuleImpl(inner, this)); } } this.defaultRules = new TreeMap<>(); inners = this.inner().defaultSecurityRules(); if (inners != null) { for (SecurityRuleInner inner : inners) { this.defaultRules.put(inner.name(), new NetworkSecurityRuleImpl(inner, this)); } } } @Override public NetworkSecurityRuleImpl updateRule(String name) { return (NetworkSecurityRuleImpl) this.rules.get(name); } @Override public NetworkSecurityRuleImpl defineRule(String name) { SecurityRuleInner inner = new SecurityRuleInner(); inner.withName(name); inner.withPriority(100); return new NetworkSecurityRuleImpl(inner, this); } @Override public Mono<NetworkSecurityGroup> refreshAsync() { return super .refreshAsync() .map( networkSecurityGroup -> { NetworkSecurityGroupImpl impl = (NetworkSecurityGroupImpl) networkSecurityGroup; impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkSecurityGroupInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkSecurityGroups() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public List<Subnet> listAssociatedSubnets() { return this.myManager.listAssociatedSubnets(this.inner().subnets()); } @Override public Update withoutRule(String name) { this.rules.remove(name); return this; } NetworkSecurityGroupImpl withRule(NetworkSecurityRuleImpl rule) { this.rules.put(rule.name(), rule); return this; } @Override public Map<String, NetworkSecurityRule> securityRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, NetworkSecurityRule> defaultSecurityRules() { return Collections.unmodifiableMap(this.defaultRules); } @Override public Set<String> networkInterfaceIds() { Set<String> ids = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (this.inner().networkInterfaces() != null) { for (NetworkInterfaceInner inner : this.inner().networkInterfaces()) { ids.add(inner.getId()); } } return Collections.unmodifiableSet(ids); } @Override protected void beforeCreating() { this.inner().withSecurityRules(innersFromWrappers(this.rules.values())); } @Override protected Mono<NetworkSecurityGroupInner> createInner() { return this .manager() .inner() .networkSecurityGroups() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } }
class NetworkSecurityGroupImpl extends GroupableParentResourceWithTagsImpl< NetworkSecurityGroup, NetworkSecurityGroupInner, NetworkSecurityGroupImpl, NetworkManager> implements NetworkSecurityGroup, NetworkSecurityGroup.Definition, NetworkSecurityGroup.Update { private Map<String, NetworkSecurityRule> rules; private Map<String, NetworkSecurityRule> defaultRules; NetworkSecurityGroupImpl( final String name, final NetworkSecurityGroupInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected void initializeChildrenFromInner() { this.rules = new TreeMap<>(); List<SecurityRuleInner> inners = this.inner().securityRules(); if (inners != null) { for (SecurityRuleInner inner : inners) { this.rules.put(inner.name(), new NetworkSecurityRuleImpl(inner, this)); } } this.defaultRules = new TreeMap<>(); inners = this.inner().defaultSecurityRules(); if (inners != null) { for (SecurityRuleInner inner : inners) { this.defaultRules.put(inner.name(), new NetworkSecurityRuleImpl(inner, this)); } } } @Override public NetworkSecurityRuleImpl updateRule(String name) { return (NetworkSecurityRuleImpl) this.rules.get(name); } @Override public NetworkSecurityRuleImpl defineRule(String name) { SecurityRuleInner inner = new SecurityRuleInner(); inner.withName(name); inner.withPriority(100); return new NetworkSecurityRuleImpl(inner, this); } @Override public Mono<NetworkSecurityGroup> refreshAsync() { return super .refreshAsync() .map( networkSecurityGroup -> { NetworkSecurityGroupImpl impl = (NetworkSecurityGroupImpl) networkSecurityGroup; impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkSecurityGroupInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkSecurityGroups() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public List<Subnet> listAssociatedSubnets() { return this.myManager.listAssociatedSubnets(this.inner().subnets()); } @Override public Update withoutRule(String name) { this.rules.remove(name); return this; } NetworkSecurityGroupImpl withRule(NetworkSecurityRuleImpl rule) { this.rules.put(rule.name(), rule); return this; } @Override public Map<String, NetworkSecurityRule> securityRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, NetworkSecurityRule> defaultSecurityRules() { return Collections.unmodifiableMap(this.defaultRules); } @Override public Set<String> networkInterfaceIds() { Set<String> ids = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (this.inner().networkInterfaces() != null) { for (NetworkInterfaceInner inner : this.inner().networkInterfaces()) { ids.add(inner.getId()); } } return Collections.unmodifiableSet(ids); } @Override protected void beforeCreating() { this.inner().withSecurityRules(innersFromWrappers(this.rules.values())); } @Override protected Mono<NetworkSecurityGroupInner> createInner() { return this .manager() .inner() .networkSecurityGroups() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } }
Should all expand TODO remain `null`?
protected Mono<NetworkInterfaceInner> getInnerAsync() { return this .manager() .inner() .networkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name(), null); }
protected Mono<NetworkInterfaceInner> getInnerAsync() { return this .manager() .inner() .networkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); }
class NetworkInterfaceImpl extends GroupableParentResourceWithTagsImpl< NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { /** the name of the network interface. */ private final String nicName; /** used to generate unique name for any dependency resources. */ protected final ResourceNamer namer; /** references to all ip configuration. */ private Map<String, NicIPConfiguration> nicIPConfigurations; /** unique key of a creatable network security group to be associated with the network interface. */ private String creatableNetworkSecurityGroupKey; /** reference to an network security group to be associated with the network interface. */ private NetworkSecurityGroup existingNetworkSecurityGroupToAssociate; /** cached related resources. */ private NetworkSecurityGroup networkSecurityGroup; NetworkInterfaceImpl(String name, NetworkInterfaceInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.nicName = name; this.namer = this.manager().getSdkContext().getResourceNamerFactory().createResourceNamer(this.nicName); initializeChildrenFromInner(); } @Override public Mono<NetworkInterface> refreshAsync() { return super .refreshAsync() .map( networkInterface -> { NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; impl.clearCachedRelatedResources(); impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkInterfaceInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkInterfaces() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public NetworkInterfaceImpl withAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(true); return this; } @Override public NetworkInterfaceImpl withoutAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(false); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(Creatable<Network> creatable) { this.primaryIPConfiguration().withNewNetwork(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String name, String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(name, addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryNetwork(Network network) { this.primaryIPConfiguration().withExistingNetwork(network); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) { this.primaryIPConfiguration().withNewPublicIPAddress(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress() { this.primaryIPConfiguration().withNewPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { this.primaryIPConfiguration().withNewPublicIPAddress(leafDnsLabel); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBalancer, String backendName) { this.primaryIPConfiguration().withExistingLoadBalancerBackend(loadBalancer, backendName); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( LoadBalancer loadBalancer, String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @Override public Update withoutLoadBalancerBackends() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerBackends(); } return this; } @Override public Update withoutLoadBalancerInboundNatRules() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerInboundNatRules(); } return this; } @Override public NetworkInterfaceImpl withoutPrimaryPublicIPAddress() { this.primaryIPConfiguration().withoutPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) { this.primaryIPConfiguration().withExistingPublicIPAddress(publicIPAddress); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressDynamic() { this.primaryIPConfiguration().withPrivateIPAddressDynamic(); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { this.primaryIPConfiguration().withPrivateIPAddressStatic(staticPrivateIPAddress); return this; } @Override public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) { if (this.creatableNetworkSecurityGroupKey == null) { this.creatableNetworkSecurityGroupKey = this.addDependency(creatable); } return this; } @Override public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) { this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup; return this; } @Override public NetworkInterfaceImpl withoutNetworkSecurityGroup() { this.inner().withNetworkSecurityGroup(null); return this; } @Override public NicIPConfigurationImpl defineSecondaryIPConfiguration(String name) { return prepareNewNicIPConfiguration(name); } @Override public NicIPConfigurationImpl updateIPConfiguration(String name) { return (NicIPConfigurationImpl) this.nicIPConfigurations.get(name); } @Override public NetworkInterfaceImpl withIPForwarding() { this.inner().withEnableIPForwarding(true); return this; } @Override public NetworkInterfaceImpl withoutIPConfiguration(String name) { this.nicIPConfigurations.remove(name); return this; } @Override public NetworkInterfaceImpl withoutIPForwarding() { this.inner().withEnableIPForwarding(false); return this; } @Override public NetworkInterfaceImpl withDnsServer(String ipAddress) { this.dnsServerIPs().add(ipAddress); return this; } @Override public NetworkInterfaceImpl withoutDnsServer(String ipAddress) { this.dnsServerIPs().remove(ipAddress); return this; } @Override public NetworkInterfaceImpl withAzureDnsServer() { this.dnsServerIPs().clear(); return this; } @Override public NetworkInterfaceImpl withSubnet(String name) { this.primaryIPConfiguration().withSubnet(name); return this; } @Override public NetworkInterfaceImpl withInternalDnsNameLabel(String dnsNameLabel) { this.inner().dnsSettings().withInternalDnsNameLabel(dnsNameLabel); return this; } @Override public boolean isAcceleratedNetworkingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableAcceleratedNetworking()); } @Override public String virtualMachineId() { if (this.inner().virtualMachine() != null) { return this.inner().virtualMachine().getId(); } else { return null; } } @Override public boolean isIPForwardingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableIPForwarding()); } @Override public String macAddress() { return this.inner().macAddress(); } @Override public String internalDnsNameLabel() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDnsNameLabel() : null; } @Override public String internalDomainNameSuffix() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDomainNameSuffix() : null; } @Override public List<String> appliedDnsServers() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return Collections.unmodifiableList(dnsServers); } else if (this.inner().dnsSettings().appliedDnsServers() == null) { return Collections.unmodifiableList(dnsServers); } else { return Collections.unmodifiableList(this.inner().dnsSettings().appliedDnsServers()); } } @Override public String internalFqdn() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalFqdn() : null; } @Override public List<String> dnsServers() { return this.dnsServerIPs(); } @Override public String primaryPrivateIP() { return this.primaryIPConfiguration().privateIPAddress(); } @Override public IPAllocationMethod primaryPrivateIPAllocationMethod() { return this.primaryIPConfiguration().privateIPAllocationMethod(); } @Override public Map<String, NicIPConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.nicIPConfigurations); } @Override public String networkSecurityGroupId() { return (this.inner().networkSecurityGroup() != null) ? this.inner().networkSecurityGroup().getId() : null; } @Override public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); this.networkSecurityGroup = super .myManager .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } /** @return the primary IP configuration of the network interface */ @Override public NicIPConfigurationImpl primaryIPConfiguration() { NicIPConfigurationImpl primaryIPConfig = null; if (this.nicIPConfigurations.size() == 0) { primaryIPConfig = prepareNewNicIPConfiguration("primary"); primaryIPConfig.inner().withPrimary(true); withIPConfiguration(primaryIPConfig); } else if (this.nicIPConfigurations.size() == 1) { primaryIPConfig = (NicIPConfigurationImpl) this.nicIPConfigurations.values().iterator().next(); } else { for (NicIPConfiguration ipConfig : this.nicIPConfigurations.values()) { if (ipConfig.isPrimary()) { primaryIPConfig = (NicIPConfigurationImpl) ipConfig; break; } } } return primaryIPConfig; } /** @return the list of DNS server IPs from the DNS settings */ private List<String> dnsServerIPs() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return dnsServers; } else if (this.inner().dnsSettings().dnsServers() == null) { return dnsServers; } else { return this.inner().dnsSettings().dnsServers(); } } @Override protected void initializeChildrenFromInner() { this.nicIPConfigurations = new TreeMap<>(); List<NetworkInterfaceIPConfigurationInner> inners = this.inner().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIPConfigurationInner inner : inners) { NicIPConfigurationImpl nicIPConfiguration = new NicIPConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } } /** * Gets a new IP configuration child resource {@link NicIPConfiguration} wrapping {@link * NetworkInterfaceIPConfigurationInner}. * * @param name the name for the new ip configuration * @return {@link NicIPConfiguration} */ private NicIPConfigurationImpl prepareNewNicIPConfiguration(String name) { NicIPConfigurationImpl nicIPConfiguration = NicIPConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } private void clearCachedRelatedResources() { this.networkSecurityGroup = null; } NetworkInterfaceImpl withIPConfiguration(NicIPConfigurationImpl nicIPConfiguration) { this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); return this; } void addToCreatableDependencies(Creatable<? extends Resource> creatableResource) { this.addDependency(creatableResource); } Resource createdDependencyResource(String key) { return this.<Resource>taskResult(key); } Creatable<ResourceGroup> newGroup() { return this.creatableGroup; } @Override protected Mono<NetworkInterfaceInner> createInner() { return this .manager() .inner() .networkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override protected void afterCreating() { clearCachedRelatedResources(); } @Override protected void beforeCreating() { NetworkSecurityGroup networkSecurityGroup = null; if (creatableNetworkSecurityGroupKey != null) { networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey); } else if (existingNetworkSecurityGroupToAssociate != null) { networkSecurityGroup = existingNetworkSecurityGroupToAssociate; } if (networkSecurityGroup != null) { this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values()); this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values())); } }
class NetworkInterfaceImpl extends GroupableParentResourceWithTagsImpl< NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { /** the name of the network interface. */ private final String nicName; /** used to generate unique name for any dependency resources. */ protected final ResourceNamer namer; /** references to all ip configuration. */ private Map<String, NicIPConfiguration> nicIPConfigurations; /** unique key of a creatable network security group to be associated with the network interface. */ private String creatableNetworkSecurityGroupKey; /** reference to an network security group to be associated with the network interface. */ private NetworkSecurityGroup existingNetworkSecurityGroupToAssociate; /** cached related resources. */ private NetworkSecurityGroup networkSecurityGroup; NetworkInterfaceImpl(String name, NetworkInterfaceInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.nicName = name; this.namer = this.manager().getSdkContext().getResourceNamerFactory().createResourceNamer(this.nicName); initializeChildrenFromInner(); } @Override public Mono<NetworkInterface> refreshAsync() { return super .refreshAsync() .map( networkInterface -> { NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; impl.clearCachedRelatedResources(); impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkInterfaceInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkInterfaces() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public NetworkInterfaceImpl withAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(true); return this; } @Override public NetworkInterfaceImpl withoutAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(false); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(Creatable<Network> creatable) { this.primaryIPConfiguration().withNewNetwork(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String name, String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(name, addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryNetwork(Network network) { this.primaryIPConfiguration().withExistingNetwork(network); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) { this.primaryIPConfiguration().withNewPublicIPAddress(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress() { this.primaryIPConfiguration().withNewPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { this.primaryIPConfiguration().withNewPublicIPAddress(leafDnsLabel); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBalancer, String backendName) { this.primaryIPConfiguration().withExistingLoadBalancerBackend(loadBalancer, backendName); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( LoadBalancer loadBalancer, String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @Override public Update withoutLoadBalancerBackends() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerBackends(); } return this; } @Override public Update withoutLoadBalancerInboundNatRules() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerInboundNatRules(); } return this; } @Override public NetworkInterfaceImpl withoutPrimaryPublicIPAddress() { this.primaryIPConfiguration().withoutPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) { this.primaryIPConfiguration().withExistingPublicIPAddress(publicIPAddress); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressDynamic() { this.primaryIPConfiguration().withPrivateIPAddressDynamic(); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { this.primaryIPConfiguration().withPrivateIPAddressStatic(staticPrivateIPAddress); return this; } @Override public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) { if (this.creatableNetworkSecurityGroupKey == null) { this.creatableNetworkSecurityGroupKey = this.addDependency(creatable); } return this; } @Override public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) { this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup; return this; } @Override public NetworkInterfaceImpl withoutNetworkSecurityGroup() { this.inner().withNetworkSecurityGroup(null); return this; } @Override public NicIPConfigurationImpl defineSecondaryIPConfiguration(String name) { return prepareNewNicIPConfiguration(name); } @Override public NicIPConfigurationImpl updateIPConfiguration(String name) { return (NicIPConfigurationImpl) this.nicIPConfigurations.get(name); } @Override public NetworkInterfaceImpl withIPForwarding() { this.inner().withEnableIPForwarding(true); return this; } @Override public NetworkInterfaceImpl withoutIPConfiguration(String name) { this.nicIPConfigurations.remove(name); return this; } @Override public NetworkInterfaceImpl withoutIPForwarding() { this.inner().withEnableIPForwarding(false); return this; } @Override public NetworkInterfaceImpl withDnsServer(String ipAddress) { this.dnsServerIPs().add(ipAddress); return this; } @Override public NetworkInterfaceImpl withoutDnsServer(String ipAddress) { this.dnsServerIPs().remove(ipAddress); return this; } @Override public NetworkInterfaceImpl withAzureDnsServer() { this.dnsServerIPs().clear(); return this; } @Override public NetworkInterfaceImpl withSubnet(String name) { this.primaryIPConfiguration().withSubnet(name); return this; } @Override public NetworkInterfaceImpl withInternalDnsNameLabel(String dnsNameLabel) { this.inner().dnsSettings().withInternalDnsNameLabel(dnsNameLabel); return this; } @Override public boolean isAcceleratedNetworkingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableAcceleratedNetworking()); } @Override public String virtualMachineId() { if (this.inner().virtualMachine() != null) { return this.inner().virtualMachine().getId(); } else { return null; } } @Override public boolean isIPForwardingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableIPForwarding()); } @Override public String macAddress() { return this.inner().macAddress(); } @Override public String internalDnsNameLabel() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDnsNameLabel() : null; } @Override public String internalDomainNameSuffix() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDomainNameSuffix() : null; } @Override public List<String> appliedDnsServers() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return Collections.unmodifiableList(dnsServers); } else if (this.inner().dnsSettings().appliedDnsServers() == null) { return Collections.unmodifiableList(dnsServers); } else { return Collections.unmodifiableList(this.inner().dnsSettings().appliedDnsServers()); } } @Override public String internalFqdn() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalFqdn() : null; } @Override public List<String> dnsServers() { return this.dnsServerIPs(); } @Override public String primaryPrivateIP() { return this.primaryIPConfiguration().privateIPAddress(); } @Override public IPAllocationMethod primaryPrivateIPAllocationMethod() { return this.primaryIPConfiguration().privateIPAllocationMethod(); } @Override public Map<String, NicIPConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.nicIPConfigurations); } @Override public String networkSecurityGroupId() { return (this.inner().networkSecurityGroup() != null) ? this.inner().networkSecurityGroup().getId() : null; } @Override public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); this.networkSecurityGroup = super .myManager .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } /** @return the primary IP configuration of the network interface */ @Override public NicIPConfigurationImpl primaryIPConfiguration() { NicIPConfigurationImpl primaryIPConfig = null; if (this.nicIPConfigurations.size() == 0) { primaryIPConfig = prepareNewNicIPConfiguration("primary"); primaryIPConfig.inner().withPrimary(true); withIPConfiguration(primaryIPConfig); } else if (this.nicIPConfigurations.size() == 1) { primaryIPConfig = (NicIPConfigurationImpl) this.nicIPConfigurations.values().iterator().next(); } else { for (NicIPConfiguration ipConfig : this.nicIPConfigurations.values()) { if (ipConfig.isPrimary()) { primaryIPConfig = (NicIPConfigurationImpl) ipConfig; break; } } } return primaryIPConfig; } /** @return the list of DNS server IPs from the DNS settings */ private List<String> dnsServerIPs() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return dnsServers; } else if (this.inner().dnsSettings().dnsServers() == null) { return dnsServers; } else { return this.inner().dnsSettings().dnsServers(); } } @Override protected void initializeChildrenFromInner() { this.nicIPConfigurations = new TreeMap<>(); List<NetworkInterfaceIPConfigurationInner> inners = this.inner().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIPConfigurationInner inner : inners) { NicIPConfigurationImpl nicIPConfiguration = new NicIPConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } } /** * Gets a new IP configuration child resource {@link NicIPConfiguration} wrapping {@link * NetworkInterfaceIPConfigurationInner}. * * @param name the name for the new ip configuration * @return {@link NicIPConfiguration} */ private NicIPConfigurationImpl prepareNewNicIPConfiguration(String name) { NicIPConfigurationImpl nicIPConfiguration = NicIPConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } private void clearCachedRelatedResources() { this.networkSecurityGroup = null; } NetworkInterfaceImpl withIPConfiguration(NicIPConfigurationImpl nicIPConfiguration) { this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); return this; } void addToCreatableDependencies(Creatable<? extends Resource> creatableResource) { this.addDependency(creatableResource); } Resource createdDependencyResource(String key) { return this.<Resource>taskResult(key); } Creatable<ResourceGroup> newGroup() { return this.creatableGroup; } @Override protected Mono<NetworkInterfaceInner> createInner() { return this .manager() .inner() .networkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override protected void afterCreating() { clearCachedRelatedResources(); } @Override protected void beforeCreating() { NetworkSecurityGroup networkSecurityGroup = null; if (creatableNetworkSecurityGroupKey != null) { networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey); } else if (existingNetworkSecurityGroupToAssociate != null) { networkSecurityGroup = existingNetworkSecurityGroupToAssociate; } if (networkSecurityGroup != null) { this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values()); this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values())); } }
If the call is using `null` it could now be deleted. This is yaohai adding these `null`s when method call with defaults not ready.
protected Mono<NetworkInterfaceInner> getInnerAsync() { return this .manager() .inner() .networkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name(), null); }
protected Mono<NetworkInterfaceInner> getInnerAsync() { return this .manager() .inner() .networkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); }
class NetworkInterfaceImpl extends GroupableParentResourceWithTagsImpl< NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { /** the name of the network interface. */ private final String nicName; /** used to generate unique name for any dependency resources. */ protected final ResourceNamer namer; /** references to all ip configuration. */ private Map<String, NicIPConfiguration> nicIPConfigurations; /** unique key of a creatable network security group to be associated with the network interface. */ private String creatableNetworkSecurityGroupKey; /** reference to an network security group to be associated with the network interface. */ private NetworkSecurityGroup existingNetworkSecurityGroupToAssociate; /** cached related resources. */ private NetworkSecurityGroup networkSecurityGroup; NetworkInterfaceImpl(String name, NetworkInterfaceInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.nicName = name; this.namer = this.manager().getSdkContext().getResourceNamerFactory().createResourceNamer(this.nicName); initializeChildrenFromInner(); } @Override public Mono<NetworkInterface> refreshAsync() { return super .refreshAsync() .map( networkInterface -> { NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; impl.clearCachedRelatedResources(); impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkInterfaceInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkInterfaces() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public NetworkInterfaceImpl withAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(true); return this; } @Override public NetworkInterfaceImpl withoutAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(false); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(Creatable<Network> creatable) { this.primaryIPConfiguration().withNewNetwork(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String name, String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(name, addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryNetwork(Network network) { this.primaryIPConfiguration().withExistingNetwork(network); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) { this.primaryIPConfiguration().withNewPublicIPAddress(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress() { this.primaryIPConfiguration().withNewPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { this.primaryIPConfiguration().withNewPublicIPAddress(leafDnsLabel); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBalancer, String backendName) { this.primaryIPConfiguration().withExistingLoadBalancerBackend(loadBalancer, backendName); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( LoadBalancer loadBalancer, String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @Override public Update withoutLoadBalancerBackends() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerBackends(); } return this; } @Override public Update withoutLoadBalancerInboundNatRules() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerInboundNatRules(); } return this; } @Override public NetworkInterfaceImpl withoutPrimaryPublicIPAddress() { this.primaryIPConfiguration().withoutPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) { this.primaryIPConfiguration().withExistingPublicIPAddress(publicIPAddress); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressDynamic() { this.primaryIPConfiguration().withPrivateIPAddressDynamic(); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { this.primaryIPConfiguration().withPrivateIPAddressStatic(staticPrivateIPAddress); return this; } @Override public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) { if (this.creatableNetworkSecurityGroupKey == null) { this.creatableNetworkSecurityGroupKey = this.addDependency(creatable); } return this; } @Override public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) { this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup; return this; } @Override public NetworkInterfaceImpl withoutNetworkSecurityGroup() { this.inner().withNetworkSecurityGroup(null); return this; } @Override public NicIPConfigurationImpl defineSecondaryIPConfiguration(String name) { return prepareNewNicIPConfiguration(name); } @Override public NicIPConfigurationImpl updateIPConfiguration(String name) { return (NicIPConfigurationImpl) this.nicIPConfigurations.get(name); } @Override public NetworkInterfaceImpl withIPForwarding() { this.inner().withEnableIPForwarding(true); return this; } @Override public NetworkInterfaceImpl withoutIPConfiguration(String name) { this.nicIPConfigurations.remove(name); return this; } @Override public NetworkInterfaceImpl withoutIPForwarding() { this.inner().withEnableIPForwarding(false); return this; } @Override public NetworkInterfaceImpl withDnsServer(String ipAddress) { this.dnsServerIPs().add(ipAddress); return this; } @Override public NetworkInterfaceImpl withoutDnsServer(String ipAddress) { this.dnsServerIPs().remove(ipAddress); return this; } @Override public NetworkInterfaceImpl withAzureDnsServer() { this.dnsServerIPs().clear(); return this; } @Override public NetworkInterfaceImpl withSubnet(String name) { this.primaryIPConfiguration().withSubnet(name); return this; } @Override public NetworkInterfaceImpl withInternalDnsNameLabel(String dnsNameLabel) { this.inner().dnsSettings().withInternalDnsNameLabel(dnsNameLabel); return this; } @Override public boolean isAcceleratedNetworkingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableAcceleratedNetworking()); } @Override public String virtualMachineId() { if (this.inner().virtualMachine() != null) { return this.inner().virtualMachine().getId(); } else { return null; } } @Override public boolean isIPForwardingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableIPForwarding()); } @Override public String macAddress() { return this.inner().macAddress(); } @Override public String internalDnsNameLabel() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDnsNameLabel() : null; } @Override public String internalDomainNameSuffix() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDomainNameSuffix() : null; } @Override public List<String> appliedDnsServers() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return Collections.unmodifiableList(dnsServers); } else if (this.inner().dnsSettings().appliedDnsServers() == null) { return Collections.unmodifiableList(dnsServers); } else { return Collections.unmodifiableList(this.inner().dnsSettings().appliedDnsServers()); } } @Override public String internalFqdn() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalFqdn() : null; } @Override public List<String> dnsServers() { return this.dnsServerIPs(); } @Override public String primaryPrivateIP() { return this.primaryIPConfiguration().privateIPAddress(); } @Override public IPAllocationMethod primaryPrivateIPAllocationMethod() { return this.primaryIPConfiguration().privateIPAllocationMethod(); } @Override public Map<String, NicIPConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.nicIPConfigurations); } @Override public String networkSecurityGroupId() { return (this.inner().networkSecurityGroup() != null) ? this.inner().networkSecurityGroup().getId() : null; } @Override public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); this.networkSecurityGroup = super .myManager .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } /** @return the primary IP configuration of the network interface */ @Override public NicIPConfigurationImpl primaryIPConfiguration() { NicIPConfigurationImpl primaryIPConfig = null; if (this.nicIPConfigurations.size() == 0) { primaryIPConfig = prepareNewNicIPConfiguration("primary"); primaryIPConfig.inner().withPrimary(true); withIPConfiguration(primaryIPConfig); } else if (this.nicIPConfigurations.size() == 1) { primaryIPConfig = (NicIPConfigurationImpl) this.nicIPConfigurations.values().iterator().next(); } else { for (NicIPConfiguration ipConfig : this.nicIPConfigurations.values()) { if (ipConfig.isPrimary()) { primaryIPConfig = (NicIPConfigurationImpl) ipConfig; break; } } } return primaryIPConfig; } /** @return the list of DNS server IPs from the DNS settings */ private List<String> dnsServerIPs() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return dnsServers; } else if (this.inner().dnsSettings().dnsServers() == null) { return dnsServers; } else { return this.inner().dnsSettings().dnsServers(); } } @Override protected void initializeChildrenFromInner() { this.nicIPConfigurations = new TreeMap<>(); List<NetworkInterfaceIPConfigurationInner> inners = this.inner().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIPConfigurationInner inner : inners) { NicIPConfigurationImpl nicIPConfiguration = new NicIPConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } } /** * Gets a new IP configuration child resource {@link NicIPConfiguration} wrapping {@link * NetworkInterfaceIPConfigurationInner}. * * @param name the name for the new ip configuration * @return {@link NicIPConfiguration} */ private NicIPConfigurationImpl prepareNewNicIPConfiguration(String name) { NicIPConfigurationImpl nicIPConfiguration = NicIPConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } private void clearCachedRelatedResources() { this.networkSecurityGroup = null; } NetworkInterfaceImpl withIPConfiguration(NicIPConfigurationImpl nicIPConfiguration) { this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); return this; } void addToCreatableDependencies(Creatable<? extends Resource> creatableResource) { this.addDependency(creatableResource); } Resource createdDependencyResource(String key) { return this.<Resource>taskResult(key); } Creatable<ResourceGroup> newGroup() { return this.creatableGroup; } @Override protected Mono<NetworkInterfaceInner> createInner() { return this .manager() .inner() .networkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override protected void afterCreating() { clearCachedRelatedResources(); } @Override protected void beforeCreating() { NetworkSecurityGroup networkSecurityGroup = null; if (creatableNetworkSecurityGroupKey != null) { networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey); } else if (existingNetworkSecurityGroupToAssociate != null) { networkSecurityGroup = existingNetworkSecurityGroupToAssociate; } if (networkSecurityGroup != null) { this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values()); this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values())); } }
class NetworkInterfaceImpl extends GroupableParentResourceWithTagsImpl< NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { /** the name of the network interface. */ private final String nicName; /** used to generate unique name for any dependency resources. */ protected final ResourceNamer namer; /** references to all ip configuration. */ private Map<String, NicIPConfiguration> nicIPConfigurations; /** unique key of a creatable network security group to be associated with the network interface. */ private String creatableNetworkSecurityGroupKey; /** reference to an network security group to be associated with the network interface. */ private NetworkSecurityGroup existingNetworkSecurityGroupToAssociate; /** cached related resources. */ private NetworkSecurityGroup networkSecurityGroup; NetworkInterfaceImpl(String name, NetworkInterfaceInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.nicName = name; this.namer = this.manager().getSdkContext().getResourceNamerFactory().createResourceNamer(this.nicName); initializeChildrenFromInner(); } @Override public Mono<NetworkInterface> refreshAsync() { return super .refreshAsync() .map( networkInterface -> { NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; impl.clearCachedRelatedResources(); impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkInterfaceInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkInterfaces() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public NetworkInterfaceImpl withAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(true); return this; } @Override public NetworkInterfaceImpl withoutAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(false); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(Creatable<Network> creatable) { this.primaryIPConfiguration().withNewNetwork(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String name, String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(name, addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryNetwork(Network network) { this.primaryIPConfiguration().withExistingNetwork(network); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) { this.primaryIPConfiguration().withNewPublicIPAddress(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress() { this.primaryIPConfiguration().withNewPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { this.primaryIPConfiguration().withNewPublicIPAddress(leafDnsLabel); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBalancer, String backendName) { this.primaryIPConfiguration().withExistingLoadBalancerBackend(loadBalancer, backendName); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( LoadBalancer loadBalancer, String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @Override public Update withoutLoadBalancerBackends() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerBackends(); } return this; } @Override public Update withoutLoadBalancerInboundNatRules() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerInboundNatRules(); } return this; } @Override public NetworkInterfaceImpl withoutPrimaryPublicIPAddress() { this.primaryIPConfiguration().withoutPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) { this.primaryIPConfiguration().withExistingPublicIPAddress(publicIPAddress); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressDynamic() { this.primaryIPConfiguration().withPrivateIPAddressDynamic(); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { this.primaryIPConfiguration().withPrivateIPAddressStatic(staticPrivateIPAddress); return this; } @Override public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) { if (this.creatableNetworkSecurityGroupKey == null) { this.creatableNetworkSecurityGroupKey = this.addDependency(creatable); } return this; } @Override public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) { this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup; return this; } @Override public NetworkInterfaceImpl withoutNetworkSecurityGroup() { this.inner().withNetworkSecurityGroup(null); return this; } @Override public NicIPConfigurationImpl defineSecondaryIPConfiguration(String name) { return prepareNewNicIPConfiguration(name); } @Override public NicIPConfigurationImpl updateIPConfiguration(String name) { return (NicIPConfigurationImpl) this.nicIPConfigurations.get(name); } @Override public NetworkInterfaceImpl withIPForwarding() { this.inner().withEnableIPForwarding(true); return this; } @Override public NetworkInterfaceImpl withoutIPConfiguration(String name) { this.nicIPConfigurations.remove(name); return this; } @Override public NetworkInterfaceImpl withoutIPForwarding() { this.inner().withEnableIPForwarding(false); return this; } @Override public NetworkInterfaceImpl withDnsServer(String ipAddress) { this.dnsServerIPs().add(ipAddress); return this; } @Override public NetworkInterfaceImpl withoutDnsServer(String ipAddress) { this.dnsServerIPs().remove(ipAddress); return this; } @Override public NetworkInterfaceImpl withAzureDnsServer() { this.dnsServerIPs().clear(); return this; } @Override public NetworkInterfaceImpl withSubnet(String name) { this.primaryIPConfiguration().withSubnet(name); return this; } @Override public NetworkInterfaceImpl withInternalDnsNameLabel(String dnsNameLabel) { this.inner().dnsSettings().withInternalDnsNameLabel(dnsNameLabel); return this; } @Override public boolean isAcceleratedNetworkingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableAcceleratedNetworking()); } @Override public String virtualMachineId() { if (this.inner().virtualMachine() != null) { return this.inner().virtualMachine().getId(); } else { return null; } } @Override public boolean isIPForwardingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableIPForwarding()); } @Override public String macAddress() { return this.inner().macAddress(); } @Override public String internalDnsNameLabel() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDnsNameLabel() : null; } @Override public String internalDomainNameSuffix() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDomainNameSuffix() : null; } @Override public List<String> appliedDnsServers() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return Collections.unmodifiableList(dnsServers); } else if (this.inner().dnsSettings().appliedDnsServers() == null) { return Collections.unmodifiableList(dnsServers); } else { return Collections.unmodifiableList(this.inner().dnsSettings().appliedDnsServers()); } } @Override public String internalFqdn() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalFqdn() : null; } @Override public List<String> dnsServers() { return this.dnsServerIPs(); } @Override public String primaryPrivateIP() { return this.primaryIPConfiguration().privateIPAddress(); } @Override public IPAllocationMethod primaryPrivateIPAllocationMethod() { return this.primaryIPConfiguration().privateIPAllocationMethod(); } @Override public Map<String, NicIPConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.nicIPConfigurations); } @Override public String networkSecurityGroupId() { return (this.inner().networkSecurityGroup() != null) ? this.inner().networkSecurityGroup().getId() : null; } @Override public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); this.networkSecurityGroup = super .myManager .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } /** @return the primary IP configuration of the network interface */ @Override public NicIPConfigurationImpl primaryIPConfiguration() { NicIPConfigurationImpl primaryIPConfig = null; if (this.nicIPConfigurations.size() == 0) { primaryIPConfig = prepareNewNicIPConfiguration("primary"); primaryIPConfig.inner().withPrimary(true); withIPConfiguration(primaryIPConfig); } else if (this.nicIPConfigurations.size() == 1) { primaryIPConfig = (NicIPConfigurationImpl) this.nicIPConfigurations.values().iterator().next(); } else { for (NicIPConfiguration ipConfig : this.nicIPConfigurations.values()) { if (ipConfig.isPrimary()) { primaryIPConfig = (NicIPConfigurationImpl) ipConfig; break; } } } return primaryIPConfig; } /** @return the list of DNS server IPs from the DNS settings */ private List<String> dnsServerIPs() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return dnsServers; } else if (this.inner().dnsSettings().dnsServers() == null) { return dnsServers; } else { return this.inner().dnsSettings().dnsServers(); } } @Override protected void initializeChildrenFromInner() { this.nicIPConfigurations = new TreeMap<>(); List<NetworkInterfaceIPConfigurationInner> inners = this.inner().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIPConfigurationInner inner : inners) { NicIPConfigurationImpl nicIPConfiguration = new NicIPConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } } /** * Gets a new IP configuration child resource {@link NicIPConfiguration} wrapping {@link * NetworkInterfaceIPConfigurationInner}. * * @param name the name for the new ip configuration * @return {@link NicIPConfiguration} */ private NicIPConfigurationImpl prepareNewNicIPConfiguration(String name) { NicIPConfigurationImpl nicIPConfiguration = NicIPConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } private void clearCachedRelatedResources() { this.networkSecurityGroup = null; } NetworkInterfaceImpl withIPConfiguration(NicIPConfigurationImpl nicIPConfiguration) { this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); return this; } void addToCreatableDependencies(Creatable<? extends Resource> creatableResource) { this.addDependency(creatableResource); } Resource createdDependencyResource(String key) { return this.<Resource>taskResult(key); } Creatable<ResourceGroup> newGroup() { return this.creatableGroup; } @Override protected Mono<NetworkInterfaceInner> createInner() { return this .manager() .inner() .networkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override protected void afterCreating() { clearCachedRelatedResources(); } @Override protected void beforeCreating() { NetworkSecurityGroup networkSecurityGroup = null; if (creatableNetworkSecurityGroupKey != null) { networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey); } else if (existingNetworkSecurityGroupToAssociate != null) { networkSecurityGroup = existingNetworkSecurityGroupToAssociate; } if (networkSecurityGroup != null) { this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values()); this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values())); } }
The point is when generator changes the enum name, no compiler will tell anyone anything about this line. Runtime there might be error, if tests has it.
public NetworkSecurityRuleImpl withAnyProtocol() { return this.withProtocol(SecurityRuleProtocol.fromString("*")); }
return this.withProtocol(SecurityRuleProtocol.fromString("*"));
public NetworkSecurityRuleImpl withAnyProtocol() { return this.withProtocol(SecurityRuleProtocol.STAR); }
class NetworkSecurityRuleImpl extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup> implements NetworkSecurityRule, NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>, NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>, NetworkSecurityRule.Update { private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>(); private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>(); NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) { super(inner, parent); if (inner.sourceApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) { sourceAsgs.put(asg.getId(), asg); } } if (inner.destinationApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) { destinationAsgs.put(asg.getId(), asg); } } } @Override public String name() { return this.inner().name(); } @Override public SecurityRuleDirection direction() { return this.inner().direction(); } @Override public SecurityRuleProtocol protocol() { return this.inner().protocol(); } @Override public SecurityRuleAccess access() { return this.inner().access(); } @Override public String sourceAddressPrefix() { return this.inner().sourceAddressPrefix(); } @Override public List<String> sourceAddressPrefixes() { return Collections.unmodifiableList(this.inner().sourceAddressPrefixes()); } @Override public String sourcePortRange() { return this.inner().sourcePortRange(); } @Override public List<String> sourcePortRanges() { return Collections.unmodifiableList(inner().sourcePortRanges()); } @Override public String destinationAddressPrefix() { return this.inner().destinationAddressPrefix(); } @Override public List<String> destinationAddressPrefixes() { return Collections.unmodifiableList(this.inner().destinationAddressPrefixes()); } @Override public String destinationPortRange() { return this.inner().destinationPortRange(); } @Override public List<String> destinationPortRanges() { return Collections.unmodifiableList(inner().destinationPortRanges()); } @Override public int priority() { return Utils.toPrimitiveInt(this.inner().priority()); } @Override public Set<String> sourceApplicationSecurityGroupIds() { return Collections.unmodifiableSet(sourceAsgs.keySet()); } @Override public Set<String> destinationApplicationSecurityGroupIds() { return Collections.unmodifiableSet(destinationAsgs.keySet()); } @Override public NetworkSecurityRuleImpl allowInbound() { return this .withDirection(SecurityRuleDirection.INBOUND) .withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl allowOutbound() { return this .withDirection(SecurityRuleDirection.OUTBOUND) .withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl denyInbound() { return this .withDirection(SecurityRuleDirection.INBOUND) .withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl denyOutbound() { return this .withDirection(SecurityRuleDirection.OUTBOUND) .withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) { this.inner().withProtocol(protocol); return this; } @Override @Override public NetworkSecurityRuleImpl fromAddress(String cidr) { this.inner().withSourceAddressPrefix(cidr); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyAddress() { this.inner().withSourceAddressPrefix("*"); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAddresses(String... addresses) { this.inner().withSourceAddressPrefixes(Arrays.asList(addresses)); this.inner().withSourceAddressPrefix(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromPort(int port) { this.inner().withSourcePortRange(String.valueOf(port)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyPort() { this.inner().withSourcePortRange("*"); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRange(int from, int to) { this.inner().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRanges(String... ranges) { this.inner().withSourcePortRanges(Arrays.asList(ranges)); this.inner().withSourcePortRange(null); return this; } @Override public NetworkSecurityRuleImpl toAddress(String cidr) { this.inner().withDestinationAddressPrefix(cidr); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAddresses(String... addresses) { this.inner().withDestinationAddressPrefixes(Arrays.asList(addresses)); this.inner().withDestinationAddressPrefix(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAnyAddress() { this.inner().withDestinationAddressPrefix("*"); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toPort(int port) { this.inner().withDestinationPortRange(String.valueOf(port)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toAnyPort() { this.inner().withDestinationPortRange("*"); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRange(int from, int to) { this.inner().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRanges(String... ranges) { this.inner().withDestinationPortRanges(Arrays.asList(ranges)); this.inner().withDestinationPortRange(null); return this; } @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { throw new IllegalArgumentException("The priority number of a network security rule must be between 100 and 4096."); } this.inner().withPriority(priority); return this; } @Override public NetworkSecurityRuleImpl withDescription(String description) { this.inner().withDescription(description); return this; } @Override public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) { sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withSourceAddressPrefix(null); inner().withSourceAddressPrefixes(null); return this; } @Override public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) { destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withDestinationAddressPrefix(null); inner().withDestinationAddressPrefixes(null); return this; } private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) { this.inner().withDirection(direction); return this; } private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) { this.inner().withAccess(permission); return this; } @Override public NetworkSecurityGroupImpl attach() { inner().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values())); inner().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values())); return this.parent().withRule(this); } @Override public String description() { return this.inner().description(); } }
class NetworkSecurityRuleImpl extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup> implements NetworkSecurityRule, NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>, NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>, NetworkSecurityRule.Update { private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>(); private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>(); private final ClientLogger logger = new ClientLogger(getClass()); NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) { super(inner, parent); if (inner.sourceApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) { sourceAsgs.put(asg.getId(), asg); } } if (inner.destinationApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) { destinationAsgs.put(asg.getId(), asg); } } } @Override public String name() { return this.inner().name(); } @Override public SecurityRuleDirection direction() { return this.inner().direction(); } @Override public SecurityRuleProtocol protocol() { return this.inner().protocol(); } @Override public SecurityRuleAccess access() { return this.inner().access(); } @Override public String sourceAddressPrefix() { return this.inner().sourceAddressPrefix(); } @Override public List<String> sourceAddressPrefixes() { return Collections.unmodifiableList(this.inner().sourceAddressPrefixes()); } @Override public String sourcePortRange() { return this.inner().sourcePortRange(); } @Override public List<String> sourcePortRanges() { return Collections.unmodifiableList(inner().sourcePortRanges()); } @Override public String destinationAddressPrefix() { return this.inner().destinationAddressPrefix(); } @Override public List<String> destinationAddressPrefixes() { return Collections.unmodifiableList(this.inner().destinationAddressPrefixes()); } @Override public String destinationPortRange() { return this.inner().destinationPortRange(); } @Override public List<String> destinationPortRanges() { return Collections.unmodifiableList(inner().destinationPortRanges()); } @Override public int priority() { return Utils.toPrimitiveInt(this.inner().priority()); } @Override public Set<String> sourceApplicationSecurityGroupIds() { return Collections.unmodifiableSet(sourceAsgs.keySet()); } @Override public Set<String> destinationApplicationSecurityGroupIds() { return Collections.unmodifiableSet(destinationAsgs.keySet()); } @Override public NetworkSecurityRuleImpl allowInbound() { return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl allowOutbound() { return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl denyInbound() { return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl denyOutbound() { return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) { this.inner().withProtocol(protocol); return this; } @Override @Override public NetworkSecurityRuleImpl fromAddress(String cidr) { this.inner().withSourceAddressPrefix(cidr); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyAddress() { this.inner().withSourceAddressPrefix("*"); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAddresses(String... addresses) { this.inner().withSourceAddressPrefixes(Arrays.asList(addresses)); this.inner().withSourceAddressPrefix(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromPort(int port) { this.inner().withSourcePortRange(String.valueOf(port)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyPort() { this.inner().withSourcePortRange("*"); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRange(int from, int to) { this.inner().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRanges(String... ranges) { this.inner().withSourcePortRanges(Arrays.asList(ranges)); this.inner().withSourcePortRange(null); return this; } @Override public NetworkSecurityRuleImpl toAddress(String cidr) { this.inner().withDestinationAddressPrefix(cidr); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAddresses(String... addresses) { this.inner().withDestinationAddressPrefixes(Arrays.asList(addresses)); this.inner().withDestinationAddressPrefix(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAnyAddress() { this.inner().withDestinationAddressPrefix("*"); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toPort(int port) { this.inner().withDestinationPortRange(String.valueOf(port)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toAnyPort() { this.inner().withDestinationPortRange("*"); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRange(int from, int to) { this.inner().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRanges(String... ranges) { this.inner().withDestinationPortRanges(Arrays.asList(ranges)); this.inner().withDestinationPortRange(null); return this; } @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { throw logger.logExceptionAsError(new IllegalArgumentException( "The priority number of a network security rule must be between 100 and 4096.")); } this.inner().withPriority(priority); return this; } @Override public NetworkSecurityRuleImpl withDescription(String description) { this.inner().withDescription(description); return this; } @Override public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) { sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withSourceAddressPrefix(null); inner().withSourceAddressPrefixes(null); return this; } @Override public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) { destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withDestinationAddressPrefix(null); inner().withDestinationAddressPrefixes(null); return this; } private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) { this.inner().withDirection(direction); return this; } private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) { this.inner().withAccess(permission); return this; } @Override public NetworkSecurityGroupImpl attach() { inner().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values())); inner().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values())); return this.parent().withRule(this); } @Override public String description() { return this.inner().description(); } }
Yes, I change it back. But I think the `any` should not be other char than '*'.
public NetworkSecurityRuleImpl withAnyProtocol() { return this.withProtocol(SecurityRuleProtocol.fromString("*")); }
return this.withProtocol(SecurityRuleProtocol.fromString("*"));
public NetworkSecurityRuleImpl withAnyProtocol() { return this.withProtocol(SecurityRuleProtocol.STAR); }
class NetworkSecurityRuleImpl extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup> implements NetworkSecurityRule, NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>, NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>, NetworkSecurityRule.Update { private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>(); private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>(); NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) { super(inner, parent); if (inner.sourceApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) { sourceAsgs.put(asg.getId(), asg); } } if (inner.destinationApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) { destinationAsgs.put(asg.getId(), asg); } } } @Override public String name() { return this.inner().name(); } @Override public SecurityRuleDirection direction() { return this.inner().direction(); } @Override public SecurityRuleProtocol protocol() { return this.inner().protocol(); } @Override public SecurityRuleAccess access() { return this.inner().access(); } @Override public String sourceAddressPrefix() { return this.inner().sourceAddressPrefix(); } @Override public List<String> sourceAddressPrefixes() { return Collections.unmodifiableList(this.inner().sourceAddressPrefixes()); } @Override public String sourcePortRange() { return this.inner().sourcePortRange(); } @Override public List<String> sourcePortRanges() { return Collections.unmodifiableList(inner().sourcePortRanges()); } @Override public String destinationAddressPrefix() { return this.inner().destinationAddressPrefix(); } @Override public List<String> destinationAddressPrefixes() { return Collections.unmodifiableList(this.inner().destinationAddressPrefixes()); } @Override public String destinationPortRange() { return this.inner().destinationPortRange(); } @Override public List<String> destinationPortRanges() { return Collections.unmodifiableList(inner().destinationPortRanges()); } @Override public int priority() { return Utils.toPrimitiveInt(this.inner().priority()); } @Override public Set<String> sourceApplicationSecurityGroupIds() { return Collections.unmodifiableSet(sourceAsgs.keySet()); } @Override public Set<String> destinationApplicationSecurityGroupIds() { return Collections.unmodifiableSet(destinationAsgs.keySet()); } @Override public NetworkSecurityRuleImpl allowInbound() { return this .withDirection(SecurityRuleDirection.INBOUND) .withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl allowOutbound() { return this .withDirection(SecurityRuleDirection.OUTBOUND) .withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl denyInbound() { return this .withDirection(SecurityRuleDirection.INBOUND) .withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl denyOutbound() { return this .withDirection(SecurityRuleDirection.OUTBOUND) .withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) { this.inner().withProtocol(protocol); return this; } @Override @Override public NetworkSecurityRuleImpl fromAddress(String cidr) { this.inner().withSourceAddressPrefix(cidr); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyAddress() { this.inner().withSourceAddressPrefix("*"); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAddresses(String... addresses) { this.inner().withSourceAddressPrefixes(Arrays.asList(addresses)); this.inner().withSourceAddressPrefix(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromPort(int port) { this.inner().withSourcePortRange(String.valueOf(port)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyPort() { this.inner().withSourcePortRange("*"); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRange(int from, int to) { this.inner().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRanges(String... ranges) { this.inner().withSourcePortRanges(Arrays.asList(ranges)); this.inner().withSourcePortRange(null); return this; } @Override public NetworkSecurityRuleImpl toAddress(String cidr) { this.inner().withDestinationAddressPrefix(cidr); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAddresses(String... addresses) { this.inner().withDestinationAddressPrefixes(Arrays.asList(addresses)); this.inner().withDestinationAddressPrefix(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAnyAddress() { this.inner().withDestinationAddressPrefix("*"); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toPort(int port) { this.inner().withDestinationPortRange(String.valueOf(port)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toAnyPort() { this.inner().withDestinationPortRange("*"); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRange(int from, int to) { this.inner().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRanges(String... ranges) { this.inner().withDestinationPortRanges(Arrays.asList(ranges)); this.inner().withDestinationPortRange(null); return this; } @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { throw new IllegalArgumentException("The priority number of a network security rule must be between 100 and 4096."); } this.inner().withPriority(priority); return this; } @Override public NetworkSecurityRuleImpl withDescription(String description) { this.inner().withDescription(description); return this; } @Override public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) { sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withSourceAddressPrefix(null); inner().withSourceAddressPrefixes(null); return this; } @Override public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) { destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withDestinationAddressPrefix(null); inner().withDestinationAddressPrefixes(null); return this; } private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) { this.inner().withDirection(direction); return this; } private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) { this.inner().withAccess(permission); return this; } @Override public NetworkSecurityGroupImpl attach() { inner().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values())); inner().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values())); return this.parent().withRule(this); } @Override public String description() { return this.inner().description(); } }
class NetworkSecurityRuleImpl extends ChildResourceImpl<SecurityRuleInner, NetworkSecurityGroupImpl, NetworkSecurityGroup> implements NetworkSecurityRule, NetworkSecurityRule.Definition<NetworkSecurityGroup.DefinitionStages.WithCreate>, NetworkSecurityRule.UpdateDefinition<NetworkSecurityGroup.Update>, NetworkSecurityRule.Update { private Map<String, ApplicationSecurityGroupInner> sourceAsgs = new HashMap<>(); private Map<String, ApplicationSecurityGroupInner> destinationAsgs = new HashMap<>(); private final ClientLogger logger = new ClientLogger(getClass()); NetworkSecurityRuleImpl(SecurityRuleInner inner, NetworkSecurityGroupImpl parent) { super(inner, parent); if (inner.sourceApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.sourceApplicationSecurityGroups()) { sourceAsgs.put(asg.getId(), asg); } } if (inner.destinationApplicationSecurityGroups() != null) { for (ApplicationSecurityGroupInner asg : inner.destinationApplicationSecurityGroups()) { destinationAsgs.put(asg.getId(), asg); } } } @Override public String name() { return this.inner().name(); } @Override public SecurityRuleDirection direction() { return this.inner().direction(); } @Override public SecurityRuleProtocol protocol() { return this.inner().protocol(); } @Override public SecurityRuleAccess access() { return this.inner().access(); } @Override public String sourceAddressPrefix() { return this.inner().sourceAddressPrefix(); } @Override public List<String> sourceAddressPrefixes() { return Collections.unmodifiableList(this.inner().sourceAddressPrefixes()); } @Override public String sourcePortRange() { return this.inner().sourcePortRange(); } @Override public List<String> sourcePortRanges() { return Collections.unmodifiableList(inner().sourcePortRanges()); } @Override public String destinationAddressPrefix() { return this.inner().destinationAddressPrefix(); } @Override public List<String> destinationAddressPrefixes() { return Collections.unmodifiableList(this.inner().destinationAddressPrefixes()); } @Override public String destinationPortRange() { return this.inner().destinationPortRange(); } @Override public List<String> destinationPortRanges() { return Collections.unmodifiableList(inner().destinationPortRanges()); } @Override public int priority() { return Utils.toPrimitiveInt(this.inner().priority()); } @Override public Set<String> sourceApplicationSecurityGroupIds() { return Collections.unmodifiableSet(sourceAsgs.keySet()); } @Override public Set<String> destinationApplicationSecurityGroupIds() { return Collections.unmodifiableSet(destinationAsgs.keySet()); } @Override public NetworkSecurityRuleImpl allowInbound() { return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl allowOutbound() { return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.ALLOW); } @Override public NetworkSecurityRuleImpl denyInbound() { return this.withDirection(SecurityRuleDirection.INBOUND).withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl denyOutbound() { return this.withDirection(SecurityRuleDirection.OUTBOUND).withAccess(SecurityRuleAccess.DENY); } @Override public NetworkSecurityRuleImpl withProtocol(SecurityRuleProtocol protocol) { this.inner().withProtocol(protocol); return this; } @Override @Override public NetworkSecurityRuleImpl fromAddress(String cidr) { this.inner().withSourceAddressPrefix(cidr); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyAddress() { this.inner().withSourceAddressPrefix("*"); this.inner().withSourceAddressPrefixes(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromAddresses(String... addresses) { this.inner().withSourceAddressPrefixes(Arrays.asList(addresses)); this.inner().withSourceAddressPrefix(null); this.inner().withSourceApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl fromPort(int port) { this.inner().withSourcePortRange(String.valueOf(port)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromAnyPort() { this.inner().withSourcePortRange("*"); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRange(int from, int to) { this.inner().withSourcePortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withSourcePortRanges(null); return this; } @Override public NetworkSecurityRuleImpl fromPortRanges(String... ranges) { this.inner().withSourcePortRanges(Arrays.asList(ranges)); this.inner().withSourcePortRange(null); return this; } @Override public NetworkSecurityRuleImpl toAddress(String cidr) { this.inner().withDestinationAddressPrefix(cidr); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAddresses(String... addresses) { this.inner().withDestinationAddressPrefixes(Arrays.asList(addresses)); this.inner().withDestinationAddressPrefix(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toAnyAddress() { this.inner().withDestinationAddressPrefix("*"); this.inner().withDestinationAddressPrefixes(null); this.inner().withDestinationApplicationSecurityGroups(null); return this; } @Override public NetworkSecurityRuleImpl toPort(int port) { this.inner().withDestinationPortRange(String.valueOf(port)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toAnyPort() { this.inner().withDestinationPortRange("*"); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRange(int from, int to) { this.inner().withDestinationPortRange(String.valueOf(from) + "-" + String.valueOf(to)); this.inner().withDestinationPortRanges(null); return this; } @Override public NetworkSecurityRuleImpl toPortRanges(String... ranges) { this.inner().withDestinationPortRanges(Arrays.asList(ranges)); this.inner().withDestinationPortRange(null); return this; } @Override public NetworkSecurityRuleImpl withPriority(int priority) { if (priority < 100 || priority > 4096) { throw logger.logExceptionAsError(new IllegalArgumentException( "The priority number of a network security rule must be between 100 and 4096.")); } this.inner().withPriority(priority); return this; } @Override public NetworkSecurityRuleImpl withDescription(String description) { this.inner().withDescription(description); return this; } @Override public NetworkSecurityRuleImpl withSourceApplicationSecurityGroup(String id) { sourceAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withSourceAddressPrefix(null); inner().withSourceAddressPrefixes(null); return this; } @Override public NetworkSecurityRuleImpl withDestinationApplicationSecurityGroup(String id) { destinationAsgs.put(id, new ApplicationSecurityGroupInner().withId(id)); inner().withDestinationAddressPrefix(null); inner().withDestinationAddressPrefixes(null); return this; } private NetworkSecurityRuleImpl withDirection(SecurityRuleDirection direction) { this.inner().withDirection(direction); return this; } private NetworkSecurityRuleImpl withAccess(SecurityRuleAccess permission) { this.inner().withAccess(permission); return this; } @Override public NetworkSecurityGroupImpl attach() { inner().withSourceApplicationSecurityGroups(new ArrayList<>(sourceAsgs.values())); inner().withDestinationApplicationSecurityGroups(new ArrayList<>(destinationAsgs.values())); return this.parent().withRule(this); } @Override public String description() { return this.inner().description(); } }
done
protected Mono<NetworkInterfaceInner> getInnerAsync() { return this .manager() .inner() .networkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name(), null); }
protected Mono<NetworkInterfaceInner> getInnerAsync() { return this .manager() .inner() .networkInterfaces() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); }
class NetworkInterfaceImpl extends GroupableParentResourceWithTagsImpl< NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { /** the name of the network interface. */ private final String nicName; /** used to generate unique name for any dependency resources. */ protected final ResourceNamer namer; /** references to all ip configuration. */ private Map<String, NicIPConfiguration> nicIPConfigurations; /** unique key of a creatable network security group to be associated with the network interface. */ private String creatableNetworkSecurityGroupKey; /** reference to an network security group to be associated with the network interface. */ private NetworkSecurityGroup existingNetworkSecurityGroupToAssociate; /** cached related resources. */ private NetworkSecurityGroup networkSecurityGroup; NetworkInterfaceImpl(String name, NetworkInterfaceInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.nicName = name; this.namer = this.manager().getSdkContext().getResourceNamerFactory().createResourceNamer(this.nicName); initializeChildrenFromInner(); } @Override public Mono<NetworkInterface> refreshAsync() { return super .refreshAsync() .map( networkInterface -> { NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; impl.clearCachedRelatedResources(); impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkInterfaceInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkInterfaces() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public NetworkInterfaceImpl withAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(true); return this; } @Override public NetworkInterfaceImpl withoutAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(false); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(Creatable<Network> creatable) { this.primaryIPConfiguration().withNewNetwork(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String name, String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(name, addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryNetwork(Network network) { this.primaryIPConfiguration().withExistingNetwork(network); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) { this.primaryIPConfiguration().withNewPublicIPAddress(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress() { this.primaryIPConfiguration().withNewPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { this.primaryIPConfiguration().withNewPublicIPAddress(leafDnsLabel); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBalancer, String backendName) { this.primaryIPConfiguration().withExistingLoadBalancerBackend(loadBalancer, backendName); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( LoadBalancer loadBalancer, String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @Override public Update withoutLoadBalancerBackends() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerBackends(); } return this; } @Override public Update withoutLoadBalancerInboundNatRules() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerInboundNatRules(); } return this; } @Override public NetworkInterfaceImpl withoutPrimaryPublicIPAddress() { this.primaryIPConfiguration().withoutPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) { this.primaryIPConfiguration().withExistingPublicIPAddress(publicIPAddress); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressDynamic() { this.primaryIPConfiguration().withPrivateIPAddressDynamic(); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { this.primaryIPConfiguration().withPrivateIPAddressStatic(staticPrivateIPAddress); return this; } @Override public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) { if (this.creatableNetworkSecurityGroupKey == null) { this.creatableNetworkSecurityGroupKey = this.addDependency(creatable); } return this; } @Override public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) { this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup; return this; } @Override public NetworkInterfaceImpl withoutNetworkSecurityGroup() { this.inner().withNetworkSecurityGroup(null); return this; } @Override public NicIPConfigurationImpl defineSecondaryIPConfiguration(String name) { return prepareNewNicIPConfiguration(name); } @Override public NicIPConfigurationImpl updateIPConfiguration(String name) { return (NicIPConfigurationImpl) this.nicIPConfigurations.get(name); } @Override public NetworkInterfaceImpl withIPForwarding() { this.inner().withEnableIPForwarding(true); return this; } @Override public NetworkInterfaceImpl withoutIPConfiguration(String name) { this.nicIPConfigurations.remove(name); return this; } @Override public NetworkInterfaceImpl withoutIPForwarding() { this.inner().withEnableIPForwarding(false); return this; } @Override public NetworkInterfaceImpl withDnsServer(String ipAddress) { this.dnsServerIPs().add(ipAddress); return this; } @Override public NetworkInterfaceImpl withoutDnsServer(String ipAddress) { this.dnsServerIPs().remove(ipAddress); return this; } @Override public NetworkInterfaceImpl withAzureDnsServer() { this.dnsServerIPs().clear(); return this; } @Override public NetworkInterfaceImpl withSubnet(String name) { this.primaryIPConfiguration().withSubnet(name); return this; } @Override public NetworkInterfaceImpl withInternalDnsNameLabel(String dnsNameLabel) { this.inner().dnsSettings().withInternalDnsNameLabel(dnsNameLabel); return this; } @Override public boolean isAcceleratedNetworkingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableAcceleratedNetworking()); } @Override public String virtualMachineId() { if (this.inner().virtualMachine() != null) { return this.inner().virtualMachine().getId(); } else { return null; } } @Override public boolean isIPForwardingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableIPForwarding()); } @Override public String macAddress() { return this.inner().macAddress(); } @Override public String internalDnsNameLabel() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDnsNameLabel() : null; } @Override public String internalDomainNameSuffix() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDomainNameSuffix() : null; } @Override public List<String> appliedDnsServers() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return Collections.unmodifiableList(dnsServers); } else if (this.inner().dnsSettings().appliedDnsServers() == null) { return Collections.unmodifiableList(dnsServers); } else { return Collections.unmodifiableList(this.inner().dnsSettings().appliedDnsServers()); } } @Override public String internalFqdn() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalFqdn() : null; } @Override public List<String> dnsServers() { return this.dnsServerIPs(); } @Override public String primaryPrivateIP() { return this.primaryIPConfiguration().privateIPAddress(); } @Override public IPAllocationMethod primaryPrivateIPAllocationMethod() { return this.primaryIPConfiguration().privateIPAllocationMethod(); } @Override public Map<String, NicIPConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.nicIPConfigurations); } @Override public String networkSecurityGroupId() { return (this.inner().networkSecurityGroup() != null) ? this.inner().networkSecurityGroup().getId() : null; } @Override public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); this.networkSecurityGroup = super .myManager .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } /** @return the primary IP configuration of the network interface */ @Override public NicIPConfigurationImpl primaryIPConfiguration() { NicIPConfigurationImpl primaryIPConfig = null; if (this.nicIPConfigurations.size() == 0) { primaryIPConfig = prepareNewNicIPConfiguration("primary"); primaryIPConfig.inner().withPrimary(true); withIPConfiguration(primaryIPConfig); } else if (this.nicIPConfigurations.size() == 1) { primaryIPConfig = (NicIPConfigurationImpl) this.nicIPConfigurations.values().iterator().next(); } else { for (NicIPConfiguration ipConfig : this.nicIPConfigurations.values()) { if (ipConfig.isPrimary()) { primaryIPConfig = (NicIPConfigurationImpl) ipConfig; break; } } } return primaryIPConfig; } /** @return the list of DNS server IPs from the DNS settings */ private List<String> dnsServerIPs() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return dnsServers; } else if (this.inner().dnsSettings().dnsServers() == null) { return dnsServers; } else { return this.inner().dnsSettings().dnsServers(); } } @Override protected void initializeChildrenFromInner() { this.nicIPConfigurations = new TreeMap<>(); List<NetworkInterfaceIPConfigurationInner> inners = this.inner().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIPConfigurationInner inner : inners) { NicIPConfigurationImpl nicIPConfiguration = new NicIPConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } } /** * Gets a new IP configuration child resource {@link NicIPConfiguration} wrapping {@link * NetworkInterfaceIPConfigurationInner}. * * @param name the name for the new ip configuration * @return {@link NicIPConfiguration} */ private NicIPConfigurationImpl prepareNewNicIPConfiguration(String name) { NicIPConfigurationImpl nicIPConfiguration = NicIPConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } private void clearCachedRelatedResources() { this.networkSecurityGroup = null; } NetworkInterfaceImpl withIPConfiguration(NicIPConfigurationImpl nicIPConfiguration) { this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); return this; } void addToCreatableDependencies(Creatable<? extends Resource> creatableResource) { this.addDependency(creatableResource); } Resource createdDependencyResource(String key) { return this.<Resource>taskResult(key); } Creatable<ResourceGroup> newGroup() { return this.creatableGroup; } @Override protected Mono<NetworkInterfaceInner> createInner() { return this .manager() .inner() .networkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override protected void afterCreating() { clearCachedRelatedResources(); } @Override protected void beforeCreating() { NetworkSecurityGroup networkSecurityGroup = null; if (creatableNetworkSecurityGroupKey != null) { networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey); } else if (existingNetworkSecurityGroupToAssociate != null) { networkSecurityGroup = existingNetworkSecurityGroupToAssociate; } if (networkSecurityGroup != null) { this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values()); this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values())); } }
class NetworkInterfaceImpl extends GroupableParentResourceWithTagsImpl< NetworkInterface, NetworkInterfaceInner, NetworkInterfaceImpl, NetworkManager> implements NetworkInterface, NetworkInterface.Definition, NetworkInterface.Update { /** the name of the network interface. */ private final String nicName; /** used to generate unique name for any dependency resources. */ protected final ResourceNamer namer; /** references to all ip configuration. */ private Map<String, NicIPConfiguration> nicIPConfigurations; /** unique key of a creatable network security group to be associated with the network interface. */ private String creatableNetworkSecurityGroupKey; /** reference to an network security group to be associated with the network interface. */ private NetworkSecurityGroup existingNetworkSecurityGroupToAssociate; /** cached related resources. */ private NetworkSecurityGroup networkSecurityGroup; NetworkInterfaceImpl(String name, NetworkInterfaceInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); this.nicName = name; this.namer = this.manager().getSdkContext().getResourceNamerFactory().createResourceNamer(this.nicName); initializeChildrenFromInner(); } @Override public Mono<NetworkInterface> refreshAsync() { return super .refreshAsync() .map( networkInterface -> { NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface; impl.clearCachedRelatedResources(); impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkInterfaceInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkInterfaces() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public NetworkInterfaceImpl withAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(true); return this; } @Override public NetworkInterfaceImpl withoutAcceleratedNetworking() { this.inner().withEnableAcceleratedNetworking(false); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(Creatable<Network> creatable) { this.primaryIPConfiguration().withNewNetwork(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String name, String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(name, addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withNewPrimaryNetwork(String addressSpaceCidr) { this.primaryIPConfiguration().withNewNetwork(addressSpaceCidr); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryNetwork(Network network) { this.primaryIPConfiguration().withExistingNetwork(network); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) { this.primaryIPConfiguration().withNewPublicIPAddress(creatable); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress() { this.primaryIPConfiguration().withNewPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) { this.primaryIPConfiguration().withNewPublicIPAddress(leafDnsLabel); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerBackend(LoadBalancer loadBalancer, String backendName) { this.primaryIPConfiguration().withExistingLoadBalancerBackend(loadBalancer, backendName); return this; } @Override public NetworkInterfaceImpl withExistingLoadBalancerInboundNatRule( LoadBalancer loadBalancer, String inboundNatRuleName) { this.primaryIPConfiguration().withExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); return this; } @Override public Update withoutLoadBalancerBackends() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerBackends(); } return this; } @Override public Update withoutLoadBalancerInboundNatRules() { for (NicIPConfiguration ipConfig : this.ipConfigurations().values()) { this.updateIPConfiguration(ipConfig.name()).withoutLoadBalancerInboundNatRules(); } return this; } @Override public NetworkInterfaceImpl withoutPrimaryPublicIPAddress() { this.primaryIPConfiguration().withoutPublicIPAddress(); return this; } @Override public NetworkInterfaceImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) { this.primaryIPConfiguration().withExistingPublicIPAddress(publicIPAddress); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressDynamic() { this.primaryIPConfiguration().withPrivateIPAddressDynamic(); return this; } @Override public NetworkInterfaceImpl withPrimaryPrivateIPAddressStatic(String staticPrivateIPAddress) { this.primaryIPConfiguration().withPrivateIPAddressStatic(staticPrivateIPAddress); return this; } @Override public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) { if (this.creatableNetworkSecurityGroupKey == null) { this.creatableNetworkSecurityGroupKey = this.addDependency(creatable); } return this; } @Override public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) { this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup; return this; } @Override public NetworkInterfaceImpl withoutNetworkSecurityGroup() { this.inner().withNetworkSecurityGroup(null); return this; } @Override public NicIPConfigurationImpl defineSecondaryIPConfiguration(String name) { return prepareNewNicIPConfiguration(name); } @Override public NicIPConfigurationImpl updateIPConfiguration(String name) { return (NicIPConfigurationImpl) this.nicIPConfigurations.get(name); } @Override public NetworkInterfaceImpl withIPForwarding() { this.inner().withEnableIPForwarding(true); return this; } @Override public NetworkInterfaceImpl withoutIPConfiguration(String name) { this.nicIPConfigurations.remove(name); return this; } @Override public NetworkInterfaceImpl withoutIPForwarding() { this.inner().withEnableIPForwarding(false); return this; } @Override public NetworkInterfaceImpl withDnsServer(String ipAddress) { this.dnsServerIPs().add(ipAddress); return this; } @Override public NetworkInterfaceImpl withoutDnsServer(String ipAddress) { this.dnsServerIPs().remove(ipAddress); return this; } @Override public NetworkInterfaceImpl withAzureDnsServer() { this.dnsServerIPs().clear(); return this; } @Override public NetworkInterfaceImpl withSubnet(String name) { this.primaryIPConfiguration().withSubnet(name); return this; } @Override public NetworkInterfaceImpl withInternalDnsNameLabel(String dnsNameLabel) { this.inner().dnsSettings().withInternalDnsNameLabel(dnsNameLabel); return this; } @Override public boolean isAcceleratedNetworkingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableAcceleratedNetworking()); } @Override public String virtualMachineId() { if (this.inner().virtualMachine() != null) { return this.inner().virtualMachine().getId(); } else { return null; } } @Override public boolean isIPForwardingEnabled() { return Utils.toPrimitiveBoolean(this.inner().enableIPForwarding()); } @Override public String macAddress() { return this.inner().macAddress(); } @Override public String internalDnsNameLabel() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDnsNameLabel() : null; } @Override public String internalDomainNameSuffix() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalDomainNameSuffix() : null; } @Override public List<String> appliedDnsServers() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return Collections.unmodifiableList(dnsServers); } else if (this.inner().dnsSettings().appliedDnsServers() == null) { return Collections.unmodifiableList(dnsServers); } else { return Collections.unmodifiableList(this.inner().dnsSettings().appliedDnsServers()); } } @Override public String internalFqdn() { return (this.inner().dnsSettings() != null) ? this.inner().dnsSettings().internalFqdn() : null; } @Override public List<String> dnsServers() { return this.dnsServerIPs(); } @Override public String primaryPrivateIP() { return this.primaryIPConfiguration().privateIPAddress(); } @Override public IPAllocationMethod primaryPrivateIPAllocationMethod() { return this.primaryIPConfiguration().privateIPAllocationMethod(); } @Override public Map<String, NicIPConfiguration> ipConfigurations() { return Collections.unmodifiableMap(this.nicIPConfigurations); } @Override public String networkSecurityGroupId() { return (this.inner().networkSecurityGroup() != null) ? this.inner().networkSecurityGroup().getId() : null; } @Override public NetworkSecurityGroup getNetworkSecurityGroup() { if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) { String id = this.networkSecurityGroupId(); this.networkSecurityGroup = super .myManager .networkSecurityGroups() .getByResourceGroup(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); } return this.networkSecurityGroup; } /** @return the primary IP configuration of the network interface */ @Override public NicIPConfigurationImpl primaryIPConfiguration() { NicIPConfigurationImpl primaryIPConfig = null; if (this.nicIPConfigurations.size() == 0) { primaryIPConfig = prepareNewNicIPConfiguration("primary"); primaryIPConfig.inner().withPrimary(true); withIPConfiguration(primaryIPConfig); } else if (this.nicIPConfigurations.size() == 1) { primaryIPConfig = (NicIPConfigurationImpl) this.nicIPConfigurations.values().iterator().next(); } else { for (NicIPConfiguration ipConfig : this.nicIPConfigurations.values()) { if (ipConfig.isPrimary()) { primaryIPConfig = (NicIPConfigurationImpl) ipConfig; break; } } } return primaryIPConfig; } /** @return the list of DNS server IPs from the DNS settings */ private List<String> dnsServerIPs() { List<String> dnsServers = new ArrayList<String>(); if (this.inner().dnsSettings() == null) { return dnsServers; } else if (this.inner().dnsSettings().dnsServers() == null) { return dnsServers; } else { return this.inner().dnsSettings().dnsServers(); } } @Override protected void initializeChildrenFromInner() { this.nicIPConfigurations = new TreeMap<>(); List<NetworkInterfaceIPConfigurationInner> inners = this.inner().ipConfigurations(); if (inners != null) { for (NetworkInterfaceIPConfigurationInner inner : inners) { NicIPConfigurationImpl nicIPConfiguration = new NicIPConfigurationImpl(inner, this, super.myManager, false); this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); } } } /** * Gets a new IP configuration child resource {@link NicIPConfiguration} wrapping {@link * NetworkInterfaceIPConfigurationInner}. * * @param name the name for the new ip configuration * @return {@link NicIPConfiguration} */ private NicIPConfigurationImpl prepareNewNicIPConfiguration(String name) { NicIPConfigurationImpl nicIPConfiguration = NicIPConfigurationImpl.prepareNicIPConfiguration(name, this, super.myManager); return nicIPConfiguration; } private void clearCachedRelatedResources() { this.networkSecurityGroup = null; } NetworkInterfaceImpl withIPConfiguration(NicIPConfigurationImpl nicIPConfiguration) { this.nicIPConfigurations.put(nicIPConfiguration.name(), nicIPConfiguration); return this; } void addToCreatableDependencies(Creatable<? extends Resource> creatableResource) { this.addDependency(creatableResource); } Resource createdDependencyResource(String key) { return this.<Resource>taskResult(key); } Creatable<ResourceGroup> newGroup() { return this.creatableGroup; } @Override protected Mono<NetworkInterfaceInner> createInner() { return this .manager() .inner() .networkInterfaces() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override protected void afterCreating() { clearCachedRelatedResources(); } @Override protected void beforeCreating() { NetworkSecurityGroup networkSecurityGroup = null; if (creatableNetworkSecurityGroupKey != null) { networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey); } else if (existingNetworkSecurityGroupToAssociate != null) { networkSecurityGroup = existingNetworkSecurityGroupToAssociate; } if (networkSecurityGroup != null) { this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id())); } NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values()); this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values())); } }
done
protected Mono<NetworkSecurityGroupInner> getInnerAsync() { return this .manager() .inner() .networkSecurityGroups() .getByResourceGroupAsync(this.resourceGroupName(), this.name(), null); }
protected Mono<NetworkSecurityGroupInner> getInnerAsync() { return this .manager() .inner() .networkSecurityGroups() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); }
class NetworkSecurityGroupImpl extends GroupableParentResourceWithTagsImpl< NetworkSecurityGroup, NetworkSecurityGroupInner, NetworkSecurityGroupImpl, NetworkManager> implements NetworkSecurityGroup, NetworkSecurityGroup.Definition, NetworkSecurityGroup.Update { private Map<String, NetworkSecurityRule> rules; private Map<String, NetworkSecurityRule> defaultRules; NetworkSecurityGroupImpl( final String name, final NetworkSecurityGroupInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected void initializeChildrenFromInner() { this.rules = new TreeMap<>(); List<SecurityRuleInner> inners = this.inner().securityRules(); if (inners != null) { for (SecurityRuleInner inner : inners) { this.rules.put(inner.name(), new NetworkSecurityRuleImpl(inner, this)); } } this.defaultRules = new TreeMap<>(); inners = this.inner().defaultSecurityRules(); if (inners != null) { for (SecurityRuleInner inner : inners) { this.defaultRules.put(inner.name(), new NetworkSecurityRuleImpl(inner, this)); } } } @Override public NetworkSecurityRuleImpl updateRule(String name) { return (NetworkSecurityRuleImpl) this.rules.get(name); } @Override public NetworkSecurityRuleImpl defineRule(String name) { SecurityRuleInner inner = new SecurityRuleInner(); inner.withName(name); inner.withPriority(100); return new NetworkSecurityRuleImpl(inner, this); } @Override public Mono<NetworkSecurityGroup> refreshAsync() { return super .refreshAsync() .map( networkSecurityGroup -> { NetworkSecurityGroupImpl impl = (NetworkSecurityGroupImpl) networkSecurityGroup; impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkSecurityGroupInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkSecurityGroups() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public List<Subnet> listAssociatedSubnets() { return this.myManager.listAssociatedSubnets(this.inner().subnets()); } @Override public Update withoutRule(String name) { this.rules.remove(name); return this; } NetworkSecurityGroupImpl withRule(NetworkSecurityRuleImpl rule) { this.rules.put(rule.name(), rule); return this; } @Override public Map<String, NetworkSecurityRule> securityRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, NetworkSecurityRule> defaultSecurityRules() { return Collections.unmodifiableMap(this.defaultRules); } @Override public Set<String> networkInterfaceIds() { Set<String> ids = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (this.inner().networkInterfaces() != null) { for (NetworkInterfaceInner inner : this.inner().networkInterfaces()) { ids.add(inner.getId()); } } return Collections.unmodifiableSet(ids); } @Override protected void beforeCreating() { this.inner().withSecurityRules(innersFromWrappers(this.rules.values())); } @Override protected Mono<NetworkSecurityGroupInner> createInner() { return this .manager() .inner() .networkSecurityGroups() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } }
class NetworkSecurityGroupImpl extends GroupableParentResourceWithTagsImpl< NetworkSecurityGroup, NetworkSecurityGroupInner, NetworkSecurityGroupImpl, NetworkManager> implements NetworkSecurityGroup, NetworkSecurityGroup.Definition, NetworkSecurityGroup.Update { private Map<String, NetworkSecurityRule> rules; private Map<String, NetworkSecurityRule> defaultRules; NetworkSecurityGroupImpl( final String name, final NetworkSecurityGroupInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected void initializeChildrenFromInner() { this.rules = new TreeMap<>(); List<SecurityRuleInner> inners = this.inner().securityRules(); if (inners != null) { for (SecurityRuleInner inner : inners) { this.rules.put(inner.name(), new NetworkSecurityRuleImpl(inner, this)); } } this.defaultRules = new TreeMap<>(); inners = this.inner().defaultSecurityRules(); if (inners != null) { for (SecurityRuleInner inner : inners) { this.defaultRules.put(inner.name(), new NetworkSecurityRuleImpl(inner, this)); } } } @Override public NetworkSecurityRuleImpl updateRule(String name) { return (NetworkSecurityRuleImpl) this.rules.get(name); } @Override public NetworkSecurityRuleImpl defineRule(String name) { SecurityRuleInner inner = new SecurityRuleInner(); inner.withName(name); inner.withPriority(100); return new NetworkSecurityRuleImpl(inner, this); } @Override public Mono<NetworkSecurityGroup> refreshAsync() { return super .refreshAsync() .map( networkSecurityGroup -> { NetworkSecurityGroupImpl impl = (NetworkSecurityGroupImpl) networkSecurityGroup; impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<NetworkSecurityGroupInner> applyTagsToInnerAsync() { return this .manager() .inner() .networkSecurityGroups() .updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override public List<Subnet> listAssociatedSubnets() { return this.myManager.listAssociatedSubnets(this.inner().subnets()); } @Override public Update withoutRule(String name) { this.rules.remove(name); return this; } NetworkSecurityGroupImpl withRule(NetworkSecurityRuleImpl rule) { this.rules.put(rule.name(), rule); return this; } @Override public Map<String, NetworkSecurityRule> securityRules() { return Collections.unmodifiableMap(this.rules); } @Override public Map<String, NetworkSecurityRule> defaultSecurityRules() { return Collections.unmodifiableMap(this.defaultRules); } @Override public Set<String> networkInterfaceIds() { Set<String> ids = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (this.inner().networkInterfaces() != null) { for (NetworkInterfaceInner inner : this.inner().networkInterfaces()) { ids.add(inner.getId()); } } return Collections.unmodifiableSet(ids); } @Override protected void beforeCreating() { this.inner().withSecurityRules(innersFromWrappers(this.rules.values())); } @Override protected Mono<NetworkSecurityGroupInner> createInner() { return this .manager() .inner() .networkSecurityGroups() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } }
Eh, I mean, you could try delete the `null` in `.getByResourceGroupAsync(this.resourceGroupName(), this.name(), null);`. If it compiles then all is good. If not let me know. It should works same on `.getByResourceGroupAsync(this.resourceGroupName(), this.name());` The `null` is there when the above overload method is not generated by old generator. So yaohai added the `null` to build pass and add that `TODO`.
protected Mono<LoadBalancerInner> getInnerAsync() { return this .manager() .inner() .loadBalancers() .getByResourceGroupAsync(this.resourceGroupName(), this.name(), null); }
return this
protected Mono<LoadBalancerInner> getInnerAsync() { return this .manager() .inner() .loadBalancers() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); }
class LoadBalancerImpl extends GroupableParentResourceWithTagsImpl<LoadBalancer, LoadBalancerInner, LoadBalancerImpl, NetworkManager> implements LoadBalancer, LoadBalancer.Definition, LoadBalancer.Update { private final ClientLogger logger = new ClientLogger(getClass()); private final Map<String, String> nicsInBackends = new HashMap<>(); protected final Map<String, String> creatablePIPKeys = new HashMap<>(); private Map<String, LoadBalancerBackend> backends; private Map<String, LoadBalancerTcpProbe> tcpProbes; private Map<String, LoadBalancerHttpProbe> httpProbes; private Map<String, LoadBalancerHttpProbe> httpsProbes; private Map<String, LoadBalancingRule> loadBalancingRules; private Map<String, LoadBalancerFrontend> frontends; private Map<String, LoadBalancerInboundNatRule> inboundNatRules; private Map<String, LoadBalancerInboundNatPool> inboundNatPools; LoadBalancerImpl(String name, final LoadBalancerInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<LoadBalancer> refreshAsync() { return super .refreshAsync() .map( loadBalancer -> { LoadBalancerImpl impl = (LoadBalancerImpl) loadBalancer; impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<LoadBalancerInner> applyTagsToInnerAsync() { return this.manager().inner().loadBalancers().updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override protected void initializeChildrenFromInner() { initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeLoadBalancingRulesFromInner(); initializeInboundNatRulesFromInner(); initializeInboundNatPoolsFromInner(); } protected LoadBalancerBackendImpl ensureUniqueBackend() { String name = this.manager().getSdkContext().randomResourceName("backend", 20); LoadBalancerBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } protected SubResource ensureFrontendRef(String name) { LoadBalancerFrontendImpl frontend; if (name == null) { frontend = this.ensureUniqueFrontend(); } else { frontend = this.defineFrontend(name); frontend.attach(); } return new SubResource().setId(this.futureResourceId() + "/frontendIPConfigurations/" + frontend.name()); } protected LoadBalancerFrontendImpl ensureUniqueFrontend() { String name = this.manager().getSdkContext().randomResourceName("frontend", 20); LoadBalancerFrontendImpl frontend = this.defineFrontend(name); frontend.attach(); return frontend; } LoadBalancerPrivateFrontend findPrivateFrontendWithSubnet(String networkId, String subnetName) { if (null == networkId || null == subnetName) { return null; } else { for (LoadBalancerPrivateFrontend frontend : this.privateFrontends().values()) { if (frontend.networkId() == null || frontend.subnetName() == null) { continue; } else if (networkId.equalsIgnoreCase(frontend.networkId()) && subnetName.equalsIgnoreCase(frontend.subnetName())) { return frontend; } } return null; } } LoadBalancerPrivateFrontend ensurePrivateFrontendWithSubnet(String networkId, String subnetName) { LoadBalancerPrivateFrontend frontend = this.findPrivateFrontendWithSubnet(networkId, subnetName); if (networkId == null || subnetName == null) { return null; } else if (frontend != null) { return frontend; } else { LoadBalancerFrontendImpl fe = this.ensureUniqueFrontend().withExistingSubnet(networkId, subnetName).withPrivateIPAddressDynamic(); fe.attach(); return fe; } } LoadBalancerPublicFrontend ensurePublicFrontendWithPip(String pipId) { LoadBalancerPublicFrontend frontend = this.findFrontendByPublicIPAddress(pipId); if (pipId == null) { return null; } else if (frontend != null) { return frontend; } else { LoadBalancerFrontendImpl fe = this.ensureUniqueFrontend().withExistingPublicIPAddress(pipId); fe.attach(); return fe; } } @Override protected void beforeCreating() { if (this.creatablePIPKeys != null) { for (Entry<String, String> pipFrontendAssociation : this.creatablePIPKeys.entrySet()) { PublicIPAddress pip = this.<PublicIPAddress>taskResult(pipFrontendAssociation.getKey()); if (pip != null) { withExistingPublicIPAddress(pip.id(), pipFrontendAssociation.getValue()); } } this.creatablePIPKeys.clear(); } List<ProbeInner> innerProbes = innersFromWrappers(this.httpProbes.values()); innerProbes = innersFromWrappers(this.httpsProbes.values(), innerProbes); innerProbes = innersFromWrappers(this.tcpProbes.values(), innerProbes); if (innerProbes == null) { innerProbes = new ArrayList<>(); } this.inner().withProbes(innerProbes); List<BackendAddressPoolInner> innerBackends = innersFromWrappers(this.backends.values()); if (null == innerBackends) { innerBackends = new ArrayList<>(); } this.inner().withBackendAddressPools(innerBackends); List<FrontendIPConfigurationInner> innerFrontends = innersFromWrappers(this.frontends.values()); if (null == innerFrontends) { innerFrontends = new ArrayList<>(); } this.inner().withFrontendIPConfigurations(innerFrontends); List<InboundNatRuleInner> innerNatRules = innersFromWrappers(this.inboundNatRules.values()); if (null == innerNatRules) { innerNatRules = new ArrayList<>(); } this.inner().withInboundNatRules(innerNatRules); for (LoadBalancerInboundNatRule natRule : this.inboundNatRules.values()) { SubResource ref = natRule.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { natRule.inner().withFrontendIPConfiguration(null); } } List<InboundNatPool> innerNatPools = innersFromWrappers(this.inboundNatPools.values()); if (null == innerNatPools) { innerNatPools = new ArrayList<>(); } this.inner().withInboundNatPools(innerNatPools); for (LoadBalancerInboundNatPool natPool : this.inboundNatPools.values()) { SubResource ref = natPool.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { natPool.inner().withFrontendIPConfiguration(null); } } List<LoadBalancingRuleInner> innerRules = innersFromWrappers(this.loadBalancingRules.values()); if (innerRules == null) { innerRules = new ArrayList<>(); } this.inner().withLoadBalancingRules(innerRules); for (LoadBalancingRule lbRule : this.loadBalancingRules.values()) { SubResource ref; ref = lbRule.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withFrontendIPConfiguration(null); } ref = lbRule.inner().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withBackendAddressPool(null); } ref = lbRule.inner().probe(); if (ref != null && !this.httpProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId())) && !this.httpsProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId())) && !this.tcpProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withProbe(null); } } } protected Mono<Void> afterCreatingAsync() { if (this.nicsInBackends != null) { List<Throwable> nicExceptions = new ArrayList<>(); return Flux .fromIterable(this.nicsInBackends.entrySet()) .flatMap( nicInBackend -> { String nicId = nicInBackend.getKey(); String backendName = nicInBackend.getValue(); return this .manager() .networkInterfaces() .getByIdAsync(nicId) .flatMap( nic -> { NicIPConfiguration nicIP = nic.primaryIPConfiguration(); return nic .update() .updateIPConfiguration(nicIP.name()) .withExistingLoadBalancerBackend(this, backendName) .parent() .applyAsync(); }); }) .onErrorResume( t -> { nicExceptions.add(t); return Mono.empty(); }) .then( Mono .defer( () -> { if (!nicExceptions.isEmpty()) { return Mono.error(Exceptions.multiple(nicExceptions)); } else { this.nicsInBackends.clear(); return Mono.empty(); } })); } return Mono.empty(); } @Override protected Mono<LoadBalancerInner> createInner() { return this .manager() .inner() .loadBalancers() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override public Mono<LoadBalancer> createResourceAsync() { beforeCreating(); return createInner() .flatMap( inner -> { setInner(inner); initializeChildrenFromInner(); return afterCreatingAsync().then(this.refreshAsync()); }); } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<FrontendIPConfigurationInner> frontendsInner = this.inner().frontendIPConfigurations(); if (frontendsInner != null) { for (FrontendIPConfigurationInner frontendInner : frontendsInner) { LoadBalancerFrontendImpl frontend = new LoadBalancerFrontendImpl(frontendInner, this); this.frontends.put(frontendInner.name(), frontend); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<BackendAddressPoolInner> backendsInner = this.inner().backendAddressPools(); if (backendsInner != null) { for (BackendAddressPoolInner backendInner : backendsInner) { LoadBalancerBackendImpl backend = new LoadBalancerBackendImpl(backendInner, this); this.backends.put(backendInner.name(), backend); } } } private void initializeProbesFromInner() { this.httpProbes = new TreeMap<>(); this.httpsProbes = new TreeMap<>(); this.tcpProbes = new TreeMap<>(); if (this.inner().probes() != null) { for (ProbeInner probeInner : this.inner().probes()) { LoadBalancerProbeImpl probe = new LoadBalancerProbeImpl(probeInner, this); if (probeInner.protocol().equals(ProbeProtocol.TCP)) { this.tcpProbes.put(probeInner.name(), probe); } else if (probeInner.protocol().equals(ProbeProtocol.HTTP)) { this.httpProbes.put(probeInner.name(), probe); } else if (probeInner.protocol().equals(ProbeProtocol.HTTPS)) { this.httpsProbes.put(probeInner.name(), probe); } } } } private void initializeLoadBalancingRulesFromInner() { this.loadBalancingRules = new TreeMap<>(); List<LoadBalancingRuleInner> rulesInner = this.inner().loadBalancingRules(); if (rulesInner != null) { for (LoadBalancingRuleInner ruleInner : rulesInner) { LoadBalancingRuleImpl rule = new LoadBalancingRuleImpl(ruleInner, this); this.loadBalancingRules.put(ruleInner.name(), rule); } } } private void initializeInboundNatPoolsFromInner() { this.inboundNatPools = new TreeMap<>(); List<InboundNatPool> inners = this.inner().inboundNatPools(); if (inners != null) { for (InboundNatPool inner : inners) { LoadBalancerInboundNatPoolImpl wrapper = new LoadBalancerInboundNatPoolImpl(inner, this); this.inboundNatPools.put(wrapper.name(), wrapper); } } } private void initializeInboundNatRulesFromInner() { this.inboundNatRules = new TreeMap<>(); List<InboundNatRuleInner> rulesInner = this.inner().inboundNatRules(); if (rulesInner != null) { for (InboundNatRuleInner ruleInner : rulesInner) { LoadBalancerInboundNatRuleImpl rule = new LoadBalancerInboundNatRuleImpl(ruleInner, this); this.inboundNatRules.put(ruleInner.name(), rule); } } } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/loadBalancers/") .append(this.name()) .toString(); } LoadBalancerImpl withFrontend(LoadBalancerFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } LoadBalancerImpl withProbe(LoadBalancerProbeImpl probe) { if (probe == null) { return this; } else if (probe.protocol() == ProbeProtocol.HTTP) { httpProbes.put(probe.name(), probe); } else if (probe.protocol() == ProbeProtocol.HTTPS) { httpsProbes.put(probe.name(), probe); } else if (probe.protocol() == ProbeProtocol.TCP) { tcpProbes.put(probe.name(), probe); } return this; } LoadBalancerImpl withLoadBalancingRule(LoadBalancingRuleImpl loadBalancingRule) { if (loadBalancingRule != null) { this.loadBalancingRules.put(loadBalancingRule.name(), loadBalancingRule); } return this; } LoadBalancerImpl withInboundNatRule(LoadBalancerInboundNatRuleImpl inboundNatRule) { if (inboundNatRule != null) { this.inboundNatRules.put(inboundNatRule.name(), inboundNatRule); } return this; } LoadBalancerImpl withInboundNatPool(LoadBalancerInboundNatPoolImpl inboundNatPool) { if (inboundNatPool != null) { this.inboundNatPools.put(inboundNatPool.name(), inboundNatPool); } return this; } LoadBalancerImpl withBackend(LoadBalancerBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } LoadBalancerImpl withNewPublicIPAddress(String dnsLeafLabel, String frontendName) { PublicIPAddress.DefinitionStages.WithGroup precreatablePIP = manager().publicIPAddresses().define(dnsLeafLabel).withRegion(this.regionName()); Creatable<PublicIPAddress> creatablePip; if (super.creatableGroup == null) { creatablePip = precreatablePIP.withExistingResourceGroup(this.resourceGroupName()).withLeafDomainLabel(dnsLeafLabel); } else { creatablePip = precreatablePIP.withNewResourceGroup(super.creatableGroup).withLeafDomainLabel(dnsLeafLabel); } return withNewPublicIPAddress(creatablePip, frontendName); } LoadBalancerImpl withNewPublicIPAddress(Creatable<PublicIPAddress> creatablePip, String frontendName) { String existingPipFrontendName = this.creatablePIPKeys.get(creatablePip.key()); if (frontendName == null) { if (existingPipFrontendName != null) { frontendName = existingPipFrontendName; } else { frontendName = ensureUniqueFrontend().name(); } } if (existingPipFrontendName == null) { this.creatablePIPKeys.put(this.addDependency(creatablePip), frontendName); } else if (!existingPipFrontendName.equalsIgnoreCase(frontendName)) { throw logger.logExceptionAsError(new IllegalArgumentException( "This public IP address definition is already associated with a frontend under a different name.")); } return this; } protected LoadBalancerImpl withExistingPublicIPAddress(String resourceId, String frontendName) { if (frontendName == null) { return ensureUniqueFrontend().withExistingPublicIPAddress(resourceId).parent(); } else { return this.definePublicFrontend(frontendName).withExistingPublicIPAddress(resourceId).attach(); } } LoadBalancerImpl withExistingVirtualMachine(HasNetworkInterfaces vm, String backendName) { if (backendName != null) { this.defineBackend(backendName).attach(); if (vm.primaryNetworkInterfaceId() != null) { this.nicsInBackends.put(vm.primaryNetworkInterfaceId(), backendName.toLowerCase()); } } return this; } @Override public LoadBalancerProbeImpl defineTcpProbe(String name) { LoadBalancerProbe probe = this.tcpProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.TCP); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancerProbeImpl defineHttpProbe(String name) { LoadBalancerProbe probe = this.httpProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.HTTP).withPort(80); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancerProbeImpl defineHttpsProbe(String name) { LoadBalancerProbe probe = this.httpsProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.HTTPS).withPort(443); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancingRuleImpl defineLoadBalancingRule(String name) { LoadBalancingRule lbRule = this.loadBalancingRules.get(name); if (lbRule == null) { LoadBalancingRuleInner inner = new LoadBalancingRuleInner().withName(name); return new LoadBalancingRuleImpl(inner, this); } else { return (LoadBalancingRuleImpl) lbRule; } } @Override public LoadBalancerInboundNatRuleImpl defineInboundNatRule(String name) { LoadBalancerInboundNatRule natRule = this.inboundNatRules.get(name); if (natRule == null) { InboundNatRuleInner inner = new InboundNatRuleInner().withName(name); return new LoadBalancerInboundNatRuleImpl(inner, this); } else { return (LoadBalancerInboundNatRuleImpl) natRule; } } @Override public LoadBalancerInboundNatPoolImpl defineInboundNatPool(String name) { LoadBalancerInboundNatPool natPool = this.inboundNatPools.get(name); if (natPool == null) { InboundNatPool inner = new InboundNatPool().withName(name); return new LoadBalancerInboundNatPoolImpl(inner, this); } else { return (LoadBalancerInboundNatPoolImpl) natPool; } } @Override public LoadBalancerFrontendImpl definePrivateFrontend(String name) { return defineFrontend(name); } @Override public LoadBalancerFrontendImpl definePublicFrontend(String name) { return defineFrontend(name); } LoadBalancerFrontendImpl defineFrontend(String name) { LoadBalancerFrontend frontend = this.frontends.get(name); if (frontend == null) { FrontendIPConfigurationInner inner = new FrontendIPConfigurationInner().withName(name); return new LoadBalancerFrontendImpl(inner, this); } else { return (LoadBalancerFrontendImpl) frontend; } } @Override public LoadBalancerBackendImpl defineBackend(String name) { LoadBalancerBackend backend = this.backends.get(name); if (backend == null) { BackendAddressPoolInner inner = new BackendAddressPoolInner().withName(name); return new LoadBalancerBackendImpl(inner, this); } else { return (LoadBalancerBackendImpl) backend; } } @Override public LoadBalancerImpl withSku(LoadBalancerSkuType skuType) { this.inner().withSku(skuType.sku()); return this; } @Override public LoadBalancerImpl withoutProbe(String name) { if (this.httpProbes.containsKey(name)) { this.httpProbes.remove(name); } else if (this.httpsProbes.containsKey(name)) { this.httpsProbes.remove(name); } else if (this.tcpProbes.containsKey(name)) { this.tcpProbes.remove(name); } return this; } @Override public LoadBalancerProbeImpl updateTcpProbe(String name) { return (LoadBalancerProbeImpl) this.tcpProbes.get(name); } @Override public LoadBalancerBackendImpl updateBackend(String name) { return (LoadBalancerBackendImpl) this.backends.get(name); } @Override public LoadBalancerFrontendImpl updatePublicFrontend(String name) { return (LoadBalancerFrontendImpl) this.frontends.get(name); } @Override public LoadBalancerFrontendImpl updatePrivateFrontend(String name) { return (LoadBalancerFrontendImpl) this.frontends.get(name); } @Override public LoadBalancerInboundNatRuleImpl updateInboundNatRule(String name) { return (LoadBalancerInboundNatRuleImpl) this.inboundNatRules.get(name); } @Override public LoadBalancerInboundNatPoolImpl updateInboundNatPool(String name) { return (LoadBalancerInboundNatPoolImpl) this.inboundNatPools.get(name); } @Override public LoadBalancerProbeImpl updateHttpProbe(String name) { return (LoadBalancerProbeImpl) this.httpProbes.get(name); } @Override public LoadBalancerProbeImpl updateHttpsProbe(String name) { return (LoadBalancerProbeImpl) this.httpsProbes.get(name); } @Override public LoadBalancingRuleImpl updateLoadBalancingRule(String name) { return (LoadBalancingRuleImpl) this.loadBalancingRules.get(name); } @Override public LoadBalancerImpl withoutLoadBalancingRule(String name) { this.loadBalancingRules.remove(name); return this; } @Override public LoadBalancerImpl withoutInboundNatRule(String name) { this.inboundNatRules.remove(name); return this; } @Override public LoadBalancerImpl withoutBackend(String name) { this.backends.remove(name); return this; } @Override public Update withoutInboundNatPool(String name) { this.inboundNatPools.remove(name); return this; } @Override public LoadBalancerImpl withoutFrontend(String name) { this.frontends.remove(name); return this; } @Override public Map<String, LoadBalancerBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, LoadBalancerInboundNatPool> inboundNatPools() { return Collections.unmodifiableMap(this.inboundNatPools); } @Override public LoadBalancerSkuType sku() { return LoadBalancerSkuType.fromSku(this.inner().sku()); } @Override public Map<String, LoadBalancerTcpProbe> tcpProbes() { return Collections.unmodifiableMap(this.tcpProbes); } @Override public Map<String, LoadBalancerFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, LoadBalancerPrivateFrontend> privateFrontends() { Map<String, LoadBalancerPrivateFrontend> privateFrontends = new HashMap<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (!frontend.isPublic()) { privateFrontends.put(frontend.name(), (LoadBalancerPrivateFrontend) frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public Map<String, LoadBalancerPublicFrontend> publicFrontends() { Map<String, LoadBalancerPublicFrontend> publicFrontends = new HashMap<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), (LoadBalancerPublicFrontend) frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, LoadBalancerInboundNatRule> inboundNatRules() { return Collections.unmodifiableMap(this.inboundNatRules); } @Override public Map<String, LoadBalancerHttpProbe> httpProbes() { return Collections.unmodifiableMap(this.httpProbes); } @Override public Map<String, LoadBalancerHttpProbe> httpsProbes() { return Collections.unmodifiableMap(this.httpsProbes); } @Override public Map<String, LoadBalancingRule> loadBalancingRules() { return Collections.unmodifiableMap(this.loadBalancingRules); } @Override public List<String> publicIPAddressIds() { List<String> publicIPAddressIds = new ArrayList<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { String pipId = ((LoadBalancerPublicFrontend) frontend).publicIPAddressId(); publicIPAddressIds.add(pipId); } } return Collections.unmodifiableList(publicIPAddressIds); } @Override public LoadBalancerPublicFrontend findFrontendByPublicIPAddress(String pipId) { if (pipId == null) { return null; } for (LoadBalancerPublicFrontend frontend : this.publicFrontends().values()) { if (frontend.publicIPAddressId() == null) { continue; } else if (pipId.equalsIgnoreCase(frontend.publicIPAddressId())) { return frontend; } } return null; } @Override public LoadBalancerPublicFrontend findFrontendByPublicIPAddress(PublicIPAddress publicIPAddress) { return (publicIPAddress != null) ? this.findFrontendByPublicIPAddress(publicIPAddress.id()) : null; } }
class LoadBalancerImpl extends GroupableParentResourceWithTagsImpl<LoadBalancer, LoadBalancerInner, LoadBalancerImpl, NetworkManager> implements LoadBalancer, LoadBalancer.Definition, LoadBalancer.Update { private final ClientLogger logger = new ClientLogger(getClass()); private final Map<String, String> nicsInBackends = new HashMap<>(); protected final Map<String, String> creatablePIPKeys = new HashMap<>(); private Map<String, LoadBalancerBackend> backends; private Map<String, LoadBalancerTcpProbe> tcpProbes; private Map<String, LoadBalancerHttpProbe> httpProbes; private Map<String, LoadBalancerHttpProbe> httpsProbes; private Map<String, LoadBalancingRule> loadBalancingRules; private Map<String, LoadBalancerFrontend> frontends; private Map<String, LoadBalancerInboundNatRule> inboundNatRules; private Map<String, LoadBalancerInboundNatPool> inboundNatPools; LoadBalancerImpl(String name, final LoadBalancerInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<LoadBalancer> refreshAsync() { return super .refreshAsync() .map( loadBalancer -> { LoadBalancerImpl impl = (LoadBalancerImpl) loadBalancer; impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<LoadBalancerInner> applyTagsToInnerAsync() { return this.manager().inner().loadBalancers().updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override protected void initializeChildrenFromInner() { initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeLoadBalancingRulesFromInner(); initializeInboundNatRulesFromInner(); initializeInboundNatPoolsFromInner(); } protected LoadBalancerBackendImpl ensureUniqueBackend() { String name = this.manager().getSdkContext().randomResourceName("backend", 20); LoadBalancerBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } protected SubResource ensureFrontendRef(String name) { LoadBalancerFrontendImpl frontend; if (name == null) { frontend = this.ensureUniqueFrontend(); } else { frontend = this.defineFrontend(name); frontend.attach(); } return new SubResource().setId(this.futureResourceId() + "/frontendIPConfigurations/" + frontend.name()); } protected LoadBalancerFrontendImpl ensureUniqueFrontend() { String name = this.manager().getSdkContext().randomResourceName("frontend", 20); LoadBalancerFrontendImpl frontend = this.defineFrontend(name); frontend.attach(); return frontend; } LoadBalancerPrivateFrontend findPrivateFrontendWithSubnet(String networkId, String subnetName) { if (null == networkId || null == subnetName) { return null; } else { for (LoadBalancerPrivateFrontend frontend : this.privateFrontends().values()) { if (frontend.networkId() == null || frontend.subnetName() == null) { continue; } else if (networkId.equalsIgnoreCase(frontend.networkId()) && subnetName.equalsIgnoreCase(frontend.subnetName())) { return frontend; } } return null; } } LoadBalancerPrivateFrontend ensurePrivateFrontendWithSubnet(String networkId, String subnetName) { LoadBalancerPrivateFrontend frontend = this.findPrivateFrontendWithSubnet(networkId, subnetName); if (networkId == null || subnetName == null) { return null; } else if (frontend != null) { return frontend; } else { LoadBalancerFrontendImpl fe = this.ensureUniqueFrontend().withExistingSubnet(networkId, subnetName).withPrivateIPAddressDynamic(); fe.attach(); return fe; } } LoadBalancerPublicFrontend ensurePublicFrontendWithPip(String pipId) { LoadBalancerPublicFrontend frontend = this.findFrontendByPublicIPAddress(pipId); if (pipId == null) { return null; } else if (frontend != null) { return frontend; } else { LoadBalancerFrontendImpl fe = this.ensureUniqueFrontend().withExistingPublicIPAddress(pipId); fe.attach(); return fe; } } @Override protected void beforeCreating() { if (this.creatablePIPKeys != null) { for (Entry<String, String> pipFrontendAssociation : this.creatablePIPKeys.entrySet()) { PublicIPAddress pip = this.<PublicIPAddress>taskResult(pipFrontendAssociation.getKey()); if (pip != null) { withExistingPublicIPAddress(pip.id(), pipFrontendAssociation.getValue()); } } this.creatablePIPKeys.clear(); } List<ProbeInner> innerProbes = innersFromWrappers(this.httpProbes.values()); innerProbes = innersFromWrappers(this.httpsProbes.values(), innerProbes); innerProbes = innersFromWrappers(this.tcpProbes.values(), innerProbes); if (innerProbes == null) { innerProbes = new ArrayList<>(); } this.inner().withProbes(innerProbes); List<BackendAddressPoolInner> innerBackends = innersFromWrappers(this.backends.values()); if (null == innerBackends) { innerBackends = new ArrayList<>(); } this.inner().withBackendAddressPools(innerBackends); List<FrontendIPConfigurationInner> innerFrontends = innersFromWrappers(this.frontends.values()); if (null == innerFrontends) { innerFrontends = new ArrayList<>(); } this.inner().withFrontendIPConfigurations(innerFrontends); List<InboundNatRuleInner> innerNatRules = innersFromWrappers(this.inboundNatRules.values()); if (null == innerNatRules) { innerNatRules = new ArrayList<>(); } this.inner().withInboundNatRules(innerNatRules); for (LoadBalancerInboundNatRule natRule : this.inboundNatRules.values()) { SubResource ref = natRule.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { natRule.inner().withFrontendIPConfiguration(null); } } List<InboundNatPool> innerNatPools = innersFromWrappers(this.inboundNatPools.values()); if (null == innerNatPools) { innerNatPools = new ArrayList<>(); } this.inner().withInboundNatPools(innerNatPools); for (LoadBalancerInboundNatPool natPool : this.inboundNatPools.values()) { SubResource ref = natPool.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { natPool.inner().withFrontendIPConfiguration(null); } } List<LoadBalancingRuleInner> innerRules = innersFromWrappers(this.loadBalancingRules.values()); if (innerRules == null) { innerRules = new ArrayList<>(); } this.inner().withLoadBalancingRules(innerRules); for (LoadBalancingRule lbRule : this.loadBalancingRules.values()) { SubResource ref; ref = lbRule.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withFrontendIPConfiguration(null); } ref = lbRule.inner().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withBackendAddressPool(null); } ref = lbRule.inner().probe(); if (ref != null && !this.httpProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId())) && !this.httpsProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId())) && !this.tcpProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withProbe(null); } } } protected Mono<Void> afterCreatingAsync() { if (this.nicsInBackends != null) { List<Throwable> nicExceptions = new ArrayList<>(); return Flux .fromIterable(this.nicsInBackends.entrySet()) .flatMap( nicInBackend -> { String nicId = nicInBackend.getKey(); String backendName = nicInBackend.getValue(); return this .manager() .networkInterfaces() .getByIdAsync(nicId) .flatMap( nic -> { NicIPConfiguration nicIP = nic.primaryIPConfiguration(); return nic .update() .updateIPConfiguration(nicIP.name()) .withExistingLoadBalancerBackend(this, backendName) .parent() .applyAsync(); }); }) .onErrorResume( t -> { nicExceptions.add(t); return Mono.empty(); }) .then( Mono .defer( () -> { if (!nicExceptions.isEmpty()) { return Mono.error(Exceptions.multiple(nicExceptions)); } else { this.nicsInBackends.clear(); return Mono.empty(); } })); } return Mono.empty(); } @Override protected Mono<LoadBalancerInner> createInner() { return this .manager() .inner() .loadBalancers() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override public Mono<LoadBalancer> createResourceAsync() { beforeCreating(); return createInner() .flatMap( inner -> { setInner(inner); initializeChildrenFromInner(); return afterCreatingAsync().then(this.refreshAsync()); }); } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<FrontendIPConfigurationInner> frontendsInner = this.inner().frontendIPConfigurations(); if (frontendsInner != null) { for (FrontendIPConfigurationInner frontendInner : frontendsInner) { LoadBalancerFrontendImpl frontend = new LoadBalancerFrontendImpl(frontendInner, this); this.frontends.put(frontendInner.name(), frontend); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<BackendAddressPoolInner> backendsInner = this.inner().backendAddressPools(); if (backendsInner != null) { for (BackendAddressPoolInner backendInner : backendsInner) { LoadBalancerBackendImpl backend = new LoadBalancerBackendImpl(backendInner, this); this.backends.put(backendInner.name(), backend); } } } private void initializeProbesFromInner() { this.httpProbes = new TreeMap<>(); this.httpsProbes = new TreeMap<>(); this.tcpProbes = new TreeMap<>(); if (this.inner().probes() != null) { for (ProbeInner probeInner : this.inner().probes()) { LoadBalancerProbeImpl probe = new LoadBalancerProbeImpl(probeInner, this); if (probeInner.protocol().equals(ProbeProtocol.TCP)) { this.tcpProbes.put(probeInner.name(), probe); } else if (probeInner.protocol().equals(ProbeProtocol.HTTP)) { this.httpProbes.put(probeInner.name(), probe); } else if (probeInner.protocol().equals(ProbeProtocol.HTTPS)) { this.httpsProbes.put(probeInner.name(), probe); } } } } private void initializeLoadBalancingRulesFromInner() { this.loadBalancingRules = new TreeMap<>(); List<LoadBalancingRuleInner> rulesInner = this.inner().loadBalancingRules(); if (rulesInner != null) { for (LoadBalancingRuleInner ruleInner : rulesInner) { LoadBalancingRuleImpl rule = new LoadBalancingRuleImpl(ruleInner, this); this.loadBalancingRules.put(ruleInner.name(), rule); } } } private void initializeInboundNatPoolsFromInner() { this.inboundNatPools = new TreeMap<>(); List<InboundNatPool> inners = this.inner().inboundNatPools(); if (inners != null) { for (InboundNatPool inner : inners) { LoadBalancerInboundNatPoolImpl wrapper = new LoadBalancerInboundNatPoolImpl(inner, this); this.inboundNatPools.put(wrapper.name(), wrapper); } } } private void initializeInboundNatRulesFromInner() { this.inboundNatRules = new TreeMap<>(); List<InboundNatRuleInner> rulesInner = this.inner().inboundNatRules(); if (rulesInner != null) { for (InboundNatRuleInner ruleInner : rulesInner) { LoadBalancerInboundNatRuleImpl rule = new LoadBalancerInboundNatRuleImpl(ruleInner, this); this.inboundNatRules.put(ruleInner.name(), rule); } } } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/loadBalancers/") .append(this.name()) .toString(); } LoadBalancerImpl withFrontend(LoadBalancerFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } LoadBalancerImpl withProbe(LoadBalancerProbeImpl probe) { if (probe == null) { return this; } else if (probe.protocol() == ProbeProtocol.HTTP) { httpProbes.put(probe.name(), probe); } else if (probe.protocol() == ProbeProtocol.HTTPS) { httpsProbes.put(probe.name(), probe); } else if (probe.protocol() == ProbeProtocol.TCP) { tcpProbes.put(probe.name(), probe); } return this; } LoadBalancerImpl withLoadBalancingRule(LoadBalancingRuleImpl loadBalancingRule) { if (loadBalancingRule != null) { this.loadBalancingRules.put(loadBalancingRule.name(), loadBalancingRule); } return this; } LoadBalancerImpl withInboundNatRule(LoadBalancerInboundNatRuleImpl inboundNatRule) { if (inboundNatRule != null) { this.inboundNatRules.put(inboundNatRule.name(), inboundNatRule); } return this; } LoadBalancerImpl withInboundNatPool(LoadBalancerInboundNatPoolImpl inboundNatPool) { if (inboundNatPool != null) { this.inboundNatPools.put(inboundNatPool.name(), inboundNatPool); } return this; } LoadBalancerImpl withBackend(LoadBalancerBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } LoadBalancerImpl withNewPublicIPAddress(String dnsLeafLabel, String frontendName) { PublicIPAddress.DefinitionStages.WithGroup precreatablePIP = manager().publicIPAddresses().define(dnsLeafLabel).withRegion(this.regionName()); Creatable<PublicIPAddress> creatablePip; if (super.creatableGroup == null) { creatablePip = precreatablePIP.withExistingResourceGroup(this.resourceGroupName()).withLeafDomainLabel(dnsLeafLabel); } else { creatablePip = precreatablePIP.withNewResourceGroup(super.creatableGroup).withLeafDomainLabel(dnsLeafLabel); } return withNewPublicIPAddress(creatablePip, frontendName); } LoadBalancerImpl withNewPublicIPAddress(Creatable<PublicIPAddress> creatablePip, String frontendName) { String existingPipFrontendName = this.creatablePIPKeys.get(creatablePip.key()); if (frontendName == null) { if (existingPipFrontendName != null) { frontendName = existingPipFrontendName; } else { frontendName = ensureUniqueFrontend().name(); } } if (existingPipFrontendName == null) { this.creatablePIPKeys.put(this.addDependency(creatablePip), frontendName); } else if (!existingPipFrontendName.equalsIgnoreCase(frontendName)) { throw logger.logExceptionAsError(new IllegalArgumentException( "This public IP address definition is already associated with a frontend under a different name.")); } return this; } protected LoadBalancerImpl withExistingPublicIPAddress(String resourceId, String frontendName) { if (frontendName == null) { return ensureUniqueFrontend().withExistingPublicIPAddress(resourceId).parent(); } else { return this.definePublicFrontend(frontendName).withExistingPublicIPAddress(resourceId).attach(); } } LoadBalancerImpl withExistingVirtualMachine(HasNetworkInterfaces vm, String backendName) { if (backendName != null) { this.defineBackend(backendName).attach(); if (vm.primaryNetworkInterfaceId() != null) { this.nicsInBackends.put(vm.primaryNetworkInterfaceId(), backendName.toLowerCase()); } } return this; } @Override public LoadBalancerProbeImpl defineTcpProbe(String name) { LoadBalancerProbe probe = this.tcpProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.TCP); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancerProbeImpl defineHttpProbe(String name) { LoadBalancerProbe probe = this.httpProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.HTTP).withPort(80); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancerProbeImpl defineHttpsProbe(String name) { LoadBalancerProbe probe = this.httpsProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.HTTPS).withPort(443); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancingRuleImpl defineLoadBalancingRule(String name) { LoadBalancingRule lbRule = this.loadBalancingRules.get(name); if (lbRule == null) { LoadBalancingRuleInner inner = new LoadBalancingRuleInner().withName(name); return new LoadBalancingRuleImpl(inner, this); } else { return (LoadBalancingRuleImpl) lbRule; } } @Override public LoadBalancerInboundNatRuleImpl defineInboundNatRule(String name) { LoadBalancerInboundNatRule natRule = this.inboundNatRules.get(name); if (natRule == null) { InboundNatRuleInner inner = new InboundNatRuleInner().withName(name); return new LoadBalancerInboundNatRuleImpl(inner, this); } else { return (LoadBalancerInboundNatRuleImpl) natRule; } } @Override public LoadBalancerInboundNatPoolImpl defineInboundNatPool(String name) { LoadBalancerInboundNatPool natPool = this.inboundNatPools.get(name); if (natPool == null) { InboundNatPool inner = new InboundNatPool().withName(name); return new LoadBalancerInboundNatPoolImpl(inner, this); } else { return (LoadBalancerInboundNatPoolImpl) natPool; } } @Override public LoadBalancerFrontendImpl definePrivateFrontend(String name) { return defineFrontend(name); } @Override public LoadBalancerFrontendImpl definePublicFrontend(String name) { return defineFrontend(name); } LoadBalancerFrontendImpl defineFrontend(String name) { LoadBalancerFrontend frontend = this.frontends.get(name); if (frontend == null) { FrontendIPConfigurationInner inner = new FrontendIPConfigurationInner().withName(name); return new LoadBalancerFrontendImpl(inner, this); } else { return (LoadBalancerFrontendImpl) frontend; } } @Override public LoadBalancerBackendImpl defineBackend(String name) { LoadBalancerBackend backend = this.backends.get(name); if (backend == null) { BackendAddressPoolInner inner = new BackendAddressPoolInner().withName(name); return new LoadBalancerBackendImpl(inner, this); } else { return (LoadBalancerBackendImpl) backend; } } @Override public LoadBalancerImpl withSku(LoadBalancerSkuType skuType) { this.inner().withSku(skuType.sku()); return this; } @Override public LoadBalancerImpl withoutProbe(String name) { if (this.httpProbes.containsKey(name)) { this.httpProbes.remove(name); } else if (this.httpsProbes.containsKey(name)) { this.httpsProbes.remove(name); } else if (this.tcpProbes.containsKey(name)) { this.tcpProbes.remove(name); } return this; } @Override public LoadBalancerProbeImpl updateTcpProbe(String name) { return (LoadBalancerProbeImpl) this.tcpProbes.get(name); } @Override public LoadBalancerBackendImpl updateBackend(String name) { return (LoadBalancerBackendImpl) this.backends.get(name); } @Override public LoadBalancerFrontendImpl updatePublicFrontend(String name) { return (LoadBalancerFrontendImpl) this.frontends.get(name); } @Override public LoadBalancerFrontendImpl updatePrivateFrontend(String name) { return (LoadBalancerFrontendImpl) this.frontends.get(name); } @Override public LoadBalancerInboundNatRuleImpl updateInboundNatRule(String name) { return (LoadBalancerInboundNatRuleImpl) this.inboundNatRules.get(name); } @Override public LoadBalancerInboundNatPoolImpl updateInboundNatPool(String name) { return (LoadBalancerInboundNatPoolImpl) this.inboundNatPools.get(name); } @Override public LoadBalancerProbeImpl updateHttpProbe(String name) { return (LoadBalancerProbeImpl) this.httpProbes.get(name); } @Override public LoadBalancerProbeImpl updateHttpsProbe(String name) { return (LoadBalancerProbeImpl) this.httpsProbes.get(name); } @Override public LoadBalancingRuleImpl updateLoadBalancingRule(String name) { return (LoadBalancingRuleImpl) this.loadBalancingRules.get(name); } @Override public LoadBalancerImpl withoutLoadBalancingRule(String name) { this.loadBalancingRules.remove(name); return this; } @Override public LoadBalancerImpl withoutInboundNatRule(String name) { this.inboundNatRules.remove(name); return this; } @Override public LoadBalancerImpl withoutBackend(String name) { this.backends.remove(name); return this; } @Override public Update withoutInboundNatPool(String name) { this.inboundNatPools.remove(name); return this; } @Override public LoadBalancerImpl withoutFrontend(String name) { this.frontends.remove(name); return this; } @Override public Map<String, LoadBalancerBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, LoadBalancerInboundNatPool> inboundNatPools() { return Collections.unmodifiableMap(this.inboundNatPools); } @Override public LoadBalancerSkuType sku() { return LoadBalancerSkuType.fromSku(this.inner().sku()); } @Override public Map<String, LoadBalancerTcpProbe> tcpProbes() { return Collections.unmodifiableMap(this.tcpProbes); } @Override public Map<String, LoadBalancerFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, LoadBalancerPrivateFrontend> privateFrontends() { Map<String, LoadBalancerPrivateFrontend> privateFrontends = new HashMap<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (!frontend.isPublic()) { privateFrontends.put(frontend.name(), (LoadBalancerPrivateFrontend) frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public Map<String, LoadBalancerPublicFrontend> publicFrontends() { Map<String, LoadBalancerPublicFrontend> publicFrontends = new HashMap<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), (LoadBalancerPublicFrontend) frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, LoadBalancerInboundNatRule> inboundNatRules() { return Collections.unmodifiableMap(this.inboundNatRules); } @Override public Map<String, LoadBalancerHttpProbe> httpProbes() { return Collections.unmodifiableMap(this.httpProbes); } @Override public Map<String, LoadBalancerHttpProbe> httpsProbes() { return Collections.unmodifiableMap(this.httpsProbes); } @Override public Map<String, LoadBalancingRule> loadBalancingRules() { return Collections.unmodifiableMap(this.loadBalancingRules); } @Override public List<String> publicIPAddressIds() { List<String> publicIPAddressIds = new ArrayList<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { String pipId = ((LoadBalancerPublicFrontend) frontend).publicIPAddressId(); publicIPAddressIds.add(pipId); } } return Collections.unmodifiableList(publicIPAddressIds); } @Override public LoadBalancerPublicFrontend findFrontendByPublicIPAddress(String pipId) { if (pipId == null) { return null; } for (LoadBalancerPublicFrontend frontend : this.publicFrontends().values()) { if (frontend.publicIPAddressId() == null) { continue; } else if (pipId.equalsIgnoreCase(frontend.publicIPAddressId())) { return frontend; } } return null; } @Override public LoadBalancerPublicFrontend findFrontendByPublicIPAddress(PublicIPAddress publicIPAddress) { return (publicIPAddress != null) ? this.findFrontendByPublicIPAddress(publicIPAddress.id()) : null; } }
Done
protected Mono<LoadBalancerInner> getInnerAsync() { return this .manager() .inner() .loadBalancers() .getByResourceGroupAsync(this.resourceGroupName(), this.name(), null); }
return this
protected Mono<LoadBalancerInner> getInnerAsync() { return this .manager() .inner() .loadBalancers() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); }
class LoadBalancerImpl extends GroupableParentResourceWithTagsImpl<LoadBalancer, LoadBalancerInner, LoadBalancerImpl, NetworkManager> implements LoadBalancer, LoadBalancer.Definition, LoadBalancer.Update { private final ClientLogger logger = new ClientLogger(getClass()); private final Map<String, String> nicsInBackends = new HashMap<>(); protected final Map<String, String> creatablePIPKeys = new HashMap<>(); private Map<String, LoadBalancerBackend> backends; private Map<String, LoadBalancerTcpProbe> tcpProbes; private Map<String, LoadBalancerHttpProbe> httpProbes; private Map<String, LoadBalancerHttpProbe> httpsProbes; private Map<String, LoadBalancingRule> loadBalancingRules; private Map<String, LoadBalancerFrontend> frontends; private Map<String, LoadBalancerInboundNatRule> inboundNatRules; private Map<String, LoadBalancerInboundNatPool> inboundNatPools; LoadBalancerImpl(String name, final LoadBalancerInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<LoadBalancer> refreshAsync() { return super .refreshAsync() .map( loadBalancer -> { LoadBalancerImpl impl = (LoadBalancerImpl) loadBalancer; impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<LoadBalancerInner> applyTagsToInnerAsync() { return this.manager().inner().loadBalancers().updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override protected void initializeChildrenFromInner() { initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeLoadBalancingRulesFromInner(); initializeInboundNatRulesFromInner(); initializeInboundNatPoolsFromInner(); } protected LoadBalancerBackendImpl ensureUniqueBackend() { String name = this.manager().getSdkContext().randomResourceName("backend", 20); LoadBalancerBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } protected SubResource ensureFrontendRef(String name) { LoadBalancerFrontendImpl frontend; if (name == null) { frontend = this.ensureUniqueFrontend(); } else { frontend = this.defineFrontend(name); frontend.attach(); } return new SubResource().setId(this.futureResourceId() + "/frontendIPConfigurations/" + frontend.name()); } protected LoadBalancerFrontendImpl ensureUniqueFrontend() { String name = this.manager().getSdkContext().randomResourceName("frontend", 20); LoadBalancerFrontendImpl frontend = this.defineFrontend(name); frontend.attach(); return frontend; } LoadBalancerPrivateFrontend findPrivateFrontendWithSubnet(String networkId, String subnetName) { if (null == networkId || null == subnetName) { return null; } else { for (LoadBalancerPrivateFrontend frontend : this.privateFrontends().values()) { if (frontend.networkId() == null || frontend.subnetName() == null) { continue; } else if (networkId.equalsIgnoreCase(frontend.networkId()) && subnetName.equalsIgnoreCase(frontend.subnetName())) { return frontend; } } return null; } } LoadBalancerPrivateFrontend ensurePrivateFrontendWithSubnet(String networkId, String subnetName) { LoadBalancerPrivateFrontend frontend = this.findPrivateFrontendWithSubnet(networkId, subnetName); if (networkId == null || subnetName == null) { return null; } else if (frontend != null) { return frontend; } else { LoadBalancerFrontendImpl fe = this.ensureUniqueFrontend().withExistingSubnet(networkId, subnetName).withPrivateIPAddressDynamic(); fe.attach(); return fe; } } LoadBalancerPublicFrontend ensurePublicFrontendWithPip(String pipId) { LoadBalancerPublicFrontend frontend = this.findFrontendByPublicIPAddress(pipId); if (pipId == null) { return null; } else if (frontend != null) { return frontend; } else { LoadBalancerFrontendImpl fe = this.ensureUniqueFrontend().withExistingPublicIPAddress(pipId); fe.attach(); return fe; } } @Override protected void beforeCreating() { if (this.creatablePIPKeys != null) { for (Entry<String, String> pipFrontendAssociation : this.creatablePIPKeys.entrySet()) { PublicIPAddress pip = this.<PublicIPAddress>taskResult(pipFrontendAssociation.getKey()); if (pip != null) { withExistingPublicIPAddress(pip.id(), pipFrontendAssociation.getValue()); } } this.creatablePIPKeys.clear(); } List<ProbeInner> innerProbes = innersFromWrappers(this.httpProbes.values()); innerProbes = innersFromWrappers(this.httpsProbes.values(), innerProbes); innerProbes = innersFromWrappers(this.tcpProbes.values(), innerProbes); if (innerProbes == null) { innerProbes = new ArrayList<>(); } this.inner().withProbes(innerProbes); List<BackendAddressPoolInner> innerBackends = innersFromWrappers(this.backends.values()); if (null == innerBackends) { innerBackends = new ArrayList<>(); } this.inner().withBackendAddressPools(innerBackends); List<FrontendIPConfigurationInner> innerFrontends = innersFromWrappers(this.frontends.values()); if (null == innerFrontends) { innerFrontends = new ArrayList<>(); } this.inner().withFrontendIPConfigurations(innerFrontends); List<InboundNatRuleInner> innerNatRules = innersFromWrappers(this.inboundNatRules.values()); if (null == innerNatRules) { innerNatRules = new ArrayList<>(); } this.inner().withInboundNatRules(innerNatRules); for (LoadBalancerInboundNatRule natRule : this.inboundNatRules.values()) { SubResource ref = natRule.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { natRule.inner().withFrontendIPConfiguration(null); } } List<InboundNatPool> innerNatPools = innersFromWrappers(this.inboundNatPools.values()); if (null == innerNatPools) { innerNatPools = new ArrayList<>(); } this.inner().withInboundNatPools(innerNatPools); for (LoadBalancerInboundNatPool natPool : this.inboundNatPools.values()) { SubResource ref = natPool.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { natPool.inner().withFrontendIPConfiguration(null); } } List<LoadBalancingRuleInner> innerRules = innersFromWrappers(this.loadBalancingRules.values()); if (innerRules == null) { innerRules = new ArrayList<>(); } this.inner().withLoadBalancingRules(innerRules); for (LoadBalancingRule lbRule : this.loadBalancingRules.values()) { SubResource ref; ref = lbRule.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withFrontendIPConfiguration(null); } ref = lbRule.inner().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withBackendAddressPool(null); } ref = lbRule.inner().probe(); if (ref != null && !this.httpProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId())) && !this.httpsProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId())) && !this.tcpProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withProbe(null); } } } protected Mono<Void> afterCreatingAsync() { if (this.nicsInBackends != null) { List<Throwable> nicExceptions = new ArrayList<>(); return Flux .fromIterable(this.nicsInBackends.entrySet()) .flatMap( nicInBackend -> { String nicId = nicInBackend.getKey(); String backendName = nicInBackend.getValue(); return this .manager() .networkInterfaces() .getByIdAsync(nicId) .flatMap( nic -> { NicIPConfiguration nicIP = nic.primaryIPConfiguration(); return nic .update() .updateIPConfiguration(nicIP.name()) .withExistingLoadBalancerBackend(this, backendName) .parent() .applyAsync(); }); }) .onErrorResume( t -> { nicExceptions.add(t); return Mono.empty(); }) .then( Mono .defer( () -> { if (!nicExceptions.isEmpty()) { return Mono.error(Exceptions.multiple(nicExceptions)); } else { this.nicsInBackends.clear(); return Mono.empty(); } })); } return Mono.empty(); } @Override protected Mono<LoadBalancerInner> createInner() { return this .manager() .inner() .loadBalancers() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override public Mono<LoadBalancer> createResourceAsync() { beforeCreating(); return createInner() .flatMap( inner -> { setInner(inner); initializeChildrenFromInner(); return afterCreatingAsync().then(this.refreshAsync()); }); } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<FrontendIPConfigurationInner> frontendsInner = this.inner().frontendIPConfigurations(); if (frontendsInner != null) { for (FrontendIPConfigurationInner frontendInner : frontendsInner) { LoadBalancerFrontendImpl frontend = new LoadBalancerFrontendImpl(frontendInner, this); this.frontends.put(frontendInner.name(), frontend); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<BackendAddressPoolInner> backendsInner = this.inner().backendAddressPools(); if (backendsInner != null) { for (BackendAddressPoolInner backendInner : backendsInner) { LoadBalancerBackendImpl backend = new LoadBalancerBackendImpl(backendInner, this); this.backends.put(backendInner.name(), backend); } } } private void initializeProbesFromInner() { this.httpProbes = new TreeMap<>(); this.httpsProbes = new TreeMap<>(); this.tcpProbes = new TreeMap<>(); if (this.inner().probes() != null) { for (ProbeInner probeInner : this.inner().probes()) { LoadBalancerProbeImpl probe = new LoadBalancerProbeImpl(probeInner, this); if (probeInner.protocol().equals(ProbeProtocol.TCP)) { this.tcpProbes.put(probeInner.name(), probe); } else if (probeInner.protocol().equals(ProbeProtocol.HTTP)) { this.httpProbes.put(probeInner.name(), probe); } else if (probeInner.protocol().equals(ProbeProtocol.HTTPS)) { this.httpsProbes.put(probeInner.name(), probe); } } } } private void initializeLoadBalancingRulesFromInner() { this.loadBalancingRules = new TreeMap<>(); List<LoadBalancingRuleInner> rulesInner = this.inner().loadBalancingRules(); if (rulesInner != null) { for (LoadBalancingRuleInner ruleInner : rulesInner) { LoadBalancingRuleImpl rule = new LoadBalancingRuleImpl(ruleInner, this); this.loadBalancingRules.put(ruleInner.name(), rule); } } } private void initializeInboundNatPoolsFromInner() { this.inboundNatPools = new TreeMap<>(); List<InboundNatPool> inners = this.inner().inboundNatPools(); if (inners != null) { for (InboundNatPool inner : inners) { LoadBalancerInboundNatPoolImpl wrapper = new LoadBalancerInboundNatPoolImpl(inner, this); this.inboundNatPools.put(wrapper.name(), wrapper); } } } private void initializeInboundNatRulesFromInner() { this.inboundNatRules = new TreeMap<>(); List<InboundNatRuleInner> rulesInner = this.inner().inboundNatRules(); if (rulesInner != null) { for (InboundNatRuleInner ruleInner : rulesInner) { LoadBalancerInboundNatRuleImpl rule = new LoadBalancerInboundNatRuleImpl(ruleInner, this); this.inboundNatRules.put(ruleInner.name(), rule); } } } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/loadBalancers/") .append(this.name()) .toString(); } LoadBalancerImpl withFrontend(LoadBalancerFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } LoadBalancerImpl withProbe(LoadBalancerProbeImpl probe) { if (probe == null) { return this; } else if (probe.protocol() == ProbeProtocol.HTTP) { httpProbes.put(probe.name(), probe); } else if (probe.protocol() == ProbeProtocol.HTTPS) { httpsProbes.put(probe.name(), probe); } else if (probe.protocol() == ProbeProtocol.TCP) { tcpProbes.put(probe.name(), probe); } return this; } LoadBalancerImpl withLoadBalancingRule(LoadBalancingRuleImpl loadBalancingRule) { if (loadBalancingRule != null) { this.loadBalancingRules.put(loadBalancingRule.name(), loadBalancingRule); } return this; } LoadBalancerImpl withInboundNatRule(LoadBalancerInboundNatRuleImpl inboundNatRule) { if (inboundNatRule != null) { this.inboundNatRules.put(inboundNatRule.name(), inboundNatRule); } return this; } LoadBalancerImpl withInboundNatPool(LoadBalancerInboundNatPoolImpl inboundNatPool) { if (inboundNatPool != null) { this.inboundNatPools.put(inboundNatPool.name(), inboundNatPool); } return this; } LoadBalancerImpl withBackend(LoadBalancerBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } LoadBalancerImpl withNewPublicIPAddress(String dnsLeafLabel, String frontendName) { PublicIPAddress.DefinitionStages.WithGroup precreatablePIP = manager().publicIPAddresses().define(dnsLeafLabel).withRegion(this.regionName()); Creatable<PublicIPAddress> creatablePip; if (super.creatableGroup == null) { creatablePip = precreatablePIP.withExistingResourceGroup(this.resourceGroupName()).withLeafDomainLabel(dnsLeafLabel); } else { creatablePip = precreatablePIP.withNewResourceGroup(super.creatableGroup).withLeafDomainLabel(dnsLeafLabel); } return withNewPublicIPAddress(creatablePip, frontendName); } LoadBalancerImpl withNewPublicIPAddress(Creatable<PublicIPAddress> creatablePip, String frontendName) { String existingPipFrontendName = this.creatablePIPKeys.get(creatablePip.key()); if (frontendName == null) { if (existingPipFrontendName != null) { frontendName = existingPipFrontendName; } else { frontendName = ensureUniqueFrontend().name(); } } if (existingPipFrontendName == null) { this.creatablePIPKeys.put(this.addDependency(creatablePip), frontendName); } else if (!existingPipFrontendName.equalsIgnoreCase(frontendName)) { throw logger.logExceptionAsError(new IllegalArgumentException( "This public IP address definition is already associated with a frontend under a different name.")); } return this; } protected LoadBalancerImpl withExistingPublicIPAddress(String resourceId, String frontendName) { if (frontendName == null) { return ensureUniqueFrontend().withExistingPublicIPAddress(resourceId).parent(); } else { return this.definePublicFrontend(frontendName).withExistingPublicIPAddress(resourceId).attach(); } } LoadBalancerImpl withExistingVirtualMachine(HasNetworkInterfaces vm, String backendName) { if (backendName != null) { this.defineBackend(backendName).attach(); if (vm.primaryNetworkInterfaceId() != null) { this.nicsInBackends.put(vm.primaryNetworkInterfaceId(), backendName.toLowerCase()); } } return this; } @Override public LoadBalancerProbeImpl defineTcpProbe(String name) { LoadBalancerProbe probe = this.tcpProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.TCP); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancerProbeImpl defineHttpProbe(String name) { LoadBalancerProbe probe = this.httpProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.HTTP).withPort(80); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancerProbeImpl defineHttpsProbe(String name) { LoadBalancerProbe probe = this.httpsProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.HTTPS).withPort(443); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancingRuleImpl defineLoadBalancingRule(String name) { LoadBalancingRule lbRule = this.loadBalancingRules.get(name); if (lbRule == null) { LoadBalancingRuleInner inner = new LoadBalancingRuleInner().withName(name); return new LoadBalancingRuleImpl(inner, this); } else { return (LoadBalancingRuleImpl) lbRule; } } @Override public LoadBalancerInboundNatRuleImpl defineInboundNatRule(String name) { LoadBalancerInboundNatRule natRule = this.inboundNatRules.get(name); if (natRule == null) { InboundNatRuleInner inner = new InboundNatRuleInner().withName(name); return new LoadBalancerInboundNatRuleImpl(inner, this); } else { return (LoadBalancerInboundNatRuleImpl) natRule; } } @Override public LoadBalancerInboundNatPoolImpl defineInboundNatPool(String name) { LoadBalancerInboundNatPool natPool = this.inboundNatPools.get(name); if (natPool == null) { InboundNatPool inner = new InboundNatPool().withName(name); return new LoadBalancerInboundNatPoolImpl(inner, this); } else { return (LoadBalancerInboundNatPoolImpl) natPool; } } @Override public LoadBalancerFrontendImpl definePrivateFrontend(String name) { return defineFrontend(name); } @Override public LoadBalancerFrontendImpl definePublicFrontend(String name) { return defineFrontend(name); } LoadBalancerFrontendImpl defineFrontend(String name) { LoadBalancerFrontend frontend = this.frontends.get(name); if (frontend == null) { FrontendIPConfigurationInner inner = new FrontendIPConfigurationInner().withName(name); return new LoadBalancerFrontendImpl(inner, this); } else { return (LoadBalancerFrontendImpl) frontend; } } @Override public LoadBalancerBackendImpl defineBackend(String name) { LoadBalancerBackend backend = this.backends.get(name); if (backend == null) { BackendAddressPoolInner inner = new BackendAddressPoolInner().withName(name); return new LoadBalancerBackendImpl(inner, this); } else { return (LoadBalancerBackendImpl) backend; } } @Override public LoadBalancerImpl withSku(LoadBalancerSkuType skuType) { this.inner().withSku(skuType.sku()); return this; } @Override public LoadBalancerImpl withoutProbe(String name) { if (this.httpProbes.containsKey(name)) { this.httpProbes.remove(name); } else if (this.httpsProbes.containsKey(name)) { this.httpsProbes.remove(name); } else if (this.tcpProbes.containsKey(name)) { this.tcpProbes.remove(name); } return this; } @Override public LoadBalancerProbeImpl updateTcpProbe(String name) { return (LoadBalancerProbeImpl) this.tcpProbes.get(name); } @Override public LoadBalancerBackendImpl updateBackend(String name) { return (LoadBalancerBackendImpl) this.backends.get(name); } @Override public LoadBalancerFrontendImpl updatePublicFrontend(String name) { return (LoadBalancerFrontendImpl) this.frontends.get(name); } @Override public LoadBalancerFrontendImpl updatePrivateFrontend(String name) { return (LoadBalancerFrontendImpl) this.frontends.get(name); } @Override public LoadBalancerInboundNatRuleImpl updateInboundNatRule(String name) { return (LoadBalancerInboundNatRuleImpl) this.inboundNatRules.get(name); } @Override public LoadBalancerInboundNatPoolImpl updateInboundNatPool(String name) { return (LoadBalancerInboundNatPoolImpl) this.inboundNatPools.get(name); } @Override public LoadBalancerProbeImpl updateHttpProbe(String name) { return (LoadBalancerProbeImpl) this.httpProbes.get(name); } @Override public LoadBalancerProbeImpl updateHttpsProbe(String name) { return (LoadBalancerProbeImpl) this.httpsProbes.get(name); } @Override public LoadBalancingRuleImpl updateLoadBalancingRule(String name) { return (LoadBalancingRuleImpl) this.loadBalancingRules.get(name); } @Override public LoadBalancerImpl withoutLoadBalancingRule(String name) { this.loadBalancingRules.remove(name); return this; } @Override public LoadBalancerImpl withoutInboundNatRule(String name) { this.inboundNatRules.remove(name); return this; } @Override public LoadBalancerImpl withoutBackend(String name) { this.backends.remove(name); return this; } @Override public Update withoutInboundNatPool(String name) { this.inboundNatPools.remove(name); return this; } @Override public LoadBalancerImpl withoutFrontend(String name) { this.frontends.remove(name); return this; } @Override public Map<String, LoadBalancerBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, LoadBalancerInboundNatPool> inboundNatPools() { return Collections.unmodifiableMap(this.inboundNatPools); } @Override public LoadBalancerSkuType sku() { return LoadBalancerSkuType.fromSku(this.inner().sku()); } @Override public Map<String, LoadBalancerTcpProbe> tcpProbes() { return Collections.unmodifiableMap(this.tcpProbes); } @Override public Map<String, LoadBalancerFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, LoadBalancerPrivateFrontend> privateFrontends() { Map<String, LoadBalancerPrivateFrontend> privateFrontends = new HashMap<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (!frontend.isPublic()) { privateFrontends.put(frontend.name(), (LoadBalancerPrivateFrontend) frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public Map<String, LoadBalancerPublicFrontend> publicFrontends() { Map<String, LoadBalancerPublicFrontend> publicFrontends = new HashMap<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), (LoadBalancerPublicFrontend) frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, LoadBalancerInboundNatRule> inboundNatRules() { return Collections.unmodifiableMap(this.inboundNatRules); } @Override public Map<String, LoadBalancerHttpProbe> httpProbes() { return Collections.unmodifiableMap(this.httpProbes); } @Override public Map<String, LoadBalancerHttpProbe> httpsProbes() { return Collections.unmodifiableMap(this.httpsProbes); } @Override public Map<String, LoadBalancingRule> loadBalancingRules() { return Collections.unmodifiableMap(this.loadBalancingRules); } @Override public List<String> publicIPAddressIds() { List<String> publicIPAddressIds = new ArrayList<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { String pipId = ((LoadBalancerPublicFrontend) frontend).publicIPAddressId(); publicIPAddressIds.add(pipId); } } return Collections.unmodifiableList(publicIPAddressIds); } @Override public LoadBalancerPublicFrontend findFrontendByPublicIPAddress(String pipId) { if (pipId == null) { return null; } for (LoadBalancerPublicFrontend frontend : this.publicFrontends().values()) { if (frontend.publicIPAddressId() == null) { continue; } else if (pipId.equalsIgnoreCase(frontend.publicIPAddressId())) { return frontend; } } return null; } @Override public LoadBalancerPublicFrontend findFrontendByPublicIPAddress(PublicIPAddress publicIPAddress) { return (publicIPAddress != null) ? this.findFrontendByPublicIPAddress(publicIPAddress.id()) : null; } }
class LoadBalancerImpl extends GroupableParentResourceWithTagsImpl<LoadBalancer, LoadBalancerInner, LoadBalancerImpl, NetworkManager> implements LoadBalancer, LoadBalancer.Definition, LoadBalancer.Update { private final ClientLogger logger = new ClientLogger(getClass()); private final Map<String, String> nicsInBackends = new HashMap<>(); protected final Map<String, String> creatablePIPKeys = new HashMap<>(); private Map<String, LoadBalancerBackend> backends; private Map<String, LoadBalancerTcpProbe> tcpProbes; private Map<String, LoadBalancerHttpProbe> httpProbes; private Map<String, LoadBalancerHttpProbe> httpsProbes; private Map<String, LoadBalancingRule> loadBalancingRules; private Map<String, LoadBalancerFrontend> frontends; private Map<String, LoadBalancerInboundNatRule> inboundNatRules; private Map<String, LoadBalancerInboundNatPool> inboundNatPools; LoadBalancerImpl(String name, final LoadBalancerInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override public Mono<LoadBalancer> refreshAsync() { return super .refreshAsync() .map( loadBalancer -> { LoadBalancerImpl impl = (LoadBalancerImpl) loadBalancer; impl.initializeChildrenFromInner(); return impl; }); } @Override @Override protected Mono<LoadBalancerInner> applyTagsToInnerAsync() { return this.manager().inner().loadBalancers().updateTagsAsync(resourceGroupName(), name(), inner().getTags()); } @Override protected void initializeChildrenFromInner() { initializeFrontendsFromInner(); initializeProbesFromInner(); initializeBackendsFromInner(); initializeLoadBalancingRulesFromInner(); initializeInboundNatRulesFromInner(); initializeInboundNatPoolsFromInner(); } protected LoadBalancerBackendImpl ensureUniqueBackend() { String name = this.manager().getSdkContext().randomResourceName("backend", 20); LoadBalancerBackendImpl backend = this.defineBackend(name); backend.attach(); return backend; } protected SubResource ensureFrontendRef(String name) { LoadBalancerFrontendImpl frontend; if (name == null) { frontend = this.ensureUniqueFrontend(); } else { frontend = this.defineFrontend(name); frontend.attach(); } return new SubResource().setId(this.futureResourceId() + "/frontendIPConfigurations/" + frontend.name()); } protected LoadBalancerFrontendImpl ensureUniqueFrontend() { String name = this.manager().getSdkContext().randomResourceName("frontend", 20); LoadBalancerFrontendImpl frontend = this.defineFrontend(name); frontend.attach(); return frontend; } LoadBalancerPrivateFrontend findPrivateFrontendWithSubnet(String networkId, String subnetName) { if (null == networkId || null == subnetName) { return null; } else { for (LoadBalancerPrivateFrontend frontend : this.privateFrontends().values()) { if (frontend.networkId() == null || frontend.subnetName() == null) { continue; } else if (networkId.equalsIgnoreCase(frontend.networkId()) && subnetName.equalsIgnoreCase(frontend.subnetName())) { return frontend; } } return null; } } LoadBalancerPrivateFrontend ensurePrivateFrontendWithSubnet(String networkId, String subnetName) { LoadBalancerPrivateFrontend frontend = this.findPrivateFrontendWithSubnet(networkId, subnetName); if (networkId == null || subnetName == null) { return null; } else if (frontend != null) { return frontend; } else { LoadBalancerFrontendImpl fe = this.ensureUniqueFrontend().withExistingSubnet(networkId, subnetName).withPrivateIPAddressDynamic(); fe.attach(); return fe; } } LoadBalancerPublicFrontend ensurePublicFrontendWithPip(String pipId) { LoadBalancerPublicFrontend frontend = this.findFrontendByPublicIPAddress(pipId); if (pipId == null) { return null; } else if (frontend != null) { return frontend; } else { LoadBalancerFrontendImpl fe = this.ensureUniqueFrontend().withExistingPublicIPAddress(pipId); fe.attach(); return fe; } } @Override protected void beforeCreating() { if (this.creatablePIPKeys != null) { for (Entry<String, String> pipFrontendAssociation : this.creatablePIPKeys.entrySet()) { PublicIPAddress pip = this.<PublicIPAddress>taskResult(pipFrontendAssociation.getKey()); if (pip != null) { withExistingPublicIPAddress(pip.id(), pipFrontendAssociation.getValue()); } } this.creatablePIPKeys.clear(); } List<ProbeInner> innerProbes = innersFromWrappers(this.httpProbes.values()); innerProbes = innersFromWrappers(this.httpsProbes.values(), innerProbes); innerProbes = innersFromWrappers(this.tcpProbes.values(), innerProbes); if (innerProbes == null) { innerProbes = new ArrayList<>(); } this.inner().withProbes(innerProbes); List<BackendAddressPoolInner> innerBackends = innersFromWrappers(this.backends.values()); if (null == innerBackends) { innerBackends = new ArrayList<>(); } this.inner().withBackendAddressPools(innerBackends); List<FrontendIPConfigurationInner> innerFrontends = innersFromWrappers(this.frontends.values()); if (null == innerFrontends) { innerFrontends = new ArrayList<>(); } this.inner().withFrontendIPConfigurations(innerFrontends); List<InboundNatRuleInner> innerNatRules = innersFromWrappers(this.inboundNatRules.values()); if (null == innerNatRules) { innerNatRules = new ArrayList<>(); } this.inner().withInboundNatRules(innerNatRules); for (LoadBalancerInboundNatRule natRule : this.inboundNatRules.values()) { SubResource ref = natRule.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { natRule.inner().withFrontendIPConfiguration(null); } } List<InboundNatPool> innerNatPools = innersFromWrappers(this.inboundNatPools.values()); if (null == innerNatPools) { innerNatPools = new ArrayList<>(); } this.inner().withInboundNatPools(innerNatPools); for (LoadBalancerInboundNatPool natPool : this.inboundNatPools.values()) { SubResource ref = natPool.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { natPool.inner().withFrontendIPConfiguration(null); } } List<LoadBalancingRuleInner> innerRules = innersFromWrappers(this.loadBalancingRules.values()); if (innerRules == null) { innerRules = new ArrayList<>(); } this.inner().withLoadBalancingRules(innerRules); for (LoadBalancingRule lbRule : this.loadBalancingRules.values()) { SubResource ref; ref = lbRule.inner().frontendIPConfiguration(); if (ref != null && !this.frontends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withFrontendIPConfiguration(null); } ref = lbRule.inner().backendAddressPool(); if (ref != null && !this.backends().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withBackendAddressPool(null); } ref = lbRule.inner().probe(); if (ref != null && !this.httpProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId())) && !this.httpsProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId())) && !this.tcpProbes().containsKey(ResourceUtils.nameFromResourceId(ref.getId()))) { lbRule.inner().withProbe(null); } } } protected Mono<Void> afterCreatingAsync() { if (this.nicsInBackends != null) { List<Throwable> nicExceptions = new ArrayList<>(); return Flux .fromIterable(this.nicsInBackends.entrySet()) .flatMap( nicInBackend -> { String nicId = nicInBackend.getKey(); String backendName = nicInBackend.getValue(); return this .manager() .networkInterfaces() .getByIdAsync(nicId) .flatMap( nic -> { NicIPConfiguration nicIP = nic.primaryIPConfiguration(); return nic .update() .updateIPConfiguration(nicIP.name()) .withExistingLoadBalancerBackend(this, backendName) .parent() .applyAsync(); }); }) .onErrorResume( t -> { nicExceptions.add(t); return Mono.empty(); }) .then( Mono .defer( () -> { if (!nicExceptions.isEmpty()) { return Mono.error(Exceptions.multiple(nicExceptions)); } else { this.nicsInBackends.clear(); return Mono.empty(); } })); } return Mono.empty(); } @Override protected Mono<LoadBalancerInner> createInner() { return this .manager() .inner() .loadBalancers() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()); } @Override public Mono<LoadBalancer> createResourceAsync() { beforeCreating(); return createInner() .flatMap( inner -> { setInner(inner); initializeChildrenFromInner(); return afterCreatingAsync().then(this.refreshAsync()); }); } private void initializeFrontendsFromInner() { this.frontends = new TreeMap<>(); List<FrontendIPConfigurationInner> frontendsInner = this.inner().frontendIPConfigurations(); if (frontendsInner != null) { for (FrontendIPConfigurationInner frontendInner : frontendsInner) { LoadBalancerFrontendImpl frontend = new LoadBalancerFrontendImpl(frontendInner, this); this.frontends.put(frontendInner.name(), frontend); } } } private void initializeBackendsFromInner() { this.backends = new TreeMap<>(); List<BackendAddressPoolInner> backendsInner = this.inner().backendAddressPools(); if (backendsInner != null) { for (BackendAddressPoolInner backendInner : backendsInner) { LoadBalancerBackendImpl backend = new LoadBalancerBackendImpl(backendInner, this); this.backends.put(backendInner.name(), backend); } } } private void initializeProbesFromInner() { this.httpProbes = new TreeMap<>(); this.httpsProbes = new TreeMap<>(); this.tcpProbes = new TreeMap<>(); if (this.inner().probes() != null) { for (ProbeInner probeInner : this.inner().probes()) { LoadBalancerProbeImpl probe = new LoadBalancerProbeImpl(probeInner, this); if (probeInner.protocol().equals(ProbeProtocol.TCP)) { this.tcpProbes.put(probeInner.name(), probe); } else if (probeInner.protocol().equals(ProbeProtocol.HTTP)) { this.httpProbes.put(probeInner.name(), probe); } else if (probeInner.protocol().equals(ProbeProtocol.HTTPS)) { this.httpsProbes.put(probeInner.name(), probe); } } } } private void initializeLoadBalancingRulesFromInner() { this.loadBalancingRules = new TreeMap<>(); List<LoadBalancingRuleInner> rulesInner = this.inner().loadBalancingRules(); if (rulesInner != null) { for (LoadBalancingRuleInner ruleInner : rulesInner) { LoadBalancingRuleImpl rule = new LoadBalancingRuleImpl(ruleInner, this); this.loadBalancingRules.put(ruleInner.name(), rule); } } } private void initializeInboundNatPoolsFromInner() { this.inboundNatPools = new TreeMap<>(); List<InboundNatPool> inners = this.inner().inboundNatPools(); if (inners != null) { for (InboundNatPool inner : inners) { LoadBalancerInboundNatPoolImpl wrapper = new LoadBalancerInboundNatPoolImpl(inner, this); this.inboundNatPools.put(wrapper.name(), wrapper); } } } private void initializeInboundNatRulesFromInner() { this.inboundNatRules = new TreeMap<>(); List<InboundNatRuleInner> rulesInner = this.inner().inboundNatRules(); if (rulesInner != null) { for (InboundNatRuleInner ruleInner : rulesInner) { LoadBalancerInboundNatRuleImpl rule = new LoadBalancerInboundNatRuleImpl(ruleInner, this); this.inboundNatRules.put(ruleInner.name(), rule); } } } String futureResourceId() { return new StringBuilder() .append(super.resourceIdBase()) .append("/providers/Microsoft.Network/loadBalancers/") .append(this.name()) .toString(); } LoadBalancerImpl withFrontend(LoadBalancerFrontendImpl frontend) { if (frontend != null) { this.frontends.put(frontend.name(), frontend); } return this; } LoadBalancerImpl withProbe(LoadBalancerProbeImpl probe) { if (probe == null) { return this; } else if (probe.protocol() == ProbeProtocol.HTTP) { httpProbes.put(probe.name(), probe); } else if (probe.protocol() == ProbeProtocol.HTTPS) { httpsProbes.put(probe.name(), probe); } else if (probe.protocol() == ProbeProtocol.TCP) { tcpProbes.put(probe.name(), probe); } return this; } LoadBalancerImpl withLoadBalancingRule(LoadBalancingRuleImpl loadBalancingRule) { if (loadBalancingRule != null) { this.loadBalancingRules.put(loadBalancingRule.name(), loadBalancingRule); } return this; } LoadBalancerImpl withInboundNatRule(LoadBalancerInboundNatRuleImpl inboundNatRule) { if (inboundNatRule != null) { this.inboundNatRules.put(inboundNatRule.name(), inboundNatRule); } return this; } LoadBalancerImpl withInboundNatPool(LoadBalancerInboundNatPoolImpl inboundNatPool) { if (inboundNatPool != null) { this.inboundNatPools.put(inboundNatPool.name(), inboundNatPool); } return this; } LoadBalancerImpl withBackend(LoadBalancerBackendImpl backend) { if (backend != null) { this.backends.put(backend.name(), backend); } return this; } LoadBalancerImpl withNewPublicIPAddress(String dnsLeafLabel, String frontendName) { PublicIPAddress.DefinitionStages.WithGroup precreatablePIP = manager().publicIPAddresses().define(dnsLeafLabel).withRegion(this.regionName()); Creatable<PublicIPAddress> creatablePip; if (super.creatableGroup == null) { creatablePip = precreatablePIP.withExistingResourceGroup(this.resourceGroupName()).withLeafDomainLabel(dnsLeafLabel); } else { creatablePip = precreatablePIP.withNewResourceGroup(super.creatableGroup).withLeafDomainLabel(dnsLeafLabel); } return withNewPublicIPAddress(creatablePip, frontendName); } LoadBalancerImpl withNewPublicIPAddress(Creatable<PublicIPAddress> creatablePip, String frontendName) { String existingPipFrontendName = this.creatablePIPKeys.get(creatablePip.key()); if (frontendName == null) { if (existingPipFrontendName != null) { frontendName = existingPipFrontendName; } else { frontendName = ensureUniqueFrontend().name(); } } if (existingPipFrontendName == null) { this.creatablePIPKeys.put(this.addDependency(creatablePip), frontendName); } else if (!existingPipFrontendName.equalsIgnoreCase(frontendName)) { throw logger.logExceptionAsError(new IllegalArgumentException( "This public IP address definition is already associated with a frontend under a different name.")); } return this; } protected LoadBalancerImpl withExistingPublicIPAddress(String resourceId, String frontendName) { if (frontendName == null) { return ensureUniqueFrontend().withExistingPublicIPAddress(resourceId).parent(); } else { return this.definePublicFrontend(frontendName).withExistingPublicIPAddress(resourceId).attach(); } } LoadBalancerImpl withExistingVirtualMachine(HasNetworkInterfaces vm, String backendName) { if (backendName != null) { this.defineBackend(backendName).attach(); if (vm.primaryNetworkInterfaceId() != null) { this.nicsInBackends.put(vm.primaryNetworkInterfaceId(), backendName.toLowerCase()); } } return this; } @Override public LoadBalancerProbeImpl defineTcpProbe(String name) { LoadBalancerProbe probe = this.tcpProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.TCP); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancerProbeImpl defineHttpProbe(String name) { LoadBalancerProbe probe = this.httpProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.HTTP).withPort(80); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancerProbeImpl defineHttpsProbe(String name) { LoadBalancerProbe probe = this.httpsProbes.get(name); if (probe == null) { ProbeInner inner = new ProbeInner().withName(name).withProtocol(ProbeProtocol.HTTPS).withPort(443); return new LoadBalancerProbeImpl(inner, this); } else { return (LoadBalancerProbeImpl) probe; } } @Override public LoadBalancingRuleImpl defineLoadBalancingRule(String name) { LoadBalancingRule lbRule = this.loadBalancingRules.get(name); if (lbRule == null) { LoadBalancingRuleInner inner = new LoadBalancingRuleInner().withName(name); return new LoadBalancingRuleImpl(inner, this); } else { return (LoadBalancingRuleImpl) lbRule; } } @Override public LoadBalancerInboundNatRuleImpl defineInboundNatRule(String name) { LoadBalancerInboundNatRule natRule = this.inboundNatRules.get(name); if (natRule == null) { InboundNatRuleInner inner = new InboundNatRuleInner().withName(name); return new LoadBalancerInboundNatRuleImpl(inner, this); } else { return (LoadBalancerInboundNatRuleImpl) natRule; } } @Override public LoadBalancerInboundNatPoolImpl defineInboundNatPool(String name) { LoadBalancerInboundNatPool natPool = this.inboundNatPools.get(name); if (natPool == null) { InboundNatPool inner = new InboundNatPool().withName(name); return new LoadBalancerInboundNatPoolImpl(inner, this); } else { return (LoadBalancerInboundNatPoolImpl) natPool; } } @Override public LoadBalancerFrontendImpl definePrivateFrontend(String name) { return defineFrontend(name); } @Override public LoadBalancerFrontendImpl definePublicFrontend(String name) { return defineFrontend(name); } LoadBalancerFrontendImpl defineFrontend(String name) { LoadBalancerFrontend frontend = this.frontends.get(name); if (frontend == null) { FrontendIPConfigurationInner inner = new FrontendIPConfigurationInner().withName(name); return new LoadBalancerFrontendImpl(inner, this); } else { return (LoadBalancerFrontendImpl) frontend; } } @Override public LoadBalancerBackendImpl defineBackend(String name) { LoadBalancerBackend backend = this.backends.get(name); if (backend == null) { BackendAddressPoolInner inner = new BackendAddressPoolInner().withName(name); return new LoadBalancerBackendImpl(inner, this); } else { return (LoadBalancerBackendImpl) backend; } } @Override public LoadBalancerImpl withSku(LoadBalancerSkuType skuType) { this.inner().withSku(skuType.sku()); return this; } @Override public LoadBalancerImpl withoutProbe(String name) { if (this.httpProbes.containsKey(name)) { this.httpProbes.remove(name); } else if (this.httpsProbes.containsKey(name)) { this.httpsProbes.remove(name); } else if (this.tcpProbes.containsKey(name)) { this.tcpProbes.remove(name); } return this; } @Override public LoadBalancerProbeImpl updateTcpProbe(String name) { return (LoadBalancerProbeImpl) this.tcpProbes.get(name); } @Override public LoadBalancerBackendImpl updateBackend(String name) { return (LoadBalancerBackendImpl) this.backends.get(name); } @Override public LoadBalancerFrontendImpl updatePublicFrontend(String name) { return (LoadBalancerFrontendImpl) this.frontends.get(name); } @Override public LoadBalancerFrontendImpl updatePrivateFrontend(String name) { return (LoadBalancerFrontendImpl) this.frontends.get(name); } @Override public LoadBalancerInboundNatRuleImpl updateInboundNatRule(String name) { return (LoadBalancerInboundNatRuleImpl) this.inboundNatRules.get(name); } @Override public LoadBalancerInboundNatPoolImpl updateInboundNatPool(String name) { return (LoadBalancerInboundNatPoolImpl) this.inboundNatPools.get(name); } @Override public LoadBalancerProbeImpl updateHttpProbe(String name) { return (LoadBalancerProbeImpl) this.httpProbes.get(name); } @Override public LoadBalancerProbeImpl updateHttpsProbe(String name) { return (LoadBalancerProbeImpl) this.httpsProbes.get(name); } @Override public LoadBalancingRuleImpl updateLoadBalancingRule(String name) { return (LoadBalancingRuleImpl) this.loadBalancingRules.get(name); } @Override public LoadBalancerImpl withoutLoadBalancingRule(String name) { this.loadBalancingRules.remove(name); return this; } @Override public LoadBalancerImpl withoutInboundNatRule(String name) { this.inboundNatRules.remove(name); return this; } @Override public LoadBalancerImpl withoutBackend(String name) { this.backends.remove(name); return this; } @Override public Update withoutInboundNatPool(String name) { this.inboundNatPools.remove(name); return this; } @Override public LoadBalancerImpl withoutFrontend(String name) { this.frontends.remove(name); return this; } @Override public Map<String, LoadBalancerBackend> backends() { return Collections.unmodifiableMap(this.backends); } @Override public Map<String, LoadBalancerInboundNatPool> inboundNatPools() { return Collections.unmodifiableMap(this.inboundNatPools); } @Override public LoadBalancerSkuType sku() { return LoadBalancerSkuType.fromSku(this.inner().sku()); } @Override public Map<String, LoadBalancerTcpProbe> tcpProbes() { return Collections.unmodifiableMap(this.tcpProbes); } @Override public Map<String, LoadBalancerFrontend> frontends() { return Collections.unmodifiableMap(this.frontends); } @Override public Map<String, LoadBalancerPrivateFrontend> privateFrontends() { Map<String, LoadBalancerPrivateFrontend> privateFrontends = new HashMap<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (!frontend.isPublic()) { privateFrontends.put(frontend.name(), (LoadBalancerPrivateFrontend) frontend); } } return Collections.unmodifiableMap(privateFrontends); } @Override public Map<String, LoadBalancerPublicFrontend> publicFrontends() { Map<String, LoadBalancerPublicFrontend> publicFrontends = new HashMap<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { publicFrontends.put(frontend.name(), (LoadBalancerPublicFrontend) frontend); } } return Collections.unmodifiableMap(publicFrontends); } @Override public Map<String, LoadBalancerInboundNatRule> inboundNatRules() { return Collections.unmodifiableMap(this.inboundNatRules); } @Override public Map<String, LoadBalancerHttpProbe> httpProbes() { return Collections.unmodifiableMap(this.httpProbes); } @Override public Map<String, LoadBalancerHttpProbe> httpsProbes() { return Collections.unmodifiableMap(this.httpsProbes); } @Override public Map<String, LoadBalancingRule> loadBalancingRules() { return Collections.unmodifiableMap(this.loadBalancingRules); } @Override public List<String> publicIPAddressIds() { List<String> publicIPAddressIds = new ArrayList<>(); for (LoadBalancerFrontend frontend : this.frontends().values()) { if (frontend.isPublic()) { String pipId = ((LoadBalancerPublicFrontend) frontend).publicIPAddressId(); publicIPAddressIds.add(pipId); } } return Collections.unmodifiableList(publicIPAddressIds); } @Override public LoadBalancerPublicFrontend findFrontendByPublicIPAddress(String pipId) { if (pipId == null) { return null; } for (LoadBalancerPublicFrontend frontend : this.publicFrontends().values()) { if (frontend.publicIPAddressId() == null) { continue; } else if (pipId.equalsIgnoreCase(frontend.publicIPAddressId())) { return frontend; } } return null; } @Override public LoadBalancerPublicFrontend findFrontendByPublicIPAddress(PublicIPAddress publicIPAddress) { return (publicIPAddress != null) ? this.findFrontendByPublicIPAddress(publicIPAddress.id()) : null; } }
I think you can change the TODO to just a note. I've updated the WAR to fallback to env var with "_" if "." not found.
public static boolean runSample(Azure azure) { final String suffix = ".azurewebsites.net"; final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20); final String app1Url = app1Name + suffix; final String storageName = azure.sdkContext().randomResourceName("jsdkstore", 20); final String containerName = azure.sdkContext().randomResourceName("jcontainer", 20); final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24); try { System.out.println("Creating storage account " + storageName + "..."); StorageAccount storageAccount = azure.storageAccounts().define(storageName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .create(); String accountKey = storageAccount.getKeys().get(0).value(); String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", storageAccount.name(), accountKey); System.out.println("Created storage account " + storageAccount.name()); System.out.println("Uploading 2 blobs to container " + containerName + "..."); BlobContainerClient container = setUpStorageAccount(connectionString, containerName); uploadFileToContainer(container, "helloworld.war", ManageLinuxWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); uploadFileToContainer(container, "install_apache.sh", ManageLinuxWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath()); System.out.println("Uploaded 2 blobs to container " + container.getBlobContainerName()); System.out.println("Creating web app " + app1Name + "..."); WebApp app1 = azure.webApps().define(app1Name) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName) .withNewLinuxPlan(PricingTier.STANDARD_S1) .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM) .withAppSetting("storage.containerName", containerName) .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); System.out.println("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP..."); Utils.uploadFileToWebApp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", ManageLinuxWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war")); System.out.println("Deployment azure-samples-blob-traverser.war to web app " + app1.name() + " completed"); Utils.print(app1); System.out.println("Warming up " + app1Url + "/azure-samples-blob-traverser..."); Utils.curl("http: SdkContext.sleep(5000); System.out.println("CURLing " + app1Url + "/azure-samples-blob-traverser..."); System.out.println(Utils.curl("http: return true; } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return false; }
public static boolean runSample(Azure azure) { final String suffix = ".azurewebsites.net"; final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20); final String app1Url = app1Name + suffix; final String storageName = azure.sdkContext().randomResourceName("jsdkstore", 20); final String containerName = azure.sdkContext().randomResourceName("jcontainer", 20); final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24); try { System.out.println("Creating storage account " + storageName + "..."); StorageAccount storageAccount = azure.storageAccounts().define(storageName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .create(); String accountKey = storageAccount.getKeys().get(0).value(); String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", storageAccount.name(), accountKey); System.out.println("Created storage account " + storageAccount.name()); System.out.println("Uploading 2 blobs to container " + containerName + "..."); BlobContainerClient container = setUpStorageAccount(connectionString, containerName); uploadFileToContainer(container, "helloworld.war", ManageLinuxWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); uploadFileToContainer(container, "install_apache.sh", ManageLinuxWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath()); System.out.println("Uploaded 2 blobs to container " + container.getBlobContainerName()); System.out.println("Creating web app " + app1Name + "..."); WebApp app1 = azure.webApps().define(app1Name) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName) .withNewLinuxPlan(PricingTier.STANDARD_S1) .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM) .withAppSetting("storage.containerName", containerName) .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); System.out.println("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP..."); Utils.uploadFileToWebApp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", ManageLinuxWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war")); System.out.println("Deployment azure-samples-blob-traverser.war to web app " + app1.name() + " completed"); Utils.print(app1); System.out.println("Warming up " + app1Url + "/azure-samples-blob-traverser..."); Utils.curl("http: SdkContext.sleep(5000); System.out.println("CURLing " + app1Url + "/azure-samples-blob-traverser..."); System.out.println(Utils.curl("http: return true; } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return false; }
class ManageLinuxWebAppStorageAccountConnection { /** * Main function which runs the actual sample. * @param azure instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); Azure azure = Azure.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credFile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private static BlobContainerClient setUpStorageAccount(String connectionString, String containerName) { BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() .connectionString(connectionString) .containerName(containerName) .buildClient(); blobContainerClient.create(); BlobSignedIdentifier identifier = new BlobSignedIdentifier() .setId("webapp") .setAccessPolicy(new BlobAccessPolicy() .setStartsOn(OffsetDateTime.now()) .setExpiresOn(OffsetDateTime.now().plusDays(7)) .setPermissions("rl")); blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)); return blobContainerClient; } private static void uploadFileToContainer(BlobContainerClient blobContainerClient, String fileName, String filePath) { BlobClient blobClient = blobContainerClient.getBlobClient(fileName); File file = new File(filePath); try (InputStream is = new FileInputStream(file)) { blobClient.upload(is, file.length()); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
class ManageLinuxWebAppStorageAccountConnection { /** * Main function which runs the actual sample. * @param azure instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); Azure azure = Azure.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credFile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private static BlobContainerClient setUpStorageAccount(String connectionString, String containerName) { BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() .connectionString(connectionString) .containerName(containerName) .buildClient(); blobContainerClient.create(); BlobSignedIdentifier identifier = new BlobSignedIdentifier() .setId("webapp") .setAccessPolicy(new BlobAccessPolicy() .setStartsOn(OffsetDateTime.now()) .setExpiresOn(OffsetDateTime.now().plusDays(7)) .setPermissions("rl")); blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)); return blobContainerClient; } private static void uploadFileToContainer(BlobContainerClient blobContainerClient, String fileName, String filePath) { BlobClient blobClient = blobContainerClient.getBlobClient(fileName); File file = new File(filePath); try (InputStream is = new FileInputStream(file)) { blobClient.upload(is, file.length()); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
might not be the best place to define `logger`?
public DockerSSLConfig(String caPem, String keyPem, String certPem) { try { Security.addProvider(new BouncyCastleProvider()); String e = System.getProperty("https.protocols"); System.setProperty("https.protocols", "TLSv1"); sslConfig = SslConfigurator.newInstance(true); if (e != null) { System.setProperty("https.protocols", e); } sslConfig.keyStore(CertificateUtils.createKeyStore(keyPem, certPem)); sslConfig.keyStorePassword("docker"); sslConfig.trustStore(CertificateUtils.createTrustStore(caPem)); } catch (Exception e) { ClientLogger logger = new ClientLogger(getClass()); throw logger.logExceptionAsError(new DockerClientException(e.getMessage(), e)); } }
ClientLogger logger = new ClientLogger(getClass());
public DockerSSLConfig(String caPem, String keyPem, String certPem) { try { Security.addProvider(new BouncyCastleProvider()); String e = System.getProperty("https.protocols"); System.setProperty("https.protocols", "TLSv1"); sslConfig = SslConfigurator.newInstance(true); if (e != null) { System.setProperty("https.protocols", e); } sslConfig.keyStore(CertificateUtils.createKeyStore(keyPem, certPem)); sslConfig.keyStorePassword("docker"); sslConfig.trustStore(CertificateUtils.createTrustStore(caPem)); } catch (Exception e) { throw new DockerClientException(e.getMessage(), e); } }
class DockerSSLConfig implements SSLConfig, Serializable { private SslConfigurator sslConfig; /** * Constructor for the class. * * @param caPem - content of the ca.pem certificate file * @param keyPem - content of the key.pem certificate file * @param certPem - content of the cert.pem certificate file */ @Override public SSLContext getSSLContext() { return sslConfig.createSSLContext(); } }
class DockerSSLConfig implements SSLConfig, Serializable { private SslConfigurator sslConfig; /** * Constructor for the class. * * @param caPem - content of the ca.pem certificate file * @param keyPem - content of the key.pem certificate file * @param certPem - content of the cert.pem certificate file * @throws DockerClientException throws when something unexpected happens */ @Override public SSLContext getSSLContext() { return sslConfig.createSSLContext(); } }
I have thought logger should not add in class since it is just a sample. Done, change it to comment rather than logger.
public DockerSSLConfig(String caPem, String keyPem, String certPem) { try { Security.addProvider(new BouncyCastleProvider()); String e = System.getProperty("https.protocols"); System.setProperty("https.protocols", "TLSv1"); sslConfig = SslConfigurator.newInstance(true); if (e != null) { System.setProperty("https.protocols", e); } sslConfig.keyStore(CertificateUtils.createKeyStore(keyPem, certPem)); sslConfig.keyStorePassword("docker"); sslConfig.trustStore(CertificateUtils.createTrustStore(caPem)); } catch (Exception e) { ClientLogger logger = new ClientLogger(getClass()); throw logger.logExceptionAsError(new DockerClientException(e.getMessage(), e)); } }
ClientLogger logger = new ClientLogger(getClass());
public DockerSSLConfig(String caPem, String keyPem, String certPem) { try { Security.addProvider(new BouncyCastleProvider()); String e = System.getProperty("https.protocols"); System.setProperty("https.protocols", "TLSv1"); sslConfig = SslConfigurator.newInstance(true); if (e != null) { System.setProperty("https.protocols", e); } sslConfig.keyStore(CertificateUtils.createKeyStore(keyPem, certPem)); sslConfig.keyStorePassword("docker"); sslConfig.trustStore(CertificateUtils.createTrustStore(caPem)); } catch (Exception e) { throw new DockerClientException(e.getMessage(), e); } }
class DockerSSLConfig implements SSLConfig, Serializable { private SslConfigurator sslConfig; /** * Constructor for the class. * * @param caPem - content of the ca.pem certificate file * @param keyPem - content of the key.pem certificate file * @param certPem - content of the cert.pem certificate file */ @Override public SSLContext getSSLContext() { return sslConfig.createSSLContext(); } }
class DockerSSLConfig implements SSLConfig, Serializable { private SslConfigurator sslConfig; /** * Constructor for the class. * * @param caPem - content of the ca.pem certificate file * @param keyPem - content of the key.pem certificate file * @param certPem - content of the cert.pem certificate file * @throws DockerClientException throws when something unexpected happens */ @Override public SSLContext getSSLContext() { return sslConfig.createSSLContext(); } }
Done
public static boolean runSample(Azure azure) { final String suffix = ".azurewebsites.net"; final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20); final String app1Url = app1Name + suffix; final String storageName = azure.sdkContext().randomResourceName("jsdkstore", 20); final String containerName = azure.sdkContext().randomResourceName("jcontainer", 20); final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24); try { System.out.println("Creating storage account " + storageName + "..."); StorageAccount storageAccount = azure.storageAccounts().define(storageName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .create(); String accountKey = storageAccount.getKeys().get(0).value(); String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", storageAccount.name(), accountKey); System.out.println("Created storage account " + storageAccount.name()); System.out.println("Uploading 2 blobs to container " + containerName + "..."); BlobContainerClient container = setUpStorageAccount(connectionString, containerName); uploadFileToContainer(container, "helloworld.war", ManageLinuxWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); uploadFileToContainer(container, "install_apache.sh", ManageLinuxWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath()); System.out.println("Uploaded 2 blobs to container " + container.getBlobContainerName()); System.out.println("Creating web app " + app1Name + "..."); WebApp app1 = azure.webApps().define(app1Name) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName) .withNewLinuxPlan(PricingTier.STANDARD_S1) .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM) .withAppSetting("storage.containerName", containerName) .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); System.out.println("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP..."); Utils.uploadFileToWebApp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", ManageLinuxWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war")); System.out.println("Deployment azure-samples-blob-traverser.war to web app " + app1.name() + " completed"); Utils.print(app1); System.out.println("Warming up " + app1Url + "/azure-samples-blob-traverser..."); Utils.curl("http: SdkContext.sleep(5000); System.out.println("CURLing " + app1Url + "/azure-samples-blob-traverser..."); System.out.println(Utils.curl("http: return true; } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return false; }
public static boolean runSample(Azure azure) { final String suffix = ".azurewebsites.net"; final String app1Name = azure.sdkContext().randomResourceName("webapp1-", 20); final String app1Url = app1Name + suffix; final String storageName = azure.sdkContext().randomResourceName("jsdkstore", 20); final String containerName = azure.sdkContext().randomResourceName("jcontainer", 20); final String rgName = azure.sdkContext().randomResourceName("rg1NEMV_", 24); try { System.out.println("Creating storage account " + storageName + "..."); StorageAccount storageAccount = azure.storageAccounts().define(storageName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .create(); String accountKey = storageAccount.getKeys().get(0).value(); String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", storageAccount.name(), accountKey); System.out.println("Created storage account " + storageAccount.name()); System.out.println("Uploading 2 blobs to container " + containerName + "..."); BlobContainerClient container = setUpStorageAccount(connectionString, containerName); uploadFileToContainer(container, "helloworld.war", ManageLinuxWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); uploadFileToContainer(container, "install_apache.sh", ManageLinuxWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath()); System.out.println("Uploaded 2 blobs to container " + container.getBlobContainerName()); System.out.println("Creating web app " + app1Name + "..."); WebApp app1 = azure.webApps().define(app1Name) .withRegion(Region.US_WEST) .withExistingResourceGroup(rgName) .withNewLinuxPlan(PricingTier.STANDARD_S1) .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM) .withAppSetting("storage.containerName", containerName) .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); System.out.println("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP..."); Utils.uploadFileToWebApp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", ManageLinuxWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war")); System.out.println("Deployment azure-samples-blob-traverser.war to web app " + app1.name() + " completed"); Utils.print(app1); System.out.println("Warming up " + app1Url + "/azure-samples-blob-traverser..."); Utils.curl("http: SdkContext.sleep(5000); System.out.println("CURLing " + app1Url + "/azure-samples-blob-traverser..."); System.out.println(Utils.curl("http: return true; } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return false; }
class ManageLinuxWebAppStorageAccountConnection { /** * Main function which runs the actual sample. * @param azure instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); Azure azure = Azure.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credFile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private static BlobContainerClient setUpStorageAccount(String connectionString, String containerName) { BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() .connectionString(connectionString) .containerName(containerName) .buildClient(); blobContainerClient.create(); BlobSignedIdentifier identifier = new BlobSignedIdentifier() .setId("webapp") .setAccessPolicy(new BlobAccessPolicy() .setStartsOn(OffsetDateTime.now()) .setExpiresOn(OffsetDateTime.now().plusDays(7)) .setPermissions("rl")); blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)); return blobContainerClient; } private static void uploadFileToContainer(BlobContainerClient blobContainerClient, String fileName, String filePath) { BlobClient blobClient = blobContainerClient.getBlobClient(fileName); File file = new File(filePath); try (InputStream is = new FileInputStream(file)) { blobClient.upload(is, file.length()); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
class ManageLinuxWebAppStorageAccountConnection { /** * Main function which runs the actual sample. * @param azure instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); Azure azure = Azure.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credFile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private static BlobContainerClient setUpStorageAccount(String connectionString, String containerName) { BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() .connectionString(connectionString) .containerName(containerName) .buildClient(); blobContainerClient.create(); BlobSignedIdentifier identifier = new BlobSignedIdentifier() .setId("webapp") .setAccessPolicy(new BlobAccessPolicy() .setStartsOn(OffsetDateTime.now()) .setExpiresOn(OffsetDateTime.now().plusDays(7)) .setPermissions("rl")); blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)); return blobContainerClient; } private static void uploadFileToContainer(BlobContainerClient blobContainerClient, String fileName, String filePath) { BlobClient blobClient = blobContainerClient.getBlobClient(fileName); File file = new File(filePath); try (InputStream is = new FileInputStream(file)) { blobClient.upload(is, file.length()); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
You'll want to move this into the `getBodyAsString` overload without parameters, nothing I've found in Azure Core leverages the `Charset` overload.
public Mono<String> getBodyAsString(Charset charset) { Objects.requireNonNull(charset, "'charset' cannot be null."); return bodyBytes == null ? Mono.empty() : Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type"))); }
: Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type")));
public Mono<String> getBodyAsString(Charset charset) { Objects.requireNonNull(charset, "'charset' cannot be null."); return bodyBytes == null ? Mono.empty() : Mono.just(new String(bodyBytes, charset)); }
class MockHttpResponse extends HttpResponse { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); private final int statusCode; private final HttpHeaders headers; private final byte[] bodyBytes; /** * Creates a HTTP response associated with a {@code request}, returns the {@code statusCode}, and has an empty * response body. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. */ public MockHttpResponse(HttpRequest request, int statusCode) { this(request, statusCode, new byte[0]); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body of * {@code bodyBytes}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param bodyBytes Contents of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, byte[] bodyBytes) { this(request, statusCode, new HttpHeaders(), bodyBytes); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and http headers. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param headers Headers of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers) { this(request, statusCode, headers, new byte[0]); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the * {@code headers}, and response body of {@code bodyBytes}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param headers HttpHeaders of the response. * @param bodyBytes Contents of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, byte[] bodyBytes) { super(request); this.statusCode = statusCode; this.headers = headers; this.bodyBytes = CoreUtils.clone(bodyBytes); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the given * {@code headers}, and response body that is JSON serialized from {@code serializable}. * * @param request HttpRequest associated with the response. * @param headers HttpHeaders of the response. * @param statusCode Status code of the response. * @param serializable Contents to be serialized into JSON for the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, Object serializable) { this(request, statusCode, headers, serialize(serializable)); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body * that is JSON serialized from {@code serializable}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param serializable Contents to be serialized into JSON for the response. */ public MockHttpResponse(HttpRequest request, int statusCode, Object serializable) { this(request, statusCode, new HttpHeaders(), serialize(serializable)); } private static byte[] serialize(Object serializable) { byte[] result = null; try { final String serializedString = SERIALIZER.serialize(serializable, SerializerEncoding.JSON); result = serializedString == null ? null : serializedString.getBytes(StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return result; } /** * {@inheritDoc} */ @Override public int getStatusCode() { return statusCode; } /** * {@inheritDoc} */ @Override public String getHeaderValue(String name) { return headers.getValue(name); } /** * {@inheritDoc} */ @Override public HttpHeaders getHeaders() { return new HttpHeaders(headers); } /** * {@inheritDoc} */ @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes == null) { return Mono.empty(); } else { return Mono.just(bodyBytes); } } /** * {@inheritDoc} */ @Override public Flux<ByteBuffer> getBody() { if (bodyBytes == null) { return Flux.empty(); } else { return Flux.just(ByteBuffer.wrap(bodyBytes)); } } /** * {@inheritDoc} */ @Override public Mono<String> getBodyAsString() { return getBodyAsString(StandardCharsets.UTF_8); } /** * {@inheritDoc} */ @Override /** * Adds the header {@code name} and {@code value} to the existing set of HTTP headers. * @param name The header to add * @param value The header value. * @return The updated response object. */ public MockHttpResponse addHeader(String name, String value) { headers.put(name, value); return this; } }
class MockHttpResponse extends HttpResponse { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); private final int statusCode; private final HttpHeaders headers; private final byte[] bodyBytes; /** * Creates a HTTP response associated with a {@code request}, returns the {@code statusCode}, and has an empty * response body. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. */ public MockHttpResponse(HttpRequest request, int statusCode) { this(request, statusCode, new byte[0]); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body of * {@code bodyBytes}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param bodyBytes Contents of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, byte[] bodyBytes) { this(request, statusCode, new HttpHeaders(), bodyBytes); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and http headers. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param headers Headers of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers) { this(request, statusCode, headers, new byte[0]); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the * {@code headers}, and response body of {@code bodyBytes}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param headers HttpHeaders of the response. * @param bodyBytes Contents of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, byte[] bodyBytes) { super(request); this.statusCode = statusCode; this.headers = headers; this.bodyBytes = CoreUtils.clone(bodyBytes); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the given * {@code headers}, and response body that is JSON serialized from {@code serializable}. * * @param request HttpRequest associated with the response. * @param headers HttpHeaders of the response. * @param statusCode Status code of the response. * @param serializable Contents to be serialized into JSON for the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, Object serializable) { this(request, statusCode, headers, serialize(serializable)); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body * that is JSON serialized from {@code serializable}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param serializable Contents to be serialized into JSON for the response. */ public MockHttpResponse(HttpRequest request, int statusCode, Object serializable) { this(request, statusCode, new HttpHeaders(), serialize(serializable)); } private static byte[] serialize(Object serializable) { byte[] result = null; try { final String serializedString = SERIALIZER.serialize(serializable, SerializerEncoding.JSON); result = serializedString == null ? null : serializedString.getBytes(StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return result; } /** * {@inheritDoc} */ @Override public int getStatusCode() { return statusCode; } /** * {@inheritDoc} */ @Override public String getHeaderValue(String name) { return headers.getValue(name); } /** * {@inheritDoc} */ @Override public HttpHeaders getHeaders() { return new HttpHeaders(headers); } /** * {@inheritDoc} */ @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes == null) { return Mono.empty(); } else { return Mono.just(bodyBytes); } } /** * {@inheritDoc} */ @Override public Flux<ByteBuffer> getBody() { if (bodyBytes == null) { return Flux.empty(); } else { return Flux.just(ByteBuffer.wrap(bodyBytes)); } } /** * {@inheritDoc} */ @Override public Mono<String> getBodyAsString() { return (bodyBytes == null) ? Mono.empty() : Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type"))); } /** * {@inheritDoc} */ @Override /** * Adds the header {@code name} and {@code value} to the existing set of HTTP headers. * @param name The header to add * @param value The header value. * @return The updated response object. */ public MockHttpResponse addHeader(String name, String value) { headers.put(name, value); return this; } }
```java public Mono<String> getBodyAsString() { return (bodyBytes == null) ? Mono.empty() : Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type")); }
public Mono<String> getBodyAsString(Charset charset) { Objects.requireNonNull(charset, "'charset' cannot be null."); return bodyBytes == null ? Mono.empty() : Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type"))); }
: Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type")));
public Mono<String> getBodyAsString(Charset charset) { Objects.requireNonNull(charset, "'charset' cannot be null."); return bodyBytes == null ? Mono.empty() : Mono.just(new String(bodyBytes, charset)); }
class MockHttpResponse extends HttpResponse { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); private final int statusCode; private final HttpHeaders headers; private final byte[] bodyBytes; /** * Creates a HTTP response associated with a {@code request}, returns the {@code statusCode}, and has an empty * response body. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. */ public MockHttpResponse(HttpRequest request, int statusCode) { this(request, statusCode, new byte[0]); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body of * {@code bodyBytes}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param bodyBytes Contents of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, byte[] bodyBytes) { this(request, statusCode, new HttpHeaders(), bodyBytes); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and http headers. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param headers Headers of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers) { this(request, statusCode, headers, new byte[0]); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the * {@code headers}, and response body of {@code bodyBytes}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param headers HttpHeaders of the response. * @param bodyBytes Contents of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, byte[] bodyBytes) { super(request); this.statusCode = statusCode; this.headers = headers; this.bodyBytes = CoreUtils.clone(bodyBytes); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the given * {@code headers}, and response body that is JSON serialized from {@code serializable}. * * @param request HttpRequest associated with the response. * @param headers HttpHeaders of the response. * @param statusCode Status code of the response. * @param serializable Contents to be serialized into JSON for the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, Object serializable) { this(request, statusCode, headers, serialize(serializable)); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body * that is JSON serialized from {@code serializable}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param serializable Contents to be serialized into JSON for the response. */ public MockHttpResponse(HttpRequest request, int statusCode, Object serializable) { this(request, statusCode, new HttpHeaders(), serialize(serializable)); } private static byte[] serialize(Object serializable) { byte[] result = null; try { final String serializedString = SERIALIZER.serialize(serializable, SerializerEncoding.JSON); result = serializedString == null ? null : serializedString.getBytes(StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return result; } /** * {@inheritDoc} */ @Override public int getStatusCode() { return statusCode; } /** * {@inheritDoc} */ @Override public String getHeaderValue(String name) { return headers.getValue(name); } /** * {@inheritDoc} */ @Override public HttpHeaders getHeaders() { return new HttpHeaders(headers); } /** * {@inheritDoc} */ @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes == null) { return Mono.empty(); } else { return Mono.just(bodyBytes); } } /** * {@inheritDoc} */ @Override public Flux<ByteBuffer> getBody() { if (bodyBytes == null) { return Flux.empty(); } else { return Flux.just(ByteBuffer.wrap(bodyBytes)); } } /** * {@inheritDoc} */ @Override public Mono<String> getBodyAsString() { return getBodyAsString(StandardCharsets.UTF_8); } /** * {@inheritDoc} */ @Override /** * Adds the header {@code name} and {@code value} to the existing set of HTTP headers. * @param name The header to add * @param value The header value. * @return The updated response object. */ public MockHttpResponse addHeader(String name, String value) { headers.put(name, value); return this; } }
class MockHttpResponse extends HttpResponse { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); private final int statusCode; private final HttpHeaders headers; private final byte[] bodyBytes; /** * Creates a HTTP response associated with a {@code request}, returns the {@code statusCode}, and has an empty * response body. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. */ public MockHttpResponse(HttpRequest request, int statusCode) { this(request, statusCode, new byte[0]); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body of * {@code bodyBytes}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param bodyBytes Contents of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, byte[] bodyBytes) { this(request, statusCode, new HttpHeaders(), bodyBytes); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and http headers. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param headers Headers of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers) { this(request, statusCode, headers, new byte[0]); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the * {@code headers}, and response body of {@code bodyBytes}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param headers HttpHeaders of the response. * @param bodyBytes Contents of the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, byte[] bodyBytes) { super(request); this.statusCode = statusCode; this.headers = headers; this.bodyBytes = CoreUtils.clone(bodyBytes); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the given * {@code headers}, and response body that is JSON serialized from {@code serializable}. * * @param request HttpRequest associated with the response. * @param headers HttpHeaders of the response. * @param statusCode Status code of the response. * @param serializable Contents to be serialized into JSON for the response. */ public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, Object serializable) { this(request, statusCode, headers, serialize(serializable)); } /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body * that is JSON serialized from {@code serializable}. * * @param request HttpRequest associated with the response. * @param statusCode Status code of the response. * @param serializable Contents to be serialized into JSON for the response. */ public MockHttpResponse(HttpRequest request, int statusCode, Object serializable) { this(request, statusCode, new HttpHeaders(), serialize(serializable)); } private static byte[] serialize(Object serializable) { byte[] result = null; try { final String serializedString = SERIALIZER.serialize(serializable, SerializerEncoding.JSON); result = serializedString == null ? null : serializedString.getBytes(StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return result; } /** * {@inheritDoc} */ @Override public int getStatusCode() { return statusCode; } /** * {@inheritDoc} */ @Override public String getHeaderValue(String name) { return headers.getValue(name); } /** * {@inheritDoc} */ @Override public HttpHeaders getHeaders() { return new HttpHeaders(headers); } /** * {@inheritDoc} */ @Override public Mono<byte[]> getBodyAsByteArray() { if (bodyBytes == null) { return Mono.empty(); } else { return Mono.just(bodyBytes); } } /** * {@inheritDoc} */ @Override public Flux<ByteBuffer> getBody() { if (bodyBytes == null) { return Flux.empty(); } else { return Flux.just(ByteBuffer.wrap(bodyBytes)); } } /** * {@inheritDoc} */ @Override public Mono<String> getBodyAsString() { return (bodyBytes == null) ? Mono.empty() : Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type"))); } /** * {@inheritDoc} */ @Override /** * Adds the header {@code name} and {@code value} to the existing set of HTTP headers. * @param name The header to add * @param value The header value. * @return The updated response object. */ public MockHttpResponse addHeader(String name, String value) { headers.put(name, value); return this; } }
If create succeeded, then you can break out of the `do-while` loop.
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
.create();
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
The management plane does not provide us the status of creation. I have to ping the service to confirm. The newly added code is to avoid failure of creating on already exists account.
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
.create();
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
Could we check the `status` of the `SearchService` object?
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
.create();
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
Just checked over the API. Find the status one this time. Missing from the initial investigation. Will try to switch to status() checking
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
.create();
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
I have tried the API they provided. Seems not that stable as service ping. In order to make our live tests more stable. I decided to switch back to ping machenism.
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
.create();
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
https://dev.azure.com/azure-sdk/internal/_build/results?buildId=356026&view=results
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
.create();
public void createService(TestResourceNamer testResourceNamer) { searchServiceName = testResourceNamer.randomName(SEARCH_SERVICE_NAME_PREFIX, 60); System.out.println("Creating Azure Cognitive Search service: " + searchServiceName); int recreateCount = 0; do { try { searchService = azure.searchServices() .define(searchServiceName) .withRegion(location) .withExistingResourceGroup(resourceGroup) .withFreeSku() .create(); recreateCount += 1; } catch (CloudException ex) { if (ex.getMessage().contains("already exists")) { System.out.println(String.format("Azure Cognitive Search service %s has already been created. ", searchServiceName)); break; } } } while (recreateCount < 3 && shouldRetryCreateService()); if (recreateCount == 3 && shouldRetryCreateService()) { fail("Failed to create service"); } searchAdminKey = searchService.getAdminKeys().primaryKey(); }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
class variables * to be retrieved later. */ public void initialize() { validate(); initializeAzureResources(); if (azure == null) { azure = Azure.configure() .authenticate(azureTokenCredentials) .withSubscription(subscriptionId); } searchDnsSuffix = testEnvironment.equals("DOGFOOD") ? DOGFOOD_DNS_SUFFIX : DEFAULT_DNS_SUFFIX; endpoint = String.format("https: }
This logic doesn't exist in SB either.... would you mind copy and paste it there? :D Kill two birds with 3 stones?
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()),coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } }
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } }
class EventHubClientBuilder { static final int DEFAULT_PREFETCH_COUNT = 500; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private int prefetchCount; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; prefetchCount = DEFAULT_PREFETCH_COUNT; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose); } /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { logger.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(logger.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); logger.info("connectionId[{}]: Emitting a single connection.", connectionId); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer, product, clientVersion); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler); } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } }
class EventHubClientBuilder { static final int DEFAULT_PREFETCH_COUNT = 500; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private int prefetchCount; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; prefetchCount = DEFAULT_PREFETCH_COUNT; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose); } /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { logger.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(logger.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); logger.info("connectionId[{}]: Emitting a single connection.", connectionId); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer, product, clientVersion); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler); } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } }
Sure, let me fix SB too.
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()),coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } }
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } }
class EventHubClientBuilder { static final int DEFAULT_PREFETCH_COUNT = 500; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private int prefetchCount; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; prefetchCount = DEFAULT_PREFETCH_COUNT; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose); } /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { logger.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(logger.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); logger.info("connectionId[{}]: Emitting a single connection.", connectionId); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer, product, clientVersion); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler); } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } }
class EventHubClientBuilder { static final int DEFAULT_PREFETCH_COUNT = 500; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private int prefetchCount; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; prefetchCount = DEFAULT_PREFETCH_COUNT; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose); } /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { logger.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(logger.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); logger.info("connectionId[{}]: Emitting a single connection.", connectionId); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer, product, clientVersion); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler); } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } }
You're the best! ![](https://media2.giphy.com/media/26AHAw0aMmWwRI4Hm/giphy.gif)
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()),coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } }
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) { String host; int port; if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) { final String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); final String username = configuration.get(ProxyOptions.PROXY_USERNAME); final String password = configuration.get(ProxyOptions.PROXY_PASSWORD); return new ProxyOptions(authentication, proxy, username, password); } else { com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions .fromConfiguration(configuration); return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(), coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword()); } }
class EventHubClientBuilder { static final int DEFAULT_PREFETCH_COUNT = 500; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private int prefetchCount; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; prefetchCount = DEFAULT_PREFETCH_COUNT; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose); } /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { logger.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(logger.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); logger.info("connectionId[{}]: Emitting a single connection.", connectionId); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer, product, clientVersion); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler); } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } }
class EventHubClientBuilder { static final int DEFAULT_PREFETCH_COUNT = 500; /** * The name of the default consumer group in the Event Hubs service. */ public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default"; /** * The minimum value allowed for the prefetch count of the consumer. */ private static final int MINIMUM_PREFETCH_COUNT = 1; /** * The maximum value allowed for the prefetch count of the consumer. */ private static final int MAXIMUM_PREFETCH_COUNT = 8000; private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; private static final String NAME_KEY = "name"; private static final String VERSION_KEY = "version"; private static final String UNKNOWN = "UNKNOWN"; private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions() .setTryTimeout(ClientConstants.OPERATION_TIMEOUT); private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+"); private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class); private final Object connectionLock = new Object(); private final AtomicBoolean isSharedConnection = new AtomicBoolean(); private TokenCredential credentials; private Configuration configuration; private ProxyOptions proxyOptions; private AmqpRetryOptions retryOptions; private Scheduler scheduler; private AmqpTransportType transport; private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; private EventHubConnectionProcessor eventHubConnectionProcessor; private int prefetchCount; /** * Keeps track of the open clients that were created from this builder when there is a shared connection. */ private final AtomicInteger openClients = new AtomicInteger(); /** * Creates a new instance with the default transport {@link AmqpTransportType * non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer * created using the builder. */ public EventHubClientBuilder() { transport = AmqpTransportType.AMQP; prefetchCount = DEFAULT_PREFETCH_COUNT; } /** * Sets the credential information given a connection string to the Event Hub instance. * * <p> * If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the * desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal * "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub". * </p> * * <p> * If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string * from that Event Hub will result in a connection string that contains the name. * </p> * * @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected * that the Event Hub name and the shared access key properties are contained in this connection string. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code * connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString) { final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential); } /** * Sets the credential information given a connection string to the Event Hubs namespace and name to a specific * Event Hub instance. * * @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is * expected that the shared access key properties are contained in this connection string, but not the Event Hub * name. * @param eventHubName The name of the Event Hub to connect the client to. * * @return The updated {@link EventHubClientBuilder} object. * @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null. * @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or, * if the {@code connectionString} contains the Event Hub name. * @throws AzureException If the shared access signature token credential could not be created using the * connection string. */ public EventHubClientBuilder connectionString(String connectionString, String eventHubName) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot be an empty string.")); } else if (eventHubName.isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY); if (!CoreUtils.isNullOrEmpty(properties.getEntityPath()) && !eventHubName.equals(properties.getEntityPath())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'connectionString' contains an Event Hub name [%s] and it does not match the given " + "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. " + "Or supply a 'connectionString' without 'EntityPath' in it.", properties.getEntityPath(), eventHubName))); } return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential); } /** * Sets the configuration store that is used during construction of the service client. * * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use * {@link Configuration * * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Toggles the builder to use the same connection for producers or consumers that are built from this instance. By * default, a new connection is constructed and used created for each Event Hub consumer or producer created. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder shareConnection() { this.isSharedConnection.set(true); return this; } /** * Sets the credential information for which Event Hub instance to connect to, and how to authorize against it. * * @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be * similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>. * @param eventHubName The name of the Event Hub to connect the client to. * @param credential The token credential to use for authorization. Access controls may be specified by the * Event Hubs namespace or the requested Event Hub, depending on Azure configuration. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty * string. * @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is * null. */ public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName, TokenCredential credential) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null."); this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string.")); } else if (CoreUtils.isNullOrEmpty(eventHubName)) { throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string.")); } return this; } /** * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * AmqpTransportType * * @param proxyOptions The proxy configuration to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link * AmqpTransportType * * @param transport The transport type to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder transportType(AmqpTransportType transport) { this.transport = transport; return this; } /** * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used. * * @param retryOptions The retry policy to use. * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is {@link * "$Default"}. * * @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the * context of this group. The name of the consumer group that is created by default is {@link * * * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder consumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; return this; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. * * @param prefetchCount The amount of events to queue locally. * * @return The updated {@link EventHubClientBuilder} object. * @throws IllegalArgumentException if {@code prefetchCount} is less than {@link * greater than {@link */ public EventHubClientBuilder prefetchCount(int prefetchCount) { if (prefetchCount < MINIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT))); } if (prefetchCount > MAXIMUM_PREFETCH_COUNT) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT))); } this.prefetchCount = prefetchCount; return this; } /** * Package-private method that sets the scheduler for the created Event Hub client. * * @param scheduler Scheduler to set. * * @return The updated {@link EventHubClientBuilder} object. */ EventHubClientBuilder scheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code * buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created. * * @return A new {@link EventHubConsumerAsyncClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerAsyncClient buildAsyncConsumerClient() { if (CoreUtils.isNullOrEmpty(consumerGroup)) { throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty " + "string. using EventHubClientBuilder.consumerGroup(String)")); } return buildAsyncClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code * buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created. * * @return A new {@link EventHubConsumerClient} with the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * {@link * {@link AmqpTransportType */ public EventHubConsumerClient buildConsumerClient() { return buildClient().createConsumer(consumerGroup, prefetchCount); } /** * Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created. * * @return A new {@link EventHubProducerAsyncClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerAsyncClient buildAsyncProducerClient() { return buildAsyncClient().createProducer(); } /** * Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code * buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created. * * @return A new {@link EventHubProducerClient} instance with all the configured options. * @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using * either {@link * proxy is specified but the transport type is not {@link AmqpTransportType */ public EventHubProducerClient buildProducerClient() { return buildClient().createProducer(); } /** * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code * buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubAsyncClient buildAsyncClient() { if (retryOptions == null) { retryOptions = DEFAULT_RETRY; } if (scheduler == null) { scheduler = Schedulers.elastic(); } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); final EventHubConnectionProcessor processor; if (isSharedConnection.get()) { synchronized (connectionLock) { if (eventHubConnectionProcessor == null) { eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } } processor = eventHubConnectionProcessor; final int numberOfOpenClients = openClients.incrementAndGet(); logger.info(" } else { processor = buildConnectionProcessor(messageSerializer); } final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler, isSharedConnection.get(), this::onClientClose); } /** * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is * invoked, a new instance of {@link EventHubClient} is created. * * <p> * The following options are used if ones are not specified in the builder: * * <ul> * <li>If no configuration is specified, the {@link Configuration * is used to provide any shared configuration values. The configuration values read are the {@link * Configuration * ProxyOptions * <li>If no retry is specified, the default retry options are used.</li> * <li>If no proxy is specified, the builder checks the {@link Configuration * configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li> * <li>If no timeout is specified, a {@link ClientConstants * <li>If no scheduler is specified, an {@link Schedulers * </ul> * * @return A new {@link EventHubClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * * specified but the transport type is not {@link AmqpTransportType */ EventHubClient buildClient() { final EventHubAsyncClient client = buildAsyncClient(); return new EventHubClient(client, retryOptions); } void onClientClose() { synchronized (connectionLock) { final int numberOfOpenClients = openClients.decrementAndGet(); logger.info("Closing a dependent client. if (numberOfOpenClients > 0) { return; } if (numberOfOpenClients < 0) { logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients); } logger.info("No more open clients, closing shared connection."); if (eventHubConnectionProcessor != null) { eventHubConnectionProcessor.dispose(); eventHubConnectionProcessor = null; } else { logger.warning("Shared EventHubConnectionProcessor was already disposed."); } } } private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE); final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> { sink.onRequest(request -> { if (request == 0) { return; } else if (request > 1) { sink.error(logger.logExceptionAsWarning(new IllegalArgumentException( "Requested more than one connection. Only emitting one. Request: " + request))); return; } final String connectionId = StringUtil.getRandomString("MF"); logger.info("connectionId[{}]: Emitting a single connection.", connectionId); final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId, connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider, messageSerializer, product, clientVersion); sink.next(connection); }); }); return connectionFlux.subscribeWith(new EventHubConnectionProcessor( connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; if (credentials == null) { final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(connectionString)) { throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. " + "They can be set using: connectionString(String), connectionString(String, String), " + "credentials(String, String, TokenCredential), or setting the environment variable '" + AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string")); } connectionString(connectionString); } if (proxyOptions == null) { proxyOptions = getDefaultProxyConfiguration(configuration); } if (proxyOptions != null && proxyOptions.isProxyAddressConfigured() && transport != AmqpTransportType.AMQP_WEB_SOCKETS) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot use a proxy when TransportType is not AMQP Web Sockets.")); } final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential ? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE : CbsAuthorizationType.JSON_WEB_TOKEN; return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions, proxyOptions, scheduler); } private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyOptions != null) { authentication = proxyOptions.getAuthentication(); } String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY); if (CoreUtils.isNullOrEmpty(proxyAddress)) { return ProxyOptions.SYSTEM_DEFAULTS; } return getProxyOptions(authentication, proxyAddress); } }
Here and in all the other tests and samples; can we avoid callingModelBridgeInternal.setFeedOptionsMaxItemCount() and instead do the byPage() conversion?
public Mono<Void> readAllAsync(int expectedNumberOfDocuments) { return Mono.defer(() -> { while (true) { int totalItemRead = 0; FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); totalItemRead += response.getResults().size(); } while (response.getContinuationToken() != null); if (totalItemRead < expectedNumberOfDocuments) { logger.info("Total item read {} from {} is less than {}, retrying reads", totalItemRead, this.client.getReadEndpoint(), expectedNumberOfDocuments); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { logger.info("interrupted"); break; } continue; } else { logger.info("READ {} items from {}", totalItemRead, this.client.getReadEndpoint()); break; } } return Mono.empty(); }); }
ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null);
public Mono<Void> readAllAsync(int expectedNumberOfDocuments) { return Mono.defer(() -> { while (true) { int totalItemRead = 0; FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); totalItemRead += response.getResults().size(); } while (response.getContinuationToken() != null); if (totalItemRead < expectedNumberOfDocuments) { logger.info("Total item read {} from {} is less than {}, retrying reads", totalItemRead, this.client.getReadEndpoint(), expectedNumberOfDocuments); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { logger.info("interrupted"); break; } continue; } else { logger.info("READ {} items from {}", totalItemRead, this.client.getReadEndpoint()); break; } } return Mono.empty(); }); }
class Worker { private final static Logger logger = LoggerFactory.getLogger(Worker.class); private final AsyncDocumentClient client; private final String documentCollectionUri; private final Scheduler schedulerForBlockingWork; private final ExecutorService executor; public Worker(AsyncDocumentClient client, String databaseName, String collectionName) { this.client = client; this.documentCollectionUri = String.format("/dbs/%s/colls/%s", databaseName, collectionName); this.executor = Executors.newSingleThreadExecutor(); this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public Mono<Void> runLoopAsync(int documentsToInsert) { return Mono.defer(() -> { int iterationCount = 0; List<Long> latency = new ArrayList<>(); while (iterationCount++ < documentsToInsert) { long startTick = System.currentTimeMillis(); Document d = new Document(); d.setId(UUID.randomUUID().toString()); this.client.createDocument(this.documentCollectionUri, d, null, false) .subscribeOn(schedulerForBlockingWork).single().block(); long endTick = System.currentTimeMillis(); latency.add(endTick - startTick); } Collections.sort(latency); int p50Index = (latency.size() / 2); logger.info("Inserted {} documents at {} with p50 {} ms", documentsToInsert, this.client.getWriteEndpoint(), latency.get(p50Index)); return Mono.empty(); }); } void deleteAll() { List<Document> documents = new ArrayList<>(); FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); documents.addAll(response.getResults()); } while (response.getContinuationToken() != null); for (Document document : documents) { try { this.client.deleteDocument(document.getSelfLink(), null) .subscribeOn(schedulerForBlockingWork).single().block(); } catch (RuntimeException exEx) { CosmosClientException dce = getDocumentClientExceptionCause(exEx); if (dce.getStatusCode() != 404) { logger.info("Error occurred while deleting {} from {}", dce, client.getWriteEndpoint()); } } } logger.info("Deleted all documents from region {}", this.client.getWriteEndpoint()); } private CosmosClientException getDocumentClientExceptionCause(Throwable e) { while (e != null) { if (e instanceof CosmosClientException) { return (CosmosClientException) e; } e = e.getCause(); } return null; } public void shutdown() { executor.shutdown(); client.close(); } }
class Worker { private final static Logger logger = LoggerFactory.getLogger(Worker.class); private final AsyncDocumentClient client; private final String documentCollectionUri; private final Scheduler schedulerForBlockingWork; private final ExecutorService executor; public Worker(AsyncDocumentClient client, String databaseName, String collectionName) { this.client = client; this.documentCollectionUri = String.format("/dbs/%s/colls/%s", databaseName, collectionName); this.executor = Executors.newSingleThreadExecutor(); this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public Mono<Void> runLoopAsync(int documentsToInsert) { return Mono.defer(() -> { int iterationCount = 0; List<Long> latency = new ArrayList<>(); while (iterationCount++ < documentsToInsert) { long startTick = System.currentTimeMillis(); Document d = new Document(); d.setId(UUID.randomUUID().toString()); this.client.createDocument(this.documentCollectionUri, d, null, false) .subscribeOn(schedulerForBlockingWork).single().block(); long endTick = System.currentTimeMillis(); latency.add(endTick - startTick); } Collections.sort(latency); int p50Index = (latency.size() / 2); logger.info("Inserted {} documents at {} with p50 {} ms", documentsToInsert, this.client.getWriteEndpoint(), latency.get(p50Index)); return Mono.empty(); }); } void deleteAll() { List<Document> documents = new ArrayList<>(); FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); documents.addAll(response.getResults()); } while (response.getContinuationToken() != null); for (Document document : documents) { try { this.client.deleteDocument(document.getSelfLink(), null) .subscribeOn(schedulerForBlockingWork).single().block(); } catch (RuntimeException exEx) { CosmosClientException dce = getDocumentClientExceptionCause(exEx); if (dce.getStatusCode() != 404) { logger.info("Error occurred while deleting {} from {}", dce, client.getWriteEndpoint()); } } } logger.info("Deleted all documents from region {}", this.client.getWriteEndpoint()); } private CosmosClientException getDocumentClientExceptionCause(Throwable e) { while (e != null) { if (e instanceof CosmosClientException) { return (CosmosClientException) e; } e = e.getCause(); } return null; } public void shutdown() { executor.shutdown(); client.close(); } }
We cannot, because these ones use `AsyncDocumentClient` - which is an internal type. Public APIs `byPage()` are not available here. So that's why we used ModelBridgeInternal class. See this: https://github.com/Azure/azure-sdk-for-java/pull/10146/files/9c29922a7eea87190f77de4548325a4890364a9b#diff-6ca349d07cccd84853fafeaecacab723R30 But I agree, going forward, we should change the examples itself to use `CosmosClient` and public APIs. But that is a much bigger change across SDK.
public Mono<Void> readAllAsync(int expectedNumberOfDocuments) { return Mono.defer(() -> { while (true) { int totalItemRead = 0; FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); totalItemRead += response.getResults().size(); } while (response.getContinuationToken() != null); if (totalItemRead < expectedNumberOfDocuments) { logger.info("Total item read {} from {} is less than {}, retrying reads", totalItemRead, this.client.getReadEndpoint(), expectedNumberOfDocuments); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { logger.info("interrupted"); break; } continue; } else { logger.info("READ {} items from {}", totalItemRead, this.client.getReadEndpoint()); break; } } return Mono.empty(); }); }
ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null);
public Mono<Void> readAllAsync(int expectedNumberOfDocuments) { return Mono.defer(() -> { while (true) { int totalItemRead = 0; FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); totalItemRead += response.getResults().size(); } while (response.getContinuationToken() != null); if (totalItemRead < expectedNumberOfDocuments) { logger.info("Total item read {} from {} is less than {}, retrying reads", totalItemRead, this.client.getReadEndpoint(), expectedNumberOfDocuments); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { logger.info("interrupted"); break; } continue; } else { logger.info("READ {} items from {}", totalItemRead, this.client.getReadEndpoint()); break; } } return Mono.empty(); }); }
class Worker { private final static Logger logger = LoggerFactory.getLogger(Worker.class); private final AsyncDocumentClient client; private final String documentCollectionUri; private final Scheduler schedulerForBlockingWork; private final ExecutorService executor; public Worker(AsyncDocumentClient client, String databaseName, String collectionName) { this.client = client; this.documentCollectionUri = String.format("/dbs/%s/colls/%s", databaseName, collectionName); this.executor = Executors.newSingleThreadExecutor(); this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public Mono<Void> runLoopAsync(int documentsToInsert) { return Mono.defer(() -> { int iterationCount = 0; List<Long> latency = new ArrayList<>(); while (iterationCount++ < documentsToInsert) { long startTick = System.currentTimeMillis(); Document d = new Document(); d.setId(UUID.randomUUID().toString()); this.client.createDocument(this.documentCollectionUri, d, null, false) .subscribeOn(schedulerForBlockingWork).single().block(); long endTick = System.currentTimeMillis(); latency.add(endTick - startTick); } Collections.sort(latency); int p50Index = (latency.size() / 2); logger.info("Inserted {} documents at {} with p50 {} ms", documentsToInsert, this.client.getWriteEndpoint(), latency.get(p50Index)); return Mono.empty(); }); } void deleteAll() { List<Document> documents = new ArrayList<>(); FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); documents.addAll(response.getResults()); } while (response.getContinuationToken() != null); for (Document document : documents) { try { this.client.deleteDocument(document.getSelfLink(), null) .subscribeOn(schedulerForBlockingWork).single().block(); } catch (RuntimeException exEx) { CosmosClientException dce = getDocumentClientExceptionCause(exEx); if (dce.getStatusCode() != 404) { logger.info("Error occurred while deleting {} from {}", dce, client.getWriteEndpoint()); } } } logger.info("Deleted all documents from region {}", this.client.getWriteEndpoint()); } private CosmosClientException getDocumentClientExceptionCause(Throwable e) { while (e != null) { if (e instanceof CosmosClientException) { return (CosmosClientException) e; } e = e.getCause(); } return null; } public void shutdown() { executor.shutdown(); client.close(); } }
class Worker { private final static Logger logger = LoggerFactory.getLogger(Worker.class); private final AsyncDocumentClient client; private final String documentCollectionUri; private final Scheduler schedulerForBlockingWork; private final ExecutorService executor; public Worker(AsyncDocumentClient client, String databaseName, String collectionName) { this.client = client; this.documentCollectionUri = String.format("/dbs/%s/colls/%s", databaseName, collectionName); this.executor = Executors.newSingleThreadExecutor(); this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public Mono<Void> runLoopAsync(int documentsToInsert) { return Mono.defer(() -> { int iterationCount = 0; List<Long> latency = new ArrayList<>(); while (iterationCount++ < documentsToInsert) { long startTick = System.currentTimeMillis(); Document d = new Document(); d.setId(UUID.randomUUID().toString()); this.client.createDocument(this.documentCollectionUri, d, null, false) .subscribeOn(schedulerForBlockingWork).single().block(); long endTick = System.currentTimeMillis(); latency.add(endTick - startTick); } Collections.sort(latency); int p50Index = (latency.size() / 2); logger.info("Inserted {} documents at {} with p50 {} ms", documentsToInsert, this.client.getWriteEndpoint(), latency.get(p50Index)); return Mono.empty(); }); } void deleteAll() { List<Document> documents = new ArrayList<>(); FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); documents.addAll(response.getResults()); } while (response.getContinuationToken() != null); for (Document document : documents) { try { this.client.deleteDocument(document.getSelfLink(), null) .subscribeOn(schedulerForBlockingWork).single().block(); } catch (RuntimeException exEx) { CosmosClientException dce = getDocumentClientExceptionCause(exEx); if (dce.getStatusCode() != 404) { logger.info("Error occurred while deleting {} from {}", dce, client.getWriteEndpoint()); } } } logger.info("Deleted all documents from region {}", this.client.getWriteEndpoint()); } private CosmosClientException getDocumentClientExceptionCause(Throwable e) { while (e != null) { if (e instanceof CosmosClientException) { return (CosmosClientException) e; } e = e.getCause(); } return null; } public void shutdown() { executor.shutdown(); client.close(); } }
understood
public Mono<Void> readAllAsync(int expectedNumberOfDocuments) { return Mono.defer(() -> { while (true) { int totalItemRead = 0; FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); totalItemRead += response.getResults().size(); } while (response.getContinuationToken() != null); if (totalItemRead < expectedNumberOfDocuments) { logger.info("Total item read {} from {} is less than {}, retrying reads", totalItemRead, this.client.getReadEndpoint(), expectedNumberOfDocuments); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { logger.info("interrupted"); break; } continue; } else { logger.info("READ {} items from {}", totalItemRead, this.client.getReadEndpoint()); break; } } return Mono.empty(); }); }
ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null);
public Mono<Void> readAllAsync(int expectedNumberOfDocuments) { return Mono.defer(() -> { while (true) { int totalItemRead = 0; FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); totalItemRead += response.getResults().size(); } while (response.getContinuationToken() != null); if (totalItemRead < expectedNumberOfDocuments) { logger.info("Total item read {} from {} is less than {}, retrying reads", totalItemRead, this.client.getReadEndpoint(), expectedNumberOfDocuments); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { logger.info("interrupted"); break; } continue; } else { logger.info("READ {} items from {}", totalItemRead, this.client.getReadEndpoint()); break; } } return Mono.empty(); }); }
class Worker { private final static Logger logger = LoggerFactory.getLogger(Worker.class); private final AsyncDocumentClient client; private final String documentCollectionUri; private final Scheduler schedulerForBlockingWork; private final ExecutorService executor; public Worker(AsyncDocumentClient client, String databaseName, String collectionName) { this.client = client; this.documentCollectionUri = String.format("/dbs/%s/colls/%s", databaseName, collectionName); this.executor = Executors.newSingleThreadExecutor(); this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public Mono<Void> runLoopAsync(int documentsToInsert) { return Mono.defer(() -> { int iterationCount = 0; List<Long> latency = new ArrayList<>(); while (iterationCount++ < documentsToInsert) { long startTick = System.currentTimeMillis(); Document d = new Document(); d.setId(UUID.randomUUID().toString()); this.client.createDocument(this.documentCollectionUri, d, null, false) .subscribeOn(schedulerForBlockingWork).single().block(); long endTick = System.currentTimeMillis(); latency.add(endTick - startTick); } Collections.sort(latency); int p50Index = (latency.size() / 2); logger.info("Inserted {} documents at {} with p50 {} ms", documentsToInsert, this.client.getWriteEndpoint(), latency.get(p50Index)); return Mono.empty(); }); } void deleteAll() { List<Document> documents = new ArrayList<>(); FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); documents.addAll(response.getResults()); } while (response.getContinuationToken() != null); for (Document document : documents) { try { this.client.deleteDocument(document.getSelfLink(), null) .subscribeOn(schedulerForBlockingWork).single().block(); } catch (RuntimeException exEx) { CosmosClientException dce = getDocumentClientExceptionCause(exEx); if (dce.getStatusCode() != 404) { logger.info("Error occurred while deleting {} from {}", dce, client.getWriteEndpoint()); } } } logger.info("Deleted all documents from region {}", this.client.getWriteEndpoint()); } private CosmosClientException getDocumentClientExceptionCause(Throwable e) { while (e != null) { if (e instanceof CosmosClientException) { return (CosmosClientException) e; } e = e.getCause(); } return null; } public void shutdown() { executor.shutdown(); client.close(); } }
class Worker { private final static Logger logger = LoggerFactory.getLogger(Worker.class); private final AsyncDocumentClient client; private final String documentCollectionUri; private final Scheduler schedulerForBlockingWork; private final ExecutorService executor; public Worker(AsyncDocumentClient client, String databaseName, String collectionName) { this.client = client; this.documentCollectionUri = String.format("/dbs/%s/colls/%s", databaseName, collectionName); this.executor = Executors.newSingleThreadExecutor(); this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public Mono<Void> runLoopAsync(int documentsToInsert) { return Mono.defer(() -> { int iterationCount = 0; List<Long> latency = new ArrayList<>(); while (iterationCount++ < documentsToInsert) { long startTick = System.currentTimeMillis(); Document d = new Document(); d.setId(UUID.randomUUID().toString()); this.client.createDocument(this.documentCollectionUri, d, null, false) .subscribeOn(schedulerForBlockingWork).single().block(); long endTick = System.currentTimeMillis(); latency.add(endTick - startTick); } Collections.sort(latency); int p50Index = (latency.size() / 2); logger.info("Inserted {} documents at {} with p50 {} ms", documentsToInsert, this.client.getWriteEndpoint(), latency.get(p50Index)); return Mono.empty(); }); } void deleteAll() { List<Document> documents = new ArrayList<>(); FeedResponse<Document> response = null; do { FeedOptions options = new FeedOptions(); ModelBridgeInternal.setFeedOptionsContinuationToken(options, response != null ? response.getContinuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).take(1) .subscribeOn(schedulerForBlockingWork).single().block(); documents.addAll(response.getResults()); } while (response.getContinuationToken() != null); for (Document document : documents) { try { this.client.deleteDocument(document.getSelfLink(), null) .subscribeOn(schedulerForBlockingWork).single().block(); } catch (RuntimeException exEx) { CosmosClientException dce = getDocumentClientExceptionCause(exEx); if (dce.getStatusCode() != 404) { logger.info("Error occurred while deleting {} from {}", dce, client.getWriteEndpoint()); } } } logger.info("Deleted all documents from region {}", this.client.getWriteEndpoint()); } private CosmosClientException getDocumentClientExceptionCause(Throwable e) { while (e != null) { if (e instanceof CosmosClientException) { return (CosmosClientException) e; } e = e.getCause(); } return null; } public void shutdown() { executor.shutdown(); client.close(); } }
This would be easier to understand if you do: ```java if (this.hidden != null) { this.retrievable = !this.hidden; } ``` Shouldn't the retrievable logic be done after setting the member variable? not before?
public Field setHidden(Boolean hidden) { retrievable = this.hidden == null ? null : !this.hidden; this.hidden = hidden; return this; }
retrievable = this.hidden == null ? null : !this.hidden;
public Field setHidden(Boolean hidden) { this.hidden = hidden; retrievable = this.hidden == null ? null : !this.hidden; return this; }
class Field { /* * The name of the field, which must be unique within the fields collection * of the index or parent field. */ @JsonProperty(value = "name", required = true) private String name; /* * The data type of the field. Possible values include: 'Edm.String', * 'Edm.Int32', 'Edm.Int64', 'Edm.Double', 'Edm.Boolean', * 'Edm.DateTimeOffset', 'Edm.GeographyPoint', 'Edm.ComplexType' */ @JsonProperty(value = "type", required = true) private DataType type; /* * A value indicating whether the field uniquely identifies documents in * the index. Exactly one top-level field in each index must be chosen as * the key field and it must be of type Edm.String. Key fields can be used * to look up documents directly and update or delete specific documents. * Default is false for simple fields and null for complex fields. */ @JsonProperty(value = "key") private Boolean key; /* * A value indicating whether the field can be returned in a search result. * You can disable this option if you want to use a field (for example, * margin) as a filter, sorting, or scoring mechanism but do not want the * field to be visible to the end user. This property must be true for key * fields, and it must be null for complex fields. This property can be * changed on existing fields. Enabling this property does not cause any * increase in index storage requirements. Default is true for simple * fields and null for complex fields. */ @JsonProperty(value = "retrievable") private Boolean retrievable; /* * A value indicating whether the field is full-text searchable. This means * it will undergo analysis such as word-breaking during indexing. If you * set a searchable field to a value like "sunny day", internally it will * be split into the individual tokens "sunny" and "day". This enables * full-text searches for these terms. Fields of type Edm.String or * Collection(Edm.String) are searchable by default. This property must be * false for simple fields of other non-string data types, and it must be * null for complex fields. Note: searchable fields consume extra space in * your index since Azure Cognitive Search will store an additional * tokenized version of the field value for full-text searches. If you want * to save space in your index and you don't need a field to be included in * searches, set searchable to false. */ @JsonProperty(value = "searchable") private Boolean searchable; /* * A value indicating whether to enable the field to be referenced in * $filter queries. filterable differs from searchable in how strings are * handled. Fields of type Edm.String or Collection(Edm.String) that are * filterable do not undergo word-breaking, so comparisons are for exact * matches only. For example, if you set such a field f to "sunny day", * $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' * will. This property must be null for complex fields. Default is true for * simple fields and null for complex fields. */ @JsonProperty(value = "filterable") private Boolean filterable; /* * A value indicating whether to enable the field to be referenced in * $orderby expressions. By default Azure Cognitive Search sorts results by * score, but in many experiences users will want to sort by fields in the * documents. A simple field can be sortable only if it is single-valued * (it has a single value in the scope of the parent document). Simple * collection fields cannot be sortable, since they are multi-valued. * Simple sub-fields of complex collections are also multi-valued, and * therefore cannot be sortable. This is true whether it's an immediate * parent field, or an ancestor field, that's the complex collection. * Complex fields cannot be sortable and the sortable property must be null * for such fields. The default for sortable is true for single-valued * simple fields, false for multi-valued simple fields, and null for * complex fields. */ @JsonProperty(value = "sortable") private Boolean sortable; /* * A value indicating whether to enable the field to be referenced in facet * queries. Typically used in a presentation of search results that * includes hit count by category (for example, search for digital cameras * and see hits by brand, by megapixels, by price, and so on). This * property must be null for complex fields. Fields of type * Edm.GeographyPoint or Collection(Edm.GeographyPoint) cannot be * facetable. Default is true for all other simple fields. */ @JsonProperty(value = "facetable") private Boolean facetable; /* * The name of the analyzer to use for the field. This option can be used * only with searchable fields and it can't be set together with either * searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot * be changed for the field. Must be null for complex fields. Possible * values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', 'BnMicrosoft', * 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', 'CaLucene', * 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', * 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', * 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', * 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', * 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', * 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', * 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', * 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', * 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', * 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', * 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "analyzer") private AnalyzerName analyzer; /* * The name of the analyzer used at search time for the field. This option * can be used only with searchable fields. It must be set together with * indexAnalyzer and it cannot be set together with the analyzer option. * This property cannot be set to the name of a language analyzer; use the * analyzer property instead if you need a language analyzer. This analyzer * can be updated on an existing field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "searchAnalyzer") private AnalyzerName searchAnalyzer; /* * The name of the analyzer used at indexing time for the field. This * option can be used only with searchable fields. It must be set together * with searchAnalyzer and it cannot be set together with the analyzer * option. This property cannot be set to the name of a language analyzer; * use the analyzer property instead if you need a language analyzer. Once * the analyzer is chosen, it cannot be changed for the field. Must be null * for complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace' */ @JsonProperty(value = "indexAnalyzer") private AnalyzerName indexAnalyzer; /* * A list of the names of synonym maps to associate with this field. This * option can be used only with searchable fields. Currently only one * synonym map per field is supported. Assigning a synonym map to a field * ensures that query terms targeting that field are expanded at query-time * using the rules in the synonym map. This attribute can be changed on * existing fields. Must be null or an empty collection for complex fields. */ @JsonProperty(value = "synonymMaps") private List<String> synonymMaps; /* * A list of sub-fields if this is a field of type Edm.ComplexType or * Collection(Edm.ComplexType). Must be null or empty for simple fields. */ @JsonProperty(value = "fields") private List<Field> fields; /* * A value indicating whether the field will be returned in a search * result. This property must be false for key fields, and must be null for * complex fields. You can hide a field from search results if you want to * use it only as a filter, for sorting, or for scoring. This property can * also be changed on existing fields and enabling it does not cause an * increase in index storage requirements. */ @JsonIgnore private Boolean hidden; /** * Get the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @param name the name value to set. * @return the Field object itself. */ public Field setName(String name) { this.name = name; return this; } /** * Get the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @return the type value. */ public DataType getType() { return this.type; } /** * Set the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @param type the type value to set. * @return the Field object itself. */ public Field setType(DataType type) { this.type = type; return this; } /** * Get the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @return the key value. */ public Boolean isKey() { return this.key; } /** * Set the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @param key the key value to set. * @return the Field object itself. */ public Field setKey(Boolean key) { this.key = key; return this; } /** * Get the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @return the retrievable value. */ private Boolean isRetrievable() { return this.retrievable; } /** * Set the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @param retrievable the retrievable value to set. * @return the Field object itself. */ private Field setRetrievable(Boolean retrievable) { this.retrievable = retrievable; return this; } /** * Get the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @return the searchable value. */ public Boolean isSearchable() { return this.searchable; } /** * Set the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @param searchable the searchable value to set. * @return the Field object itself. */ public Field setSearchable(Boolean searchable) { this.searchable = searchable; return this; } /** * Get the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @return the filterable value. */ public Boolean isFilterable() { return this.filterable; } /** * Set the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @param filterable the filterable value to set. * @return the Field object itself. */ public Field setFilterable(Boolean filterable) { this.filterable = filterable; return this; } /** * Get the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @return the sortable value. */ public Boolean isSortable() { return this.sortable; } /** * Set the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @param sortable the sortable value to set. * @return the Field object itself. */ public Field setSortable(Boolean sortable) { this.sortable = sortable; return this; } /** * Get the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @return the facetable value. */ public Boolean isFacetable() { return this.facetable; } /** * Set the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @param facetable the facetable value to set. * @return the Field object itself. */ public Field setFacetable(Boolean facetable) { this.facetable = facetable; return this; } /** * Get the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @return the analyzer value. */ public AnalyzerName getAnalyzer() { return this.analyzer; } /** * Set the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @param analyzer the analyzer value to set. * @return the Field object itself. */ public Field setAnalyzer(AnalyzerName analyzer) { this.analyzer = analyzer; return this; } /** * Get the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the searchAnalyzer value. */ public AnalyzerName getSearchAnalyzer() { return this.searchAnalyzer; } /** * Set the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param searchAnalyzer the searchAnalyzer value to set. * @return the Field object itself. */ public Field setSearchAnalyzer(AnalyzerName searchAnalyzer) { this.searchAnalyzer = searchAnalyzer; return this; } /** * Get the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the indexAnalyzer value. */ public AnalyzerName getIndexAnalyzer() { return this.indexAnalyzer; } /** * Set the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param indexAnalyzer the indexAnalyzer value to set. * @return the Field object itself. */ public Field setIndexAnalyzer(AnalyzerName indexAnalyzer) { this.indexAnalyzer = indexAnalyzer; return this; } /** * Get the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @return the synonymMaps value. */ public List<String> getSynonymMaps() { return this.synonymMaps; } /** * Set the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @param synonymMaps the synonymMaps value to set. * @return the Field object itself. */ public Field setSynonymMaps(List<String> synonymMaps) { this.synonymMaps = synonymMaps; return this; } /** * Get the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @return the fields value. */ public List<Field> getFields() { return this.fields; } /** * Set the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @param fields the fields value to set. * @return the Field object itself. */ public Field setFields(List<Field> fields) { this.fields = fields; return this; } /** * Get the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @return the hidden value. */ public Boolean isHidden() { return retrievable == null ? null : !retrievable; } /** * Set the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @param hidden the hidden value to set. * @return the Field object itself. */ }
class Field { /* * The name of the field, which must be unique within the fields collection * of the index or parent field. */ @JsonProperty(value = "name", required = true) private String name; /* * The data type of the field. Possible values include: 'Edm.String', * 'Edm.Int32', 'Edm.Int64', 'Edm.Double', 'Edm.Boolean', * 'Edm.DateTimeOffset', 'Edm.GeographyPoint', 'Edm.ComplexType' */ @JsonProperty(value = "type", required = true) private DataType type; /* * A value indicating whether the field uniquely identifies documents in * the index. Exactly one top-level field in each index must be chosen as * the key field and it must be of type Edm.String. Key fields can be used * to look up documents directly and update or delete specific documents. * Default is false for simple fields and null for complex fields. */ @JsonProperty(value = "key") private Boolean key; /* * A value indicating whether the field can be returned in a search result. * You can disable this option if you want to use a field (for example, * margin) as a filter, sorting, or scoring mechanism but do not want the * field to be visible to the end user. This property must be true for key * fields, and it must be null for complex fields. This property can be * changed on existing fields. Enabling this property does not cause any * increase in index storage requirements. Default is true for simple * fields and null for complex fields. */ @JsonProperty(value = "retrievable") private Boolean retrievable; /* * A value indicating whether the field is full-text searchable. This means * it will undergo analysis such as word-breaking during indexing. If you * set a searchable field to a value like "sunny day", internally it will * be split into the individual tokens "sunny" and "day". This enables * full-text searches for these terms. Fields of type Edm.String or * Collection(Edm.String) are searchable by default. This property must be * false for simple fields of other non-string data types, and it must be * null for complex fields. Note: searchable fields consume extra space in * your index since Azure Cognitive Search will store an additional * tokenized version of the field value for full-text searches. If you want * to save space in your index and you don't need a field to be included in * searches, set searchable to false. */ @JsonProperty(value = "searchable") private Boolean searchable; /* * A value indicating whether to enable the field to be referenced in * $filter queries. filterable differs from searchable in how strings are * handled. Fields of type Edm.String or Collection(Edm.String) that are * filterable do not undergo word-breaking, so comparisons are for exact * matches only. For example, if you set such a field f to "sunny day", * $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' * will. This property must be null for complex fields. Default is true for * simple fields and null for complex fields. */ @JsonProperty(value = "filterable") private Boolean filterable; /* * A value indicating whether to enable the field to be referenced in * $orderby expressions. By default Azure Cognitive Search sorts results by * score, but in many experiences users will want to sort by fields in the * documents. A simple field can be sortable only if it is single-valued * (it has a single value in the scope of the parent document). Simple * collection fields cannot be sortable, since they are multi-valued. * Simple sub-fields of complex collections are also multi-valued, and * therefore cannot be sortable. This is true whether it's an immediate * parent field, or an ancestor field, that's the complex collection. * Complex fields cannot be sortable and the sortable property must be null * for such fields. The default for sortable is true for single-valued * simple fields, false for multi-valued simple fields, and null for * complex fields. */ @JsonProperty(value = "sortable") private Boolean sortable; /* * A value indicating whether to enable the field to be referenced in facet * queries. Typically used in a presentation of search results that * includes hit count by category (for example, search for digital cameras * and see hits by brand, by megapixels, by price, and so on). This * property must be null for complex fields. Fields of type * Edm.GeographyPoint or Collection(Edm.GeographyPoint) cannot be * facetable. Default is true for all other simple fields. */ @JsonProperty(value = "facetable") private Boolean facetable; /* * The name of the analyzer to use for the field. This option can be used * only with searchable fields and it can't be set together with either * searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot * be changed for the field. Must be null for complex fields. Possible * values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', 'BnMicrosoft', * 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', 'CaLucene', * 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', * 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', * 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', * 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', * 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', * 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', * 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', * 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', * 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', * 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', * 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "analyzer") private AnalyzerName analyzer; /* * The name of the analyzer used at search time for the field. This option * can be used only with searchable fields. It must be set together with * indexAnalyzer and it cannot be set together with the analyzer option. * This property cannot be set to the name of a language analyzer; use the * analyzer property instead if you need a language analyzer. This analyzer * can be updated on an existing field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "searchAnalyzer") private AnalyzerName searchAnalyzer; /* * The name of the analyzer used at indexing time for the field. This * option can be used only with searchable fields. It must be set together * with searchAnalyzer and it cannot be set together with the analyzer * option. This property cannot be set to the name of a language analyzer; * use the analyzer property instead if you need a language analyzer. Once * the analyzer is chosen, it cannot be changed for the field. Must be null * for complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace' */ @JsonProperty(value = "indexAnalyzer") private AnalyzerName indexAnalyzer; /* * A list of the names of synonym maps to associate with this field. This * option can be used only with searchable fields. Currently only one * synonym map per field is supported. Assigning a synonym map to a field * ensures that query terms targeting that field are expanded at query-time * using the rules in the synonym map. This attribute can be changed on * existing fields. Must be null or an empty collection for complex fields. */ @JsonProperty(value = "synonymMaps") private List<String> synonymMaps; /* * A list of sub-fields if this is a field of type Edm.ComplexType or * Collection(Edm.ComplexType). Must be null or empty for simple fields. */ @JsonProperty(value = "fields") private List<Field> fields; /* * A value indicating whether the field will be returned in a search * result. This property must be false for key fields, and must be null for * complex fields. You can hide a field from search results if you want to * use it only as a filter, for sorting, or for scoring. This property can * also be changed on existing fields and enabling it does not cause an * increase in index storage requirements. */ @JsonIgnore private Boolean hidden; /** * Get the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @param name the name value to set. * @return the Field object itself. */ public Field setName(String name) { this.name = name; return this; } /** * Get the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @return the type value. */ public DataType getType() { return this.type; } /** * Set the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @param type the type value to set. * @return the Field object itself. */ public Field setType(DataType type) { this.type = type; return this; } /** * Get the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @return the key value. */ public Boolean isKey() { return this.key; } /** * Set the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @param key the key value to set. * @return the Field object itself. */ public Field setKey(Boolean key) { this.key = key; return this; } /** * Get the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @return the retrievable value. */ private Boolean isRetrievable() { return this.retrievable; } /** * Set the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @param retrievable the retrievable value to set. * @return the Field object itself. */ private Field setRetrievable(Boolean retrievable) { this.retrievable = retrievable; return this; } /** * Get the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @return the searchable value. */ public Boolean isSearchable() { return this.searchable; } /** * Set the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @param searchable the searchable value to set. * @return the Field object itself. */ public Field setSearchable(Boolean searchable) { this.searchable = searchable; return this; } /** * Get the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @return the filterable value. */ public Boolean isFilterable() { return this.filterable; } /** * Set the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @param filterable the filterable value to set. * @return the Field object itself. */ public Field setFilterable(Boolean filterable) { this.filterable = filterable; return this; } /** * Get the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @return the sortable value. */ public Boolean isSortable() { return this.sortable; } /** * Set the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @param sortable the sortable value to set. * @return the Field object itself. */ public Field setSortable(Boolean sortable) { this.sortable = sortable; return this; } /** * Get the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @return the facetable value. */ public Boolean isFacetable() { return this.facetable; } /** * Set the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @param facetable the facetable value to set. * @return the Field object itself. */ public Field setFacetable(Boolean facetable) { this.facetable = facetable; return this; } /** * Get the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @return the analyzer value. */ public AnalyzerName getAnalyzer() { return this.analyzer; } /** * Set the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @param analyzer the analyzer value to set. * @return the Field object itself. */ public Field setAnalyzer(AnalyzerName analyzer) { this.analyzer = analyzer; return this; } /** * Get the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the searchAnalyzer value. */ public AnalyzerName getSearchAnalyzer() { return this.searchAnalyzer; } /** * Set the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param searchAnalyzer the searchAnalyzer value to set. * @return the Field object itself. */ public Field setSearchAnalyzer(AnalyzerName searchAnalyzer) { this.searchAnalyzer = searchAnalyzer; return this; } /** * Get the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the indexAnalyzer value. */ public AnalyzerName getIndexAnalyzer() { return this.indexAnalyzer; } /** * Set the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param indexAnalyzer the indexAnalyzer value to set. * @return the Field object itself. */ public Field setIndexAnalyzer(AnalyzerName indexAnalyzer) { this.indexAnalyzer = indexAnalyzer; return this; } /** * Get the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @return the synonymMaps value. */ public List<String> getSynonymMaps() { return this.synonymMaps; } /** * Set the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @param synonymMaps the synonymMaps value to set. * @return the Field object itself. */ public Field setSynonymMaps(List<String> synonymMaps) { this.synonymMaps = synonymMaps; return this; } /** * Get the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @return the fields value. */ public List<Field> getFields() { return this.fields; } /** * Set the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @param fields the fields value to set. * @return the Field object itself. */ public Field setFields(List<Field> fields) { this.fields = fields; return this; } /** * Get the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @return the hidden value. */ public Boolean isHidden() { return retrievable == null ? null : !retrievable; } /** * Set the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @param hidden the hidden value to set. * @return the Field object itself. */ }
setHidden is the only entry to set `retrievable` field. The logic needs to change to ``` if (hidden != null) { this.retrievable = !hidden; } this.hidden = hidden; ``` Good catch
public Field setHidden(Boolean hidden) { retrievable = this.hidden == null ? null : !this.hidden; this.hidden = hidden; return this; }
retrievable = this.hidden == null ? null : !this.hidden;
public Field setHidden(Boolean hidden) { this.hidden = hidden; retrievable = this.hidden == null ? null : !this.hidden; return this; }
class Field { /* * The name of the field, which must be unique within the fields collection * of the index or parent field. */ @JsonProperty(value = "name", required = true) private String name; /* * The data type of the field. Possible values include: 'Edm.String', * 'Edm.Int32', 'Edm.Int64', 'Edm.Double', 'Edm.Boolean', * 'Edm.DateTimeOffset', 'Edm.GeographyPoint', 'Edm.ComplexType' */ @JsonProperty(value = "type", required = true) private DataType type; /* * A value indicating whether the field uniquely identifies documents in * the index. Exactly one top-level field in each index must be chosen as * the key field and it must be of type Edm.String. Key fields can be used * to look up documents directly and update or delete specific documents. * Default is false for simple fields and null for complex fields. */ @JsonProperty(value = "key") private Boolean key; /* * A value indicating whether the field can be returned in a search result. * You can disable this option if you want to use a field (for example, * margin) as a filter, sorting, or scoring mechanism but do not want the * field to be visible to the end user. This property must be true for key * fields, and it must be null for complex fields. This property can be * changed on existing fields. Enabling this property does not cause any * increase in index storage requirements. Default is true for simple * fields and null for complex fields. */ @JsonProperty(value = "retrievable") private Boolean retrievable; /* * A value indicating whether the field is full-text searchable. This means * it will undergo analysis such as word-breaking during indexing. If you * set a searchable field to a value like "sunny day", internally it will * be split into the individual tokens "sunny" and "day". This enables * full-text searches for these terms. Fields of type Edm.String or * Collection(Edm.String) are searchable by default. This property must be * false for simple fields of other non-string data types, and it must be * null for complex fields. Note: searchable fields consume extra space in * your index since Azure Cognitive Search will store an additional * tokenized version of the field value for full-text searches. If you want * to save space in your index and you don't need a field to be included in * searches, set searchable to false. */ @JsonProperty(value = "searchable") private Boolean searchable; /* * A value indicating whether to enable the field to be referenced in * $filter queries. filterable differs from searchable in how strings are * handled. Fields of type Edm.String or Collection(Edm.String) that are * filterable do not undergo word-breaking, so comparisons are for exact * matches only. For example, if you set such a field f to "sunny day", * $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' * will. This property must be null for complex fields. Default is true for * simple fields and null for complex fields. */ @JsonProperty(value = "filterable") private Boolean filterable; /* * A value indicating whether to enable the field to be referenced in * $orderby expressions. By default Azure Cognitive Search sorts results by * score, but in many experiences users will want to sort by fields in the * documents. A simple field can be sortable only if it is single-valued * (it has a single value in the scope of the parent document). Simple * collection fields cannot be sortable, since they are multi-valued. * Simple sub-fields of complex collections are also multi-valued, and * therefore cannot be sortable. This is true whether it's an immediate * parent field, or an ancestor field, that's the complex collection. * Complex fields cannot be sortable and the sortable property must be null * for such fields. The default for sortable is true for single-valued * simple fields, false for multi-valued simple fields, and null for * complex fields. */ @JsonProperty(value = "sortable") private Boolean sortable; /* * A value indicating whether to enable the field to be referenced in facet * queries. Typically used in a presentation of search results that * includes hit count by category (for example, search for digital cameras * and see hits by brand, by megapixels, by price, and so on). This * property must be null for complex fields. Fields of type * Edm.GeographyPoint or Collection(Edm.GeographyPoint) cannot be * facetable. Default is true for all other simple fields. */ @JsonProperty(value = "facetable") private Boolean facetable; /* * The name of the analyzer to use for the field. This option can be used * only with searchable fields and it can't be set together with either * searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot * be changed for the field. Must be null for complex fields. Possible * values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', 'BnMicrosoft', * 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', 'CaLucene', * 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', * 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', * 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', * 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', * 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', * 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', * 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', * 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', * 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', * 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', * 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "analyzer") private AnalyzerName analyzer; /* * The name of the analyzer used at search time for the field. This option * can be used only with searchable fields. It must be set together with * indexAnalyzer and it cannot be set together with the analyzer option. * This property cannot be set to the name of a language analyzer; use the * analyzer property instead if you need a language analyzer. This analyzer * can be updated on an existing field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "searchAnalyzer") private AnalyzerName searchAnalyzer; /* * The name of the analyzer used at indexing time for the field. This * option can be used only with searchable fields. It must be set together * with searchAnalyzer and it cannot be set together with the analyzer * option. This property cannot be set to the name of a language analyzer; * use the analyzer property instead if you need a language analyzer. Once * the analyzer is chosen, it cannot be changed for the field. Must be null * for complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace' */ @JsonProperty(value = "indexAnalyzer") private AnalyzerName indexAnalyzer; /* * A list of the names of synonym maps to associate with this field. This * option can be used only with searchable fields. Currently only one * synonym map per field is supported. Assigning a synonym map to a field * ensures that query terms targeting that field are expanded at query-time * using the rules in the synonym map. This attribute can be changed on * existing fields. Must be null or an empty collection for complex fields. */ @JsonProperty(value = "synonymMaps") private List<String> synonymMaps; /* * A list of sub-fields if this is a field of type Edm.ComplexType or * Collection(Edm.ComplexType). Must be null or empty for simple fields. */ @JsonProperty(value = "fields") private List<Field> fields; /* * A value indicating whether the field will be returned in a search * result. This property must be false for key fields, and must be null for * complex fields. You can hide a field from search results if you want to * use it only as a filter, for sorting, or for scoring. This property can * also be changed on existing fields and enabling it does not cause an * increase in index storage requirements. */ @JsonIgnore private Boolean hidden; /** * Get the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @param name the name value to set. * @return the Field object itself. */ public Field setName(String name) { this.name = name; return this; } /** * Get the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @return the type value. */ public DataType getType() { return this.type; } /** * Set the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @param type the type value to set. * @return the Field object itself. */ public Field setType(DataType type) { this.type = type; return this; } /** * Get the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @return the key value. */ public Boolean isKey() { return this.key; } /** * Set the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @param key the key value to set. * @return the Field object itself. */ public Field setKey(Boolean key) { this.key = key; return this; } /** * Get the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @return the retrievable value. */ private Boolean isRetrievable() { return this.retrievable; } /** * Set the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @param retrievable the retrievable value to set. * @return the Field object itself. */ private Field setRetrievable(Boolean retrievable) { this.retrievable = retrievable; return this; } /** * Get the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @return the searchable value. */ public Boolean isSearchable() { return this.searchable; } /** * Set the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @param searchable the searchable value to set. * @return the Field object itself. */ public Field setSearchable(Boolean searchable) { this.searchable = searchable; return this; } /** * Get the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @return the filterable value. */ public Boolean isFilterable() { return this.filterable; } /** * Set the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @param filterable the filterable value to set. * @return the Field object itself. */ public Field setFilterable(Boolean filterable) { this.filterable = filterable; return this; } /** * Get the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @return the sortable value. */ public Boolean isSortable() { return this.sortable; } /** * Set the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @param sortable the sortable value to set. * @return the Field object itself. */ public Field setSortable(Boolean sortable) { this.sortable = sortable; return this; } /** * Get the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @return the facetable value. */ public Boolean isFacetable() { return this.facetable; } /** * Set the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @param facetable the facetable value to set. * @return the Field object itself. */ public Field setFacetable(Boolean facetable) { this.facetable = facetable; return this; } /** * Get the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @return the analyzer value. */ public AnalyzerName getAnalyzer() { return this.analyzer; } /** * Set the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @param analyzer the analyzer value to set. * @return the Field object itself. */ public Field setAnalyzer(AnalyzerName analyzer) { this.analyzer = analyzer; return this; } /** * Get the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the searchAnalyzer value. */ public AnalyzerName getSearchAnalyzer() { return this.searchAnalyzer; } /** * Set the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param searchAnalyzer the searchAnalyzer value to set. * @return the Field object itself. */ public Field setSearchAnalyzer(AnalyzerName searchAnalyzer) { this.searchAnalyzer = searchAnalyzer; return this; } /** * Get the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the indexAnalyzer value. */ public AnalyzerName getIndexAnalyzer() { return this.indexAnalyzer; } /** * Set the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param indexAnalyzer the indexAnalyzer value to set. * @return the Field object itself. */ public Field setIndexAnalyzer(AnalyzerName indexAnalyzer) { this.indexAnalyzer = indexAnalyzer; return this; } /** * Get the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @return the synonymMaps value. */ public List<String> getSynonymMaps() { return this.synonymMaps; } /** * Set the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @param synonymMaps the synonymMaps value to set. * @return the Field object itself. */ public Field setSynonymMaps(List<String> synonymMaps) { this.synonymMaps = synonymMaps; return this; } /** * Get the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @return the fields value. */ public List<Field> getFields() { return this.fields; } /** * Set the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @param fields the fields value to set. * @return the Field object itself. */ public Field setFields(List<Field> fields) { this.fields = fields; return this; } /** * Get the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @return the hidden value. */ public Boolean isHidden() { return retrievable == null ? null : !retrievable; } /** * Set the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @param hidden the hidden value to set. * @return the Field object itself. */ }
class Field { /* * The name of the field, which must be unique within the fields collection * of the index or parent field. */ @JsonProperty(value = "name", required = true) private String name; /* * The data type of the field. Possible values include: 'Edm.String', * 'Edm.Int32', 'Edm.Int64', 'Edm.Double', 'Edm.Boolean', * 'Edm.DateTimeOffset', 'Edm.GeographyPoint', 'Edm.ComplexType' */ @JsonProperty(value = "type", required = true) private DataType type; /* * A value indicating whether the field uniquely identifies documents in * the index. Exactly one top-level field in each index must be chosen as * the key field and it must be of type Edm.String. Key fields can be used * to look up documents directly and update or delete specific documents. * Default is false for simple fields and null for complex fields. */ @JsonProperty(value = "key") private Boolean key; /* * A value indicating whether the field can be returned in a search result. * You can disable this option if you want to use a field (for example, * margin) as a filter, sorting, or scoring mechanism but do not want the * field to be visible to the end user. This property must be true for key * fields, and it must be null for complex fields. This property can be * changed on existing fields. Enabling this property does not cause any * increase in index storage requirements. Default is true for simple * fields and null for complex fields. */ @JsonProperty(value = "retrievable") private Boolean retrievable; /* * A value indicating whether the field is full-text searchable. This means * it will undergo analysis such as word-breaking during indexing. If you * set a searchable field to a value like "sunny day", internally it will * be split into the individual tokens "sunny" and "day". This enables * full-text searches for these terms. Fields of type Edm.String or * Collection(Edm.String) are searchable by default. This property must be * false for simple fields of other non-string data types, and it must be * null for complex fields. Note: searchable fields consume extra space in * your index since Azure Cognitive Search will store an additional * tokenized version of the field value for full-text searches. If you want * to save space in your index and you don't need a field to be included in * searches, set searchable to false. */ @JsonProperty(value = "searchable") private Boolean searchable; /* * A value indicating whether to enable the field to be referenced in * $filter queries. filterable differs from searchable in how strings are * handled. Fields of type Edm.String or Collection(Edm.String) that are * filterable do not undergo word-breaking, so comparisons are for exact * matches only. For example, if you set such a field f to "sunny day", * $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' * will. This property must be null for complex fields. Default is true for * simple fields and null for complex fields. */ @JsonProperty(value = "filterable") private Boolean filterable; /* * A value indicating whether to enable the field to be referenced in * $orderby expressions. By default Azure Cognitive Search sorts results by * score, but in many experiences users will want to sort by fields in the * documents. A simple field can be sortable only if it is single-valued * (it has a single value in the scope of the parent document). Simple * collection fields cannot be sortable, since they are multi-valued. * Simple sub-fields of complex collections are also multi-valued, and * therefore cannot be sortable. This is true whether it's an immediate * parent field, or an ancestor field, that's the complex collection. * Complex fields cannot be sortable and the sortable property must be null * for such fields. The default for sortable is true for single-valued * simple fields, false for multi-valued simple fields, and null for * complex fields. */ @JsonProperty(value = "sortable") private Boolean sortable; /* * A value indicating whether to enable the field to be referenced in facet * queries. Typically used in a presentation of search results that * includes hit count by category (for example, search for digital cameras * and see hits by brand, by megapixels, by price, and so on). This * property must be null for complex fields. Fields of type * Edm.GeographyPoint or Collection(Edm.GeographyPoint) cannot be * facetable. Default is true for all other simple fields. */ @JsonProperty(value = "facetable") private Boolean facetable; /* * The name of the analyzer to use for the field. This option can be used * only with searchable fields and it can't be set together with either * searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot * be changed for the field. Must be null for complex fields. Possible * values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', 'BnMicrosoft', * 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', 'CaLucene', * 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', * 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', * 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', * 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', * 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', * 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', * 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', * 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', * 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', * 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', * 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "analyzer") private AnalyzerName analyzer; /* * The name of the analyzer used at search time for the field. This option * can be used only with searchable fields. It must be set together with * indexAnalyzer and it cannot be set together with the analyzer option. * This property cannot be set to the name of a language analyzer; use the * analyzer property instead if you need a language analyzer. This analyzer * can be updated on an existing field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "searchAnalyzer") private AnalyzerName searchAnalyzer; /* * The name of the analyzer used at indexing time for the field. This * option can be used only with searchable fields. It must be set together * with searchAnalyzer and it cannot be set together with the analyzer * option. This property cannot be set to the name of a language analyzer; * use the analyzer property instead if you need a language analyzer. Once * the analyzer is chosen, it cannot be changed for the field. Must be null * for complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace' */ @JsonProperty(value = "indexAnalyzer") private AnalyzerName indexAnalyzer; /* * A list of the names of synonym maps to associate with this field. This * option can be used only with searchable fields. Currently only one * synonym map per field is supported. Assigning a synonym map to a field * ensures that query terms targeting that field are expanded at query-time * using the rules in the synonym map. This attribute can be changed on * existing fields. Must be null or an empty collection for complex fields. */ @JsonProperty(value = "synonymMaps") private List<String> synonymMaps; /* * A list of sub-fields if this is a field of type Edm.ComplexType or * Collection(Edm.ComplexType). Must be null or empty for simple fields. */ @JsonProperty(value = "fields") private List<Field> fields; /* * A value indicating whether the field will be returned in a search * result. This property must be false for key fields, and must be null for * complex fields. You can hide a field from search results if you want to * use it only as a filter, for sorting, or for scoring. This property can * also be changed on existing fields and enabling it does not cause an * increase in index storage requirements. */ @JsonIgnore private Boolean hidden; /** * Get the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @param name the name value to set. * @return the Field object itself. */ public Field setName(String name) { this.name = name; return this; } /** * Get the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @return the type value. */ public DataType getType() { return this.type; } /** * Set the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @param type the type value to set. * @return the Field object itself. */ public Field setType(DataType type) { this.type = type; return this; } /** * Get the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @return the key value. */ public Boolean isKey() { return this.key; } /** * Set the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @param key the key value to set. * @return the Field object itself. */ public Field setKey(Boolean key) { this.key = key; return this; } /** * Get the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @return the retrievable value. */ private Boolean isRetrievable() { return this.retrievable; } /** * Set the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @param retrievable the retrievable value to set. * @return the Field object itself. */ private Field setRetrievable(Boolean retrievable) { this.retrievable = retrievable; return this; } /** * Get the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @return the searchable value. */ public Boolean isSearchable() { return this.searchable; } /** * Set the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @param searchable the searchable value to set. * @return the Field object itself. */ public Field setSearchable(Boolean searchable) { this.searchable = searchable; return this; } /** * Get the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @return the filterable value. */ public Boolean isFilterable() { return this.filterable; } /** * Set the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @param filterable the filterable value to set. * @return the Field object itself. */ public Field setFilterable(Boolean filterable) { this.filterable = filterable; return this; } /** * Get the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @return the sortable value. */ public Boolean isSortable() { return this.sortable; } /** * Set the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @param sortable the sortable value to set. * @return the Field object itself. */ public Field setSortable(Boolean sortable) { this.sortable = sortable; return this; } /** * Get the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @return the facetable value. */ public Boolean isFacetable() { return this.facetable; } /** * Set the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @param facetable the facetable value to set. * @return the Field object itself. */ public Field setFacetable(Boolean facetable) { this.facetable = facetable; return this; } /** * Get the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @return the analyzer value. */ public AnalyzerName getAnalyzer() { return this.analyzer; } /** * Set the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @param analyzer the analyzer value to set. * @return the Field object itself. */ public Field setAnalyzer(AnalyzerName analyzer) { this.analyzer = analyzer; return this; } /** * Get the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the searchAnalyzer value. */ public AnalyzerName getSearchAnalyzer() { return this.searchAnalyzer; } /** * Set the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param searchAnalyzer the searchAnalyzer value to set. * @return the Field object itself. */ public Field setSearchAnalyzer(AnalyzerName searchAnalyzer) { this.searchAnalyzer = searchAnalyzer; return this; } /** * Get the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the indexAnalyzer value. */ public AnalyzerName getIndexAnalyzer() { return this.indexAnalyzer; } /** * Set the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param indexAnalyzer the indexAnalyzer value to set. * @return the Field object itself. */ public Field setIndexAnalyzer(AnalyzerName indexAnalyzer) { this.indexAnalyzer = indexAnalyzer; return this; } /** * Get the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @return the synonymMaps value. */ public List<String> getSynonymMaps() { return this.synonymMaps; } /** * Set the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @param synonymMaps the synonymMaps value to set. * @return the Field object itself. */ public Field setSynonymMaps(List<String> synonymMaps) { this.synonymMaps = synonymMaps; return this; } /** * Get the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @return the fields value. */ public List<Field> getFields() { return this.fields; } /** * Set the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @param fields the fields value to set. * @return the Field object itself. */ public Field setFields(List<Field> fields) { this.fields = fields; return this; } /** * Get the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @return the hidden value. */ public Boolean isHidden() { return retrievable == null ? null : !retrievable; } /** * Set the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @param hidden the hidden value to set. * @return the Field object itself. */ }
trainingPollOperationResponse -> recognizePollingOperation.
public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); }
trainingPollOperationResponse ->
public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } }
One line change is easy to do in transformer. :) I would like to switch to ``` this.hidden = hidden; retrievable = this.hidden == null ? null : !this.hidden; ```
public Field setHidden(Boolean hidden) { retrievable = this.hidden == null ? null : !this.hidden; this.hidden = hidden; return this; }
retrievable = this.hidden == null ? null : !this.hidden;
public Field setHidden(Boolean hidden) { this.hidden = hidden; retrievable = this.hidden == null ? null : !this.hidden; return this; }
class Field { /* * The name of the field, which must be unique within the fields collection * of the index or parent field. */ @JsonProperty(value = "name", required = true) private String name; /* * The data type of the field. Possible values include: 'Edm.String', * 'Edm.Int32', 'Edm.Int64', 'Edm.Double', 'Edm.Boolean', * 'Edm.DateTimeOffset', 'Edm.GeographyPoint', 'Edm.ComplexType' */ @JsonProperty(value = "type", required = true) private DataType type; /* * A value indicating whether the field uniquely identifies documents in * the index. Exactly one top-level field in each index must be chosen as * the key field and it must be of type Edm.String. Key fields can be used * to look up documents directly and update or delete specific documents. * Default is false for simple fields and null for complex fields. */ @JsonProperty(value = "key") private Boolean key; /* * A value indicating whether the field can be returned in a search result. * You can disable this option if you want to use a field (for example, * margin) as a filter, sorting, or scoring mechanism but do not want the * field to be visible to the end user. This property must be true for key * fields, and it must be null for complex fields. This property can be * changed on existing fields. Enabling this property does not cause any * increase in index storage requirements. Default is true for simple * fields and null for complex fields. */ @JsonProperty(value = "retrievable") private Boolean retrievable; /* * A value indicating whether the field is full-text searchable. This means * it will undergo analysis such as word-breaking during indexing. If you * set a searchable field to a value like "sunny day", internally it will * be split into the individual tokens "sunny" and "day". This enables * full-text searches for these terms. Fields of type Edm.String or * Collection(Edm.String) are searchable by default. This property must be * false for simple fields of other non-string data types, and it must be * null for complex fields. Note: searchable fields consume extra space in * your index since Azure Cognitive Search will store an additional * tokenized version of the field value for full-text searches. If you want * to save space in your index and you don't need a field to be included in * searches, set searchable to false. */ @JsonProperty(value = "searchable") private Boolean searchable; /* * A value indicating whether to enable the field to be referenced in * $filter queries. filterable differs from searchable in how strings are * handled. Fields of type Edm.String or Collection(Edm.String) that are * filterable do not undergo word-breaking, so comparisons are for exact * matches only. For example, if you set such a field f to "sunny day", * $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' * will. This property must be null for complex fields. Default is true for * simple fields and null for complex fields. */ @JsonProperty(value = "filterable") private Boolean filterable; /* * A value indicating whether to enable the field to be referenced in * $orderby expressions. By default Azure Cognitive Search sorts results by * score, but in many experiences users will want to sort by fields in the * documents. A simple field can be sortable only if it is single-valued * (it has a single value in the scope of the parent document). Simple * collection fields cannot be sortable, since they are multi-valued. * Simple sub-fields of complex collections are also multi-valued, and * therefore cannot be sortable. This is true whether it's an immediate * parent field, or an ancestor field, that's the complex collection. * Complex fields cannot be sortable and the sortable property must be null * for such fields. The default for sortable is true for single-valued * simple fields, false for multi-valued simple fields, and null for * complex fields. */ @JsonProperty(value = "sortable") private Boolean sortable; /* * A value indicating whether to enable the field to be referenced in facet * queries. Typically used in a presentation of search results that * includes hit count by category (for example, search for digital cameras * and see hits by brand, by megapixels, by price, and so on). This * property must be null for complex fields. Fields of type * Edm.GeographyPoint or Collection(Edm.GeographyPoint) cannot be * facetable. Default is true for all other simple fields. */ @JsonProperty(value = "facetable") private Boolean facetable; /* * The name of the analyzer to use for the field. This option can be used * only with searchable fields and it can't be set together with either * searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot * be changed for the field. Must be null for complex fields. Possible * values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', 'BnMicrosoft', * 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', 'CaLucene', * 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', * 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', * 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', * 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', * 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', * 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', * 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', * 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', * 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', * 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', * 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "analyzer") private AnalyzerName analyzer; /* * The name of the analyzer used at search time for the field. This option * can be used only with searchable fields. It must be set together with * indexAnalyzer and it cannot be set together with the analyzer option. * This property cannot be set to the name of a language analyzer; use the * analyzer property instead if you need a language analyzer. This analyzer * can be updated on an existing field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "searchAnalyzer") private AnalyzerName searchAnalyzer; /* * The name of the analyzer used at indexing time for the field. This * option can be used only with searchable fields. It must be set together * with searchAnalyzer and it cannot be set together with the analyzer * option. This property cannot be set to the name of a language analyzer; * use the analyzer property instead if you need a language analyzer. Once * the analyzer is chosen, it cannot be changed for the field. Must be null * for complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace' */ @JsonProperty(value = "indexAnalyzer") private AnalyzerName indexAnalyzer; /* * A list of the names of synonym maps to associate with this field. This * option can be used only with searchable fields. Currently only one * synonym map per field is supported. Assigning a synonym map to a field * ensures that query terms targeting that field are expanded at query-time * using the rules in the synonym map. This attribute can be changed on * existing fields. Must be null or an empty collection for complex fields. */ @JsonProperty(value = "synonymMaps") private List<String> synonymMaps; /* * A list of sub-fields if this is a field of type Edm.ComplexType or * Collection(Edm.ComplexType). Must be null or empty for simple fields. */ @JsonProperty(value = "fields") private List<Field> fields; /* * A value indicating whether the field will be returned in a search * result. This property must be false for key fields, and must be null for * complex fields. You can hide a field from search results if you want to * use it only as a filter, for sorting, or for scoring. This property can * also be changed on existing fields and enabling it does not cause an * increase in index storage requirements. */ @JsonIgnore private Boolean hidden; /** * Get the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @param name the name value to set. * @return the Field object itself. */ public Field setName(String name) { this.name = name; return this; } /** * Get the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @return the type value. */ public DataType getType() { return this.type; } /** * Set the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @param type the type value to set. * @return the Field object itself. */ public Field setType(DataType type) { this.type = type; return this; } /** * Get the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @return the key value. */ public Boolean isKey() { return this.key; } /** * Set the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @param key the key value to set. * @return the Field object itself. */ public Field setKey(Boolean key) { this.key = key; return this; } /** * Get the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @return the retrievable value. */ private Boolean isRetrievable() { return this.retrievable; } /** * Set the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @param retrievable the retrievable value to set. * @return the Field object itself. */ private Field setRetrievable(Boolean retrievable) { this.retrievable = retrievable; return this; } /** * Get the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @return the searchable value. */ public Boolean isSearchable() { return this.searchable; } /** * Set the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @param searchable the searchable value to set. * @return the Field object itself. */ public Field setSearchable(Boolean searchable) { this.searchable = searchable; return this; } /** * Get the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @return the filterable value. */ public Boolean isFilterable() { return this.filterable; } /** * Set the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @param filterable the filterable value to set. * @return the Field object itself. */ public Field setFilterable(Boolean filterable) { this.filterable = filterable; return this; } /** * Get the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @return the sortable value. */ public Boolean isSortable() { return this.sortable; } /** * Set the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @param sortable the sortable value to set. * @return the Field object itself. */ public Field setSortable(Boolean sortable) { this.sortable = sortable; return this; } /** * Get the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @return the facetable value. */ public Boolean isFacetable() { return this.facetable; } /** * Set the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @param facetable the facetable value to set. * @return the Field object itself. */ public Field setFacetable(Boolean facetable) { this.facetable = facetable; return this; } /** * Get the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @return the analyzer value. */ public AnalyzerName getAnalyzer() { return this.analyzer; } /** * Set the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @param analyzer the analyzer value to set. * @return the Field object itself. */ public Field setAnalyzer(AnalyzerName analyzer) { this.analyzer = analyzer; return this; } /** * Get the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the searchAnalyzer value. */ public AnalyzerName getSearchAnalyzer() { return this.searchAnalyzer; } /** * Set the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param searchAnalyzer the searchAnalyzer value to set. * @return the Field object itself. */ public Field setSearchAnalyzer(AnalyzerName searchAnalyzer) { this.searchAnalyzer = searchAnalyzer; return this; } /** * Get the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the indexAnalyzer value. */ public AnalyzerName getIndexAnalyzer() { return this.indexAnalyzer; } /** * Set the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param indexAnalyzer the indexAnalyzer value to set. * @return the Field object itself. */ public Field setIndexAnalyzer(AnalyzerName indexAnalyzer) { this.indexAnalyzer = indexAnalyzer; return this; } /** * Get the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @return the synonymMaps value. */ public List<String> getSynonymMaps() { return this.synonymMaps; } /** * Set the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @param synonymMaps the synonymMaps value to set. * @return the Field object itself. */ public Field setSynonymMaps(List<String> synonymMaps) { this.synonymMaps = synonymMaps; return this; } /** * Get the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @return the fields value. */ public List<Field> getFields() { return this.fields; } /** * Set the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @param fields the fields value to set. * @return the Field object itself. */ public Field setFields(List<Field> fields) { this.fields = fields; return this; } /** * Get the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @return the hidden value. */ public Boolean isHidden() { return retrievable == null ? null : !retrievable; } /** * Set the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @param hidden the hidden value to set. * @return the Field object itself. */ }
class Field { /* * The name of the field, which must be unique within the fields collection * of the index or parent field. */ @JsonProperty(value = "name", required = true) private String name; /* * The data type of the field. Possible values include: 'Edm.String', * 'Edm.Int32', 'Edm.Int64', 'Edm.Double', 'Edm.Boolean', * 'Edm.DateTimeOffset', 'Edm.GeographyPoint', 'Edm.ComplexType' */ @JsonProperty(value = "type", required = true) private DataType type; /* * A value indicating whether the field uniquely identifies documents in * the index. Exactly one top-level field in each index must be chosen as * the key field and it must be of type Edm.String. Key fields can be used * to look up documents directly and update or delete specific documents. * Default is false for simple fields and null for complex fields. */ @JsonProperty(value = "key") private Boolean key; /* * A value indicating whether the field can be returned in a search result. * You can disable this option if you want to use a field (for example, * margin) as a filter, sorting, or scoring mechanism but do not want the * field to be visible to the end user. This property must be true for key * fields, and it must be null for complex fields. This property can be * changed on existing fields. Enabling this property does not cause any * increase in index storage requirements. Default is true for simple * fields and null for complex fields. */ @JsonProperty(value = "retrievable") private Boolean retrievable; /* * A value indicating whether the field is full-text searchable. This means * it will undergo analysis such as word-breaking during indexing. If you * set a searchable field to a value like "sunny day", internally it will * be split into the individual tokens "sunny" and "day". This enables * full-text searches for these terms. Fields of type Edm.String or * Collection(Edm.String) are searchable by default. This property must be * false for simple fields of other non-string data types, and it must be * null for complex fields. Note: searchable fields consume extra space in * your index since Azure Cognitive Search will store an additional * tokenized version of the field value for full-text searches. If you want * to save space in your index and you don't need a field to be included in * searches, set searchable to false. */ @JsonProperty(value = "searchable") private Boolean searchable; /* * A value indicating whether to enable the field to be referenced in * $filter queries. filterable differs from searchable in how strings are * handled. Fields of type Edm.String or Collection(Edm.String) that are * filterable do not undergo word-breaking, so comparisons are for exact * matches only. For example, if you set such a field f to "sunny day", * $filter=f eq 'sunny' will find no matches, but $filter=f eq 'sunny day' * will. This property must be null for complex fields. Default is true for * simple fields and null for complex fields. */ @JsonProperty(value = "filterable") private Boolean filterable; /* * A value indicating whether to enable the field to be referenced in * $orderby expressions. By default Azure Cognitive Search sorts results by * score, but in many experiences users will want to sort by fields in the * documents. A simple field can be sortable only if it is single-valued * (it has a single value in the scope of the parent document). Simple * collection fields cannot be sortable, since they are multi-valued. * Simple sub-fields of complex collections are also multi-valued, and * therefore cannot be sortable. This is true whether it's an immediate * parent field, or an ancestor field, that's the complex collection. * Complex fields cannot be sortable and the sortable property must be null * for such fields. The default for sortable is true for single-valued * simple fields, false for multi-valued simple fields, and null for * complex fields. */ @JsonProperty(value = "sortable") private Boolean sortable; /* * A value indicating whether to enable the field to be referenced in facet * queries. Typically used in a presentation of search results that * includes hit count by category (for example, search for digital cameras * and see hits by brand, by megapixels, by price, and so on). This * property must be null for complex fields. Fields of type * Edm.GeographyPoint or Collection(Edm.GeographyPoint) cannot be * facetable. Default is true for all other simple fields. */ @JsonProperty(value = "facetable") private Boolean facetable; /* * The name of the analyzer to use for the field. This option can be used * only with searchable fields and it can't be set together with either * searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot * be changed for the field. Must be null for complex fields. Possible * values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', 'BnMicrosoft', * 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', 'CaLucene', * 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', * 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', * 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', * 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', * 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', * 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', * 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', * 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', * 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', * 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', * 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "analyzer") private AnalyzerName analyzer; /* * The name of the analyzer used at search time for the field. This option * can be used only with searchable fields. It must be set together with * indexAnalyzer and it cannot be set together with the analyzer option. * This property cannot be set to the name of a language analyzer; use the * analyzer property instead if you need a language analyzer. This analyzer * can be updated on an existing field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace' */ @JsonProperty(value = "searchAnalyzer") private AnalyzerName searchAnalyzer; /* * The name of the analyzer used at indexing time for the field. This * option can be used only with searchable fields. It must be set together * with searchAnalyzer and it cannot be set together with the analyzer * option. This property cannot be set to the name of a language analyzer; * use the analyzer property instead if you need a language analyzer. Once * the analyzer is chosen, it cannot be changed for the field. Must be null * for complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace' */ @JsonProperty(value = "indexAnalyzer") private AnalyzerName indexAnalyzer; /* * A list of the names of synonym maps to associate with this field. This * option can be used only with searchable fields. Currently only one * synonym map per field is supported. Assigning a synonym map to a field * ensures that query terms targeting that field are expanded at query-time * using the rules in the synonym map. This attribute can be changed on * existing fields. Must be null or an empty collection for complex fields. */ @JsonProperty(value = "synonymMaps") private List<String> synonymMaps; /* * A list of sub-fields if this is a field of type Edm.ComplexType or * Collection(Edm.ComplexType). Must be null or empty for simple fields. */ @JsonProperty(value = "fields") private List<Field> fields; /* * A value indicating whether the field will be returned in a search * result. This property must be false for key fields, and must be null for * complex fields. You can hide a field from search results if you want to * use it only as a filter, for sorting, or for scoring. This property can * also be changed on existing fields and enabling it does not cause an * increase in index storage requirements. */ @JsonIgnore private Boolean hidden; /** * Get the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @return the name value. */ public String getName() { return this.name; } /** * Set the name property: The name of the field, which must be unique * within the fields collection of the index or parent field. * * @param name the name value to set. * @return the Field object itself. */ public Field setName(String name) { this.name = name; return this; } /** * Get the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @return the type value. */ public DataType getType() { return this.type; } /** * Set the type property: The data type of the field. Possible values * include: 'Edm.String', 'Edm.Int32', 'Edm.Int64', 'Edm.Double', * 'Edm.Boolean', 'Edm.DateTimeOffset', 'Edm.GeographyPoint', * 'Edm.ComplexType'. * * @param type the type value to set. * @return the Field object itself. */ public Field setType(DataType type) { this.type = type; return this; } /** * Get the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @return the key value. */ public Boolean isKey() { return this.key; } /** * Set the key property: A value indicating whether the field uniquely * identifies documents in the index. Exactly one top-level field in each * index must be chosen as the key field and it must be of type Edm.String. * Key fields can be used to look up documents directly and update or * delete specific documents. Default is false for simple fields and null * for complex fields. * * @param key the key value to set. * @return the Field object itself. */ public Field setKey(Boolean key) { this.key = key; return this; } /** * Get the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @return the retrievable value. */ private Boolean isRetrievable() { return this.retrievable; } /** * Set the retrievable property: A value indicating whether the field can * be returned in a search result. You can disable this option if you want * to use a field (for example, margin) as a filter, sorting, or scoring * mechanism but do not want the field to be visible to the end user. This * property must be true for key fields, and it must be null for complex * fields. This property can be changed on existing fields. Enabling this * property does not cause any increase in index storage requirements. * Default is true for simple fields and null for complex fields. * * @param retrievable the retrievable value to set. * @return the Field object itself. */ private Field setRetrievable(Boolean retrievable) { this.retrievable = retrievable; return this; } /** * Get the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @return the searchable value. */ public Boolean isSearchable() { return this.searchable; } /** * Set the searchable property: A value indicating whether the field is * full-text searchable. This means it will undergo analysis such as * word-breaking during indexing. If you set a searchable field to a value * like "sunny day", internally it will be split into the individual tokens * "sunny" and "day". This enables full-text searches for these terms. * Fields of type Edm.String or Collection(Edm.String) are searchable by * default. This property must be false for simple fields of other * non-string data types, and it must be null for complex fields. Note: * searchable fields consume extra space in your index since Azure * Cognitive Search will store an additional tokenized version of the field * value for full-text searches. If you want to save space in your index * and you don't need a field to be included in searches, set searchable to * false. * * @param searchable the searchable value to set. * @return the Field object itself. */ public Field setSearchable(Boolean searchable) { this.searchable = searchable; return this; } /** * Get the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @return the filterable value. */ public Boolean isFilterable() { return this.filterable; } /** * Set the filterable property: A value indicating whether to enable the * field to be referenced in $filter queries. filterable differs from * searchable in how strings are handled. Fields of type Edm.String or * Collection(Edm.String) that are filterable do not undergo word-breaking, * so comparisons are for exact matches only. For example, if you set such * a field f to "sunny day", $filter=f eq 'sunny' will find no matches, but * $filter=f eq 'sunny day' will. This property must be null for complex * fields. Default is true for simple fields and null for complex fields. * * @param filterable the filterable value to set. * @return the Field object itself. */ public Field setFilterable(Boolean filterable) { this.filterable = filterable; return this; } /** * Get the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @return the sortable value. */ public Boolean isSortable() { return this.sortable; } /** * Set the sortable property: A value indicating whether to enable the * field to be referenced in $orderby expressions. By default Azure * Cognitive Search sorts results by score, but in many experiences users * will want to sort by fields in the documents. A simple field can be * sortable only if it is single-valued (it has a single value in the scope * of the parent document). Simple collection fields cannot be sortable, * since they are multi-valued. Simple sub-fields of complex collections * are also multi-valued, and therefore cannot be sortable. This is true * whether it's an immediate parent field, or an ancestor field, that's the * complex collection. Complex fields cannot be sortable and the sortable * property must be null for such fields. The default for sortable is true * for single-valued simple fields, false for multi-valued simple fields, * and null for complex fields. * * @param sortable the sortable value to set. * @return the Field object itself. */ public Field setSortable(Boolean sortable) { this.sortable = sortable; return this; } /** * Get the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @return the facetable value. */ public Boolean isFacetable() { return this.facetable; } /** * Set the facetable property: A value indicating whether to enable the * field to be referenced in facet queries. Typically used in a * presentation of search results that includes hit count by category (for * example, search for digital cameras and see hits by brand, by * megapixels, by price, and so on). This property must be null for complex * fields. Fields of type Edm.GeographyPoint or * Collection(Edm.GeographyPoint) cannot be facetable. Default is true for * all other simple fields. * * @param facetable the facetable value to set. * @return the Field object itself. */ public Field setFacetable(Boolean facetable) { this.facetable = facetable; return this; } /** * Get the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @return the analyzer value. */ public AnalyzerName getAnalyzer() { return this.analyzer; } /** * Set the analyzer property: The name of the analyzer to use for the * field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the * analyzer is chosen, it cannot be changed for the field. Must be null for * complex fields. Possible values include: 'ArMicrosoft', 'ArLucene', * 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', * 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', * 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', * 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', 'NlLucene', * 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', * 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', 'DeLucene', * 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', * 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', * 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', * 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', * 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', * 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', 'PlLucene', * 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', 'PtPtLucene', * 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', 'RuLucene', * 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', 'SlMicrosoft', * 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', 'TaMicrosoft', * 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', 'TrLucene', * 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', 'StandardLucene', * 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', 'Simple', 'Stop', * 'Whitespace'. * * @param analyzer the analyzer value to set. * @return the Field object itself. */ public Field setAnalyzer(AnalyzerName analyzer) { this.analyzer = analyzer; return this; } /** * Get the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the searchAnalyzer value. */ public AnalyzerName getSearchAnalyzer() { return this.searchAnalyzer; } /** * Set the searchAnalyzer property: The name of the analyzer used at search * time for the field. This option can be used only with searchable fields. * It must be set together with indexAnalyzer and it cannot be set together * with the analyzer option. This property cannot be set to the name of a * language analyzer; use the analyzer property instead if you need a * language analyzer. This analyzer can be updated on an existing field. * Must be null for complex fields. Possible values include: 'ArMicrosoft', * 'ArLucene', 'HyLucene', 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', * 'BgLucene', 'CaMicrosoft', 'CaLucene', 'ZhHansMicrosoft', * 'ZhHansLucene', 'ZhHantMicrosoft', 'ZhHantLucene', 'HrMicrosoft', * 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', 'DaLucene', 'NlMicrosoft', * 'NlLucene', 'EnMicrosoft', 'EnLucene', 'EtMicrosoft', 'FiMicrosoft', * 'FiLucene', 'FrMicrosoft', 'FrLucene', 'GlLucene', 'DeMicrosoft', * 'DeLucene', 'ElMicrosoft', 'ElLucene', 'GuMicrosoft', 'HeMicrosoft', * 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', 'HuLucene', 'IsMicrosoft', * 'IdMicrosoft', 'IdLucene', 'GaLucene', 'ItMicrosoft', 'ItLucene', * 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', 'KoMicrosoft', 'KoLucene', * 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', 'MlMicrosoft', 'MsMicrosoft', * 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', 'FaLucene', 'PlMicrosoft', * 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', 'PtPtMicrosoft', * 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', 'RuMicrosoft', * 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', 'SkMicrosoft', * 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', 'SvLucene', * 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', 'TrMicrosoft', * 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param searchAnalyzer the searchAnalyzer value to set. * @return the Field object itself. */ public Field setSearchAnalyzer(AnalyzerName searchAnalyzer) { this.searchAnalyzer = searchAnalyzer; return this; } /** * Get the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @return the indexAnalyzer value. */ public AnalyzerName getIndexAnalyzer() { return this.indexAnalyzer; } /** * Set the indexAnalyzer property: The name of the analyzer used at * indexing time for the field. This option can be used only with * searchable fields. It must be set together with searchAnalyzer and it * cannot be set together with the analyzer option. This property cannot * be set to the name of a language analyzer; use the analyzer property * instead if you need a language analyzer. Once the analyzer is chosen, it * cannot be changed for the field. Must be null for complex fields. * Possible values include: 'ArMicrosoft', 'ArLucene', 'HyLucene', * 'BnMicrosoft', 'EuLucene', 'BgMicrosoft', 'BgLucene', 'CaMicrosoft', * 'CaLucene', 'ZhHansMicrosoft', 'ZhHansLucene', 'ZhHantMicrosoft', * 'ZhHantLucene', 'HrMicrosoft', 'CsMicrosoft', 'CsLucene', 'DaMicrosoft', * 'DaLucene', 'NlMicrosoft', 'NlLucene', 'EnMicrosoft', 'EnLucene', * 'EtMicrosoft', 'FiMicrosoft', 'FiLucene', 'FrMicrosoft', 'FrLucene', * 'GlLucene', 'DeMicrosoft', 'DeLucene', 'ElMicrosoft', 'ElLucene', * 'GuMicrosoft', 'HeMicrosoft', 'HiMicrosoft', 'HiLucene', 'HuMicrosoft', * 'HuLucene', 'IsMicrosoft', 'IdMicrosoft', 'IdLucene', 'GaLucene', * 'ItMicrosoft', 'ItLucene', 'JaMicrosoft', 'JaLucene', 'KnMicrosoft', * 'KoMicrosoft', 'KoLucene', 'LvMicrosoft', 'LvLucene', 'LtMicrosoft', * 'MlMicrosoft', 'MsMicrosoft', 'MrMicrosoft', 'NbMicrosoft', 'NoLucene', * 'FaLucene', 'PlMicrosoft', 'PlLucene', 'PtBrMicrosoft', 'PtBrLucene', * 'PtPtMicrosoft', 'PtPtLucene', 'PaMicrosoft', 'RoMicrosoft', 'RoLucene', * 'RuMicrosoft', 'RuLucene', 'SrCyrillicMicrosoft', 'SrLatinMicrosoft', * 'SkMicrosoft', 'SlMicrosoft', 'EsMicrosoft', 'EsLucene', 'SvMicrosoft', * 'SvLucene', 'TaMicrosoft', 'TeMicrosoft', 'ThMicrosoft', 'ThLucene', * 'TrMicrosoft', 'TrLucene', 'UkMicrosoft', 'UrMicrosoft', 'ViMicrosoft', * 'StandardLucene', 'StandardAsciiFoldingLucene', 'Keyword', 'Pattern', * 'Simple', 'Stop', 'Whitespace'. * * @param indexAnalyzer the indexAnalyzer value to set. * @return the Field object itself. */ public Field setIndexAnalyzer(AnalyzerName indexAnalyzer) { this.indexAnalyzer = indexAnalyzer; return this; } /** * Get the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @return the synonymMaps value. */ public List<String> getSynonymMaps() { return this.synonymMaps; } /** * Set the synonymMaps property: A list of the names of synonym maps to * associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning * a synonym map to a field ensures that query terms targeting that field * are expanded at query-time using the rules in the synonym map. This * attribute can be changed on existing fields. Must be null or an empty * collection for complex fields. * * @param synonymMaps the synonymMaps value to set. * @return the Field object itself. */ public Field setSynonymMaps(List<String> synonymMaps) { this.synonymMaps = synonymMaps; return this; } /** * Get the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @return the fields value. */ public List<Field> getFields() { return this.fields; } /** * Set the fields property: A list of sub-fields if this is a field of type * Edm.ComplexType or Collection(Edm.ComplexType). Must be null or empty * for simple fields. * * @param fields the fields value to set. * @return the Field object itself. */ public Field setFields(List<Field> fields) { this.fields = fields; return this; } /** * Get the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @return the hidden value. */ public Boolean isHidden() { return retrievable == null ? null : !retrievable; } /** * Set the hidden property: A value indicating whether the field will be * returned in a search result. This property must be false for key fields, * and must be null for complex fields. You can hide a field from search * results if you want to use it only as a filter, for sorting, or for * scoring. This property can also be changed on existing fields and * enabling it does not cause an increase in index storage requirements. * * @param hidden the hidden value to set. * @return the Field object itself. */ }
"Model Type Id: --> Form type:
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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }
key, customFormModelField.getName(), customFormModelField.getAccuracy())));
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()))); }); }
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}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true).subscribe( trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true, isIncludeSubFolders, filePrefix, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { 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("Model Type Id: %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("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * 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(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model ID = %s, model status = %s, created on = %s, last updated on = %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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 */ /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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())); } }
"Max number of models that can be trained for this account"
public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); }
System.out.printf("Account properties limit: %s%n", accountProperties.getLimit());
public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); }
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}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true).subscribe( trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true, isIncludeSubFolders, filePrefix, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %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("Model Type Id: %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 -> { 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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * 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(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model ID = %s, model status = %s, created on = %s, last updated on = %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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 */ /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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())); } }
Current count of trained custom models:
public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); }
System.out.printf("Account properties count: %d%n", accountProperties.getCount());
public void getAccountProperties() { formTrainingAsyncClient.getAccountProperties().subscribe(accountProperties -> { System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); }
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}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true).subscribe( trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true, isIncludeSubFolders, filePrefix, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %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("Model Type Id: %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 -> { 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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * 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(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model ID = %s, model status = %s, created on = %s, last updated on = %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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 */ /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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())); } }
No need to subscribe on void. just update this to formTrainingAsyncClient.deleteModel("{modelId}")
public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); }
System.out.printf("Model ID = %s is deleted%n", modelId));
public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); }
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}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true).subscribe( trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true, isIncludeSubFolders, filePrefix, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %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("Model Type Id: %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 -> { 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("Model Type Id: %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("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model ID = %s, model status = %s, created on = %s, last updated on = %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * 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())); } }
subscribe and print the response status
public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); }
System.out.printf("Model ID = %s is deleted%n", modelId));
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); }); }
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}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true).subscribe( trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true, isIncludeSubFolders, filePrefix, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %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("Model Type Id: %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 -> { 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("Model Type Id: %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("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * 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 */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model ID = %s, model status = %s, created on = %s, last updated on = %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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 */ /** * 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())); } }
FYI, when app config do deletion, like deleting a configuration, we do return object to user. does method call trigger if without subscribe?
public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); }
System.out.printf("Model ID = %s is deleted%n", modelId));
public void deleteModel() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModel(modelId).subscribe(val -> System.out.printf("Model Id: %s is deleted%n", modelId)); }
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}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true).subscribe( trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true, isIncludeSubFolders, filePrefix, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %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("Model Type Id: %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 -> { 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("Model Type Id: %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("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void deleteModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.deleteModelWithResponse(modelId).subscribe(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model ID = %s, model status = %s, created on = %s, last updated on = %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * 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())); } }
remove Id from the form type.
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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }
key, customFormModelField.getName(), customFormModelField.getAccuracy())));
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()))); }); }
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}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true).subscribe( trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true, isIncludeSubFolders, filePrefix, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { 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("Model Type Id: %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("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * 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(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model ID = %s, model status = %s, created on = %s, last updated on = %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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 */ /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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())); } }
everywhere applicable.
public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); }
trainingPollOperationResponse ->
public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } }
remove `||` from all content print statements.
public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); }
System.out.printf("%s || ", recognizedTableCell.getText())));
public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } }
delete these value lines. and just update the above line to >System.out.printf("Merchant Name: %s%n", usReceipt.getMerchantName().getFieldValue());
public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); }
System.out.printf("Merchant Name Value: %s%n", usReceipt.getMerchantName().getFieldValue());
public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } }
applicable to all receipt recognize examples
public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); }
System.out.printf("Merchant Name Value: %s%n", usReceipt.getMerchantName().getFieldValue());
public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %s%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> trainingPollOperationResponse.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s || ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(trainingPollOperationResponse -> { trainingPollOperationResponse.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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("Total: %s%n", usReceipt.getTotal().getName()); System.out.printf("Total Value: %s%n", usReceipt.getTotal().getFieldValue()); })); }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } }
"Form Type Id" -> Form Type It is not an Id
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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }
key, customFormModelField.getName(), customFormModelField.getAccuracy())));
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()))); }); }
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}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true).subscribe( trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; formTrainingAsyncClient.beginTraining(trainingSetSource, true, isIncludeSubFolders, filePrefix, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> { trainingOperationResponse.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("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * Code snippet for {@link FormTrainingAsyncClient */ public void getCustomModelWithResponse() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModelWithResponse(modelId).subscribe(response -> { 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("Model Type Id: %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("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Account properties limit: %s%n", accountProperties.getLimit()); System.out.printf("Account properties count: %d%n", accountProperties.getCount()); }); } /** * 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(val -> System.out.printf("Model ID = %s is deleted%n", modelId)); } /** * Code snippet for {@link FormTrainingAsyncClient */ public void listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model ID = %s, model status = %s, created on = %s, last updated on = %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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 */ /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * 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())); } }
Need to print merchant address and tax and phone number just to show various us receipt items.
public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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().getFieldValue()); })); }); }
System.out.printf("Merchant Name: %s%n", usReceipt.getMerchantName().getFieldValue());
public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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().getFieldValue()); })); }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } }
we need only the values , not so much name.
public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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().getFieldValue()); })); }); }
System.out.printf("Merchant Name: %s%n", usReceipt.getMerchantName().getFieldValue());
public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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().getFieldValue()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.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().getFieldValue()); })); }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); String modelId = "{model_id}"; boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(buffer, modelId, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrlWithOptions() { String sourceFilePath = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(sourceFilePath, Duration.ofSeconds(5)).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, sourceFile.length(), FormContentType.APPLICATION_PDF) .subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, FormContentType.APPLICATION_PDF, sourceFile.length(), Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(layoutPageResults -> layoutPageResults.forEach(recognizedForm -> { System.out.printf("Page Angle: %s%n", recognizedForm.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", recognizedForm.getUnit()); System.out.println("Recognized Tables: "); recognizedForm.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }) )); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{file_source_url}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, includeTextDetails, Duration.ofSeconds(5)) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG) .subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File sourceFile = new File("{file_source_url}"); boolean includeTextDetails = true; Flux<ByteBuffer> buffer = Utility.convertStreamToByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_JPEG, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(recognizedReceipts -> recognizedReceipts.forEach(recognizedReceipt -> { USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getFieldValue(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %.2f, confidence: %.2f%n", usReceipt.getTotal().getFieldValue(), usReceipt.getTotal().getConfidence()); })); }); } }
print status code may be to show difference between with and without response?
public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); }
AccountProperties accountProperties = response.getValue();
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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); }
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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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 -> { 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * 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 listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * 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())); } }
like delteModelWithResponse
public void getAccountPropertiesWithResponse() { formTrainingAsyncClient.getAccountPropertiesWithResponse().subscribe(response -> { AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be trained for this account: %s%n", accountProperties.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); }
AccountProperties accountProperties = response.getValue();
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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); }
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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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 -> { 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * 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 listModels() { formTrainingAsyncClient.listModels().subscribe(result -> System.out.printf("Model Id: %s, Model status: %s, Created on: %s, Last updated on: %s.%n", result.getModelId(), result.getStatus(), result.getCreatedOn(), result.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 */ public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; boolean isIncludeSubFolders = false; String filePrefix = "{file-prefix}"; boolean useLabelFile = true; formTrainingAsyncClient.beginTraining(trainingSetSource, useLabelFile, isIncludeSubFolders, filePrefix, 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.getLimit()); System.out.printf("Current count of trained custom models: %d%n", accountProperties.getCount()); }); } /** * Code snippet for {@link FormTrainingAsyncClient */ /** * 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())); } }
I think it'd be best to have the forms also in the samples folder, doesn't look great going into the test folder
public static void main(String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_Key}")) .endpoint("https: .buildClient(); File analyzeFile = new File("../../test/resources/sample-files/Invoice_1.pdf"); byte[] fileContent = Files.readAllBytes(analyzeFile.toPath()); IterableStream<RecognizedForm> formsWithLabeledModel = client.beginRecognizeCustomForms(new ByteArrayInputStream(fileContent), "{labeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF, true, null).getFinalResult(); IterableStream<RecognizedForm> formsWithUnlabeledModel = client.beginRecognizeCustomForms(new ByteArrayInputStream(fileContent), "{unlabeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF).getFinalResult(); System.out.println("--------Recognizing forms with labeled custom model--------"); printFieldData(formsWithLabeledModel); System.out.println("-----------------------------------------------------------"); System.out.println("-------Recognizing forms with unlabeled custom model-------"); printFieldData(formsWithUnlabeledModel); }
File analyzeFile = new File("../../test/resources/sample-files/Invoice_1.pdf");
public static void main(String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File analyzeFile = new File("sample-forms/forms/Invoice_6.pdf"); IterableStream<RecognizedForm> formsWithLabeledModel = client.beginRecognizeCustomForms(new FileInputStream(analyzeFile), "{labeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF, true, null).getFinalResult(); IterableStream<RecognizedForm> formsWithUnlabeledModel = client.beginRecognizeCustomForms(new FileInputStream(analyzeFile), "{unlabeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF).getFinalResult(); System.out.println("--------Recognizing forms with labeled custom model--------"); formsWithLabeledModel.forEach(labeledForm -> labeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); System.out.println("-----------------------------------------------------------"); System.out.println("-------Recognizing forms with unlabeled custom model-------"); formsWithUnlabeledModel.forEach(unLabeledForm -> unLabeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } final StringBuilder boundingBoxLabelStr = new StringBuilder(); if (formField.getLabelText() != null && formField.getLabelText().getBoundingBox() != null) { formField.getLabelText().getBoundingBox().getPoints().forEach(point -> boundingBoxLabelStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Field %s has label %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getLabelText().getText(), boundingBoxLabelStr, formField.getConfidence()); System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); }
class AdvancedDiffLabeledUnlabeledData { /** * 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. */ private static void printFieldData(IterableStream<RecognizedForm> recognizedForms) { recognizedForms.forEach(labeledForm -> labeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%s, %s]", point.getX(), point.getY()))); } System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %s.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); } }
class AdvancedDiffLabeledUnlabeledData { /** * 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. */ }
Differences between labeled and unlabeled might be more clear without decomposition. For example, I didn't print label data information for the labeled custom model, while I did for unlabeled
public static void main(String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_Key}")) .endpoint("https: .buildClient(); File analyzeFile = new File("../../test/resources/sample-files/Invoice_1.pdf"); byte[] fileContent = Files.readAllBytes(analyzeFile.toPath()); IterableStream<RecognizedForm> formsWithLabeledModel = client.beginRecognizeCustomForms(new ByteArrayInputStream(fileContent), "{labeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF, true, null).getFinalResult(); IterableStream<RecognizedForm> formsWithUnlabeledModel = client.beginRecognizeCustomForms(new ByteArrayInputStream(fileContent), "{unlabeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF).getFinalResult(); System.out.println("--------Recognizing forms with labeled custom model--------"); printFieldData(formsWithLabeledModel); System.out.println("-----------------------------------------------------------"); System.out.println("-------Recognizing forms with unlabeled custom model-------"); printFieldData(formsWithUnlabeledModel); }
printFieldData(formsWithLabeledModel);
public static void main(String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File analyzeFile = new File("sample-forms/forms/Invoice_6.pdf"); IterableStream<RecognizedForm> formsWithLabeledModel = client.beginRecognizeCustomForms(new FileInputStream(analyzeFile), "{labeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF, true, null).getFinalResult(); IterableStream<RecognizedForm> formsWithUnlabeledModel = client.beginRecognizeCustomForms(new FileInputStream(analyzeFile), "{unlabeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF).getFinalResult(); System.out.println("--------Recognizing forms with labeled custom model--------"); formsWithLabeledModel.forEach(labeledForm -> labeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); System.out.println("-----------------------------------------------------------"); System.out.println("-------Recognizing forms with unlabeled custom model-------"); formsWithUnlabeledModel.forEach(unLabeledForm -> unLabeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } final StringBuilder boundingBoxLabelStr = new StringBuilder(); if (formField.getLabelText() != null && formField.getLabelText().getBoundingBox() != null) { formField.getLabelText().getBoundingBox().getPoints().forEach(point -> boundingBoxLabelStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Field %s has label %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getLabelText().getText(), boundingBoxLabelStr, formField.getConfidence()); System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); }
class AdvancedDiffLabeledUnlabeledData { /** * 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. */ private static void printFieldData(IterableStream<RecognizedForm> recognizedForms) { recognizedForms.forEach(labeledForm -> labeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%s, %s]", point.getX(), point.getY()))); } System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %s.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); } }
class AdvancedDiffLabeledUnlabeledData { /** * 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 thought java had automatic content type detection. If so, can you not pass the content type since that's what most users will be doing
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File sourceFile = new File("../../test/resources/sample-files/layout1.jpg"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<OperationResult, IterableStream<FormPage>> recognizeLayoutPoller = client.beginRecognizeContent(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG); IterableStream<FormPage> layoutPageResults = recognizeLayoutPoller.getFinalResult(); layoutPageResults.forEach(formPage -> { System.out.println("----Recognizing content ----"); 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("[%s, %s]", point.getX(), point.getY()))); } System.out.printf("Cell has text %s, within bounding box %s.%n", formTableCell.getText(), boundingBoxStr); }); System.out.println(); }); }); }
client.beginRecognizeContent(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG);
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File sourceFile = new File("/sample-forms/forms/layout1.jpg"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<OperationResult, IterableStream<FormPage>> recognizeLayoutPoller = client.beginRecognizeContent(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG); IterableStream<FormPage> layoutPageResults = recognizeLayoutPoller.getFinalResult(); layoutPageResults.forEach(formPage -> { System.out.println("----Recognizing content ----"); 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(); }); }); }
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. */ }
Confused why this file is empty
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File sourceFile = new File(""); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> analyzeReceiptPoller = client.beginRecognizeReceipts(targetStream, sourceFile.length(), FormContentType.APPLICATION_PDF); IterableStream<RecognizedReceipt> receiptPageResults = analyzeReceiptPoller.getFinalResult(); receiptPageResults.forEach(recognizedReceipt -> { System.out.println("----------- Recognized Receipt -----------"); USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %s%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %s%n", usReceipt.getMerchantAddress().getName(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %s%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %s confidence: %s%n", usReceipt.getTotal().getName(), usReceipt.getTotal().getConfidence()); System.out.printf("Receipt Items: %n"); usReceipt.getReceiptItems().forEach(receiptItem -> { if (receiptItem.getName() != null) { System.out.printf("Name: %s, confidence: %s%n", receiptItem.getName().getFieldValue(), receiptItem.getName().getConfidence()); } if (receiptItem.getQuantity() != null) { System.out.printf("Quantity: %s, confidence: %s%n", receiptItem.getQuantity().getFieldValue(), receiptItem.getQuantity().getConfidence()); } if (receiptItem.getPrice() != null) { System.out.printf("Price: %s, confidence: %s%n", receiptItem.getPrice().getFieldValue(), receiptItem.getPrice().getConfidence()); } if (receiptItem.getTotalPrice() != null) { System.out.printf("Total Price: %s, confidence: %s%n", receiptItem.getTotalPrice().getFieldValue(), receiptItem.getTotalPrice().getConfidence()); } }); System.out.print("-----------------------------------"); }); }
File sourceFile = new File("");
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File sourceFile = new File("/sample-forms/receipts/contoso-allinone.jpg"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<OperationResult, IterableStream<RecognizedReceipt>> analyzeReceiptPoller = client.beginRecognizeReceipts(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG); IterableStream<RecognizedReceipt> receiptPageResults = analyzeReceiptPoller.getFinalResult(); receiptPageResults.forEach(recognizedReceipt -> { System.out.println("----------- Recognized Receipt -----------"); USReceipt usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); System.out.printf("Page Number: %s%n", usReceipt.getMerchantName().getPageNumber()); System.out.printf("Merchant Name: %s, confidence: %.2f%n", usReceipt.getMerchantName().getFieldValue(), usReceipt.getMerchantName().getConfidence()); System.out.printf("Merchant Address: %s, confidence: %.2f%n", usReceipt.getMerchantAddress().getName(), usReceipt.getMerchantAddress().getConfidence()); System.out.printf("Merchant Phone Number %s, confidence: %.2f%n", usReceipt.getMerchantPhoneNumber().getFieldValue(), usReceipt.getMerchantPhoneNumber().getConfidence()); System.out.printf("Total: %s confidence: %.2f%n", usReceipt.getTotal().getName(), usReceipt.getTotal().getConfidence()); System.out.printf("Receipt Items: %n"); usReceipt.getReceiptItems().forEach(receiptItem -> { if (receiptItem.getName() != null) { System.out.printf("Name: %s, confidence: %.2fs%n", receiptItem.getName().getFieldValue(), receiptItem.getName().getConfidence()); } if (receiptItem.getQuantity() != null) { System.out.printf("Quantity: %s, confidence: %.2f%n", receiptItem.getQuantity().getFieldValue(), receiptItem.getQuantity().getConfidence()); } if (receiptItem.getPrice() != null) { System.out.printf("Price: %s, confidence: %.2f%n", receiptItem.getPrice().getFieldValue(), receiptItem.getPrice().getConfidence()); } if (receiptItem.getTotalPrice() != null) { System.out.printf("Total Price: %s, confidence: %.2f%n", receiptItem.getTotalPrice().getFieldValue(), receiptItem.getTotalPrice().getConfidence()); } }); System.out.print("-----------------------------------"); }); }
class RecognizeReceipts { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException from reading file. */ }
class RecognizeReceipts { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. * @throws IOException from reading file. */ }
I know we said Java might diverge on this (doing file for sync, url for async), but I think that because you've added a recognizeReceipts and a recognizeReceipts FromURL, you can have the other sync and async functions call the files functions
public static void main(final String[] args) { FormRecognizerAsyncClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildAsyncClient(); PollerFlux<OperationResult, IterableStream<FormPage>> recognizeLayoutPoller = client.beginRecognizeContentFromUrl("file_source_url"); Mono<IterableStream<FormPage>> layoutPageResults = recognizeLayoutPoller .last() .flatMap(trainingOperationResponse -> { if (trainingOperationResponse.getStatus().isComplete()) { return trainingOperationResponse.getFinalResult(); } else { return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:" + trainingOperationResponse.getStatus())); } }); layoutPageResults.subscribe(formPages -> formPages.forEach(formPage -> { System.out.println("----Recognizing content ----"); 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("[%s, %s]", point.getX(), point.getY()))); } System.out.printf("Cell has text %s, within bounding box %s.%n", formTableCell.getText(), boundingBoxStr); }); System.out.println(); }); })); try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
client.beginRecognizeContentFromUrl("file_source_url");
public static void main(final String[] args) { FormRecognizerAsyncClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildAsyncClient(); PollerFlux<OperationResult, IterableStream<FormPage>> recognizeLayoutPoller = client.beginRecognizeContentFromUrl("https: Mono<IterableStream<FormPage>> layoutPageResults = recognizeLayoutPoller .last() .flatMap(trainingOperationResponse -> { if (trainingOperationResponse.getStatus().isComplete()) { return trainingOperationResponse.getFinalResult(); } else { return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:" + trainingOperationResponse.getStatus())); } }); layoutPageResults.subscribe(formPages -> formPages.forEach(formPage -> { System.out.println("----Recognizing content ----"); 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(); }); })); try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
class RecognizeContentAsync { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
class RecognizeContentAsync { /** * Main method to invoke this demo. * * @param args Unused. Arguments to the program. */ }
Considering the samples might get in before the feature would like to keep it this way and maybe consider updating once we get the feature in.
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File sourceFile = new File("../../test/resources/sample-files/layout1.jpg"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<OperationResult, IterableStream<FormPage>> recognizeLayoutPoller = client.beginRecognizeContent(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG); IterableStream<FormPage> layoutPageResults = recognizeLayoutPoller.getFinalResult(); layoutPageResults.forEach(formPage -> { System.out.println("----Recognizing content ----"); 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("[%s, %s]", point.getX(), point.getY()))); } System.out.printf("Cell has text %s, within bounding box %s.%n", formTableCell.getText(), boundingBoxStr); }); System.out.println(); }); }); }
client.beginRecognizeContent(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG);
public static void main(final String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File sourceFile = new File("/sample-forms/forms/layout1.jpg"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); InputStream targetStream = new ByteArrayInputStream(fileContent); SyncPoller<OperationResult, IterableStream<FormPage>> recognizeLayoutPoller = client.beginRecognizeContent(targetStream, sourceFile.length(), FormContentType.IMAGE_JPEG); IterableStream<FormPage> layoutPageResults = recognizeLayoutPoller.getFinalResult(); layoutPageResults.forEach(formPage -> { System.out.println("----Recognizing content ----"); 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(); }); }); }
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. */ }
@samvaity don't forget to update it without real credential
public static void main(String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("48c9ec5b1c444c899770946defc486c4")) .endpoint("https: .buildClient(); File analyzeFile = new File("../../test/resources/sample-files/Invoice_6.pdf"); System.out.println(analyzeFile.exists()); IterableStream<RecognizedForm> formsWithLabeledModel = client.beginRecognizeCustomForms(new FileInputStream(analyzeFile), "{labeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF, true, null).getFinalResult(); IterableStream<RecognizedForm> formsWithUnlabeledModel = client.beginRecognizeCustomForms(new FileInputStream(analyzeFile), "{unlabeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF).getFinalResult(); System.out.println("--------Recognizing forms with labeled custom model--------"); printFieldData(formsWithLabeledModel); System.out.println("-----------------------------------------------------------"); System.out.println("-------Recognizing forms with unlabeled custom model-------"); printFieldData(formsWithUnlabeledModel); }
.apiKey(new AzureKeyCredential("48c9ec5b1c444c899770946defc486c4"))
public static void main(String[] args) throws IOException { FormRecognizerClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_key}")) .endpoint("https: .buildClient(); File analyzeFile = new File("sample-forms/forms/Invoice_6.pdf"); IterableStream<RecognizedForm> formsWithLabeledModel = client.beginRecognizeCustomForms(new FileInputStream(analyzeFile), "{labeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF, true, null).getFinalResult(); IterableStream<RecognizedForm> formsWithUnlabeledModel = client.beginRecognizeCustomForms(new FileInputStream(analyzeFile), "{unlabeled_model_Id}", analyzeFile.length(), FormContentType.APPLICATION_PDF).getFinalResult(); System.out.println("--------Recognizing forms with labeled custom model--------"); formsWithLabeledModel.forEach(labeledForm -> labeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); System.out.println("-----------------------------------------------------------"); System.out.println("-------Recognizing forms with unlabeled custom model-------"); formsWithUnlabeledModel.forEach(unLabeledForm -> unLabeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } final StringBuilder boundingBoxLabelStr = new StringBuilder(); if (formField.getLabelText() != null && formField.getLabelText().getBoundingBox() != null) { formField.getLabelText().getBoundingBox().getPoints().forEach(point -> boundingBoxLabelStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Field %s has label %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getLabelText().getText(), boundingBoxLabelStr, formField.getConfidence()); System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); }
class AdvancedDiffLabeledUnlabeledData { /** * 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. */ private static void printFieldData(IterableStream<RecognizedForm> recognizedForms) { recognizedForms.forEach(labeledForm -> labeledForm.getFields().forEach((label, formField) -> { final StringBuilder boundingBoxStr = new StringBuilder(); if (formField.getValueText().getBoundingBox() != null) { formField.getValueText().getBoundingBox().getPoints().forEach(point -> boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY()))); } System.out.printf("Field %s has value %s based on %s within bounding box %s with a confidence score " + "of %.2f.%n", label, formField.getFieldValue(), formField.getValueText().getText(), boundingBoxStr, formField.getConfidence()); })); } }
class AdvancedDiffLabeledUnlabeledData { /** * 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. */ }
We don't need to support multiple tracer implementation. Refer here - https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TracerProvider.java#L40
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); for (Tracer tracer : tracers) { local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; }
for (Tracer tracer : tracers) {
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; }
class TracerProvider { private final List<Tracer> tracers = new ArrayList<>(); private final boolean isEnabled; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); tracers.forEach(this.tracers::add); isEnabled = this.tracers.size() > 0; } public boolean isEnabled() { return isEnabled; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<T> traceEnabledNonCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName, databaseId, endpoint, (T response) -> HttpConstants.StatusCodes.OK); } public <T> Mono<CosmosAsyncItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosAsyncItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosAsyncItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), 0); } }); } private void end(int statusCode, Throwable throwable, Context context) { for (Tracer tracer : tracers) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); StringWriter errorStack = new StringWriter(); throwable.printStackTrace(new PrintWriter(errorStack)); tracer.setAttribute(TracerProvider.ERROR_STACK, errorStack.toString(), context); } tracer.end(statusCode, throwable, context); } } }
class TracerProvider { private Tracer tracer; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final int ERROR_CODE = 0; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); if (tracers.iterator().hasNext()) { tracer = tracers.iterator().next(); } } public boolean isEnabled() { return tracer != null; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<CosmosItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), ERROR_CODE); } }); } private void end(int statusCode, Throwable throwable, Context context) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); } tracer.end(statusCode, throwable, context); } }
AZ_TRACING_NAMESPACE_KEY needs to be passed using the context as the tracer expects it in the context [here](https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core-tracing-opentelemetry/src/main/java/com/azure/core/tracing/opentelemetry/OpenTelemetryTracer.java#L52) and aligns with other SDK behavior.
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); for (Tracer tracer : tracers) { local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; }
tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local);
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; }
class TracerProvider { private final List<Tracer> tracers = new ArrayList<>(); private final boolean isEnabled; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); tracers.forEach(this.tracers::add); isEnabled = this.tracers.size() > 0; } public boolean isEnabled() { return isEnabled; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<T> traceEnabledNonCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName, databaseId, endpoint, (T response) -> HttpConstants.StatusCodes.OK); } public <T> Mono<CosmosAsyncItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosAsyncItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosAsyncItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), 0); } }); } private void end(int statusCode, Throwable throwable, Context context) { for (Tracer tracer : tracers) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); StringWriter errorStack = new StringWriter(); throwable.printStackTrace(new PrintWriter(errorStack)); tracer.setAttribute(TracerProvider.ERROR_STACK, errorStack.toString(), context); } tracer.end(statusCode, throwable, context); } } }
class TracerProvider { private Tracer tracer; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final int ERROR_CODE = 0; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); if (tracers.iterator().hasNext()) { tracer = tracers.iterator().next(); } } public boolean isEnabled() { return tracer != null; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<CosmosItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), ERROR_CODE); } }); } private void end(int statusCode, Throwable throwable, Context context) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); } tracer.end(statusCode, throwable, context); } }
do we think this is a good idea? especially since `Throwable.printStackTrace()` isn't thread-safe and could give out confusing logs/statements? cc: @srnagar
private void end(int statusCode, Throwable throwable, Context context) { for (Tracer tracer : tracers) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); StringWriter errorStack = new StringWriter(); throwable.printStackTrace(new PrintWriter(errorStack)); tracer.setAttribute(TracerProvider.ERROR_STACK, errorStack.toString(), context); } tracer.end(statusCode, throwable, context); } }
throwable.printStackTrace(new PrintWriter(errorStack));
private void end(int statusCode, Throwable throwable, Context context) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); } tracer.end(statusCode, throwable, context); }
class TracerProvider { private final List<Tracer> tracers = new ArrayList<>(); private final boolean isEnabled; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); tracers.forEach(this.tracers::add); isEnabled = this.tracers.size() > 0; } public boolean isEnabled() { return isEnabled; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); for (Tracer tracer : tracers) { local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; } /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<T> traceEnabledNonCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName, databaseId, endpoint, (T response) -> HttpConstants.StatusCodes.OK); } public <T> Mono<CosmosAsyncItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosAsyncItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosAsyncItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), 0); } }); } }
class TracerProvider { private Tracer tracer; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final int ERROR_CODE = 0; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); if (tracers.iterator().hasNext()) { tracer = tracers.iterator().next(); } } public boolean isEnabled() { return tracer != null; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; } /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<CosmosItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), ERROR_CODE); } }); } }
use `StepVerifier` instead of `block` for testing async calls?
public void cosmosAsyncClient() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); client.readAllDatabases(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + cosmosAsyncDatabase.getId() + "'"; client.queryDatabases(query, new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); }
client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block();
public void cosmosAsyncClient() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); client.readAllDatabases(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + cosmosAsyncDatabase.getId() + "'"; client.queryDatabases(query, new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); }
class CosmosTracerTest extends TestSuiteBase { private static final String ITEM_ID = "tracerDoc"; CosmosAsyncClient client; CosmosAsyncDatabase cosmosAsyncDatabase; CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .buildAsyncClient(); cosmosAsyncDatabase = getSharedCosmosDatabase(client); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(client); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncDatabase() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncDatabase.createContainerIfNotExists(cosmosAsyncContainer.getId(), "/pk", 5000).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncDatabase.readProvisionedThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllUsers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllContainers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncContainer() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.read().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncContainer.readProvisionedThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosItemProperties properties = new CosmosItemProperties(); properties.setId(ITEM_ID); cosmosAsyncContainer.createItem(properties).block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.upsertItem(properties, new CosmosItemRequestOptions()).block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readItem(ITEM_ID, PartitionKey.NONE, CosmosItemProperties.class).block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.deleteItem(ITEM_ID, PartitionKey.NONE).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readAllItems(new FeedOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + ITEM_ID + "'"; cosmosAsyncContainer.queryItems(query, new FeedOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncScripts() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties = getCosmosUserDefinedFunctionProperties(); CosmosUserDefinedFunctionProperties resultUdf = cosmosAsyncContainer.getScripts().createUserDefinedFunction(cosmosUserDefinedFunctionProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosUserDefinedFunctionProperties.setBody("function() {var x = 15;}"); cosmosAsyncContainer.getScripts().getUserDefinedFunction(resultUdf.getId()).replace(resultUdf).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosTriggerProperties cosmosTriggerProperties = getCosmosTriggerProperties(); CosmosTriggerProperties resultTrigger = cosmosAsyncContainer.getScripts().createTrigger(cosmosTriggerProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(9)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(10)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).replace(resultTrigger).block(); Mockito.verify(tracer, Mockito.times(11)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(12)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(13)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosStoredProcedureProperties procedureProperties = getCosmosStoredProcedureProperties(); CosmosStoredProcedureProperties resultSproc = cosmosAsyncContainer.getScripts().createStoredProcedure(procedureProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(14)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(15)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).replace(resultSproc).block(); Mockito.verify(tracer, Mockito.times(16)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new FeedOptions()).byPage().single().block(); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(18)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @AfterClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void afterClass() { LifeCycleUtils.closeQuietly(client); } private static CosmosUserDefinedFunctionProperties getCosmosUserDefinedFunctionProperties() { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return udf; } private static CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } private static CosmosStoredProcedureProperties getCosmosStoredProcedureProperties() { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.setId(UUID.randomUUID().toString()); storedProcedureDef.setBody("function() {var x = 10;}"); return storedProcedureDef; } }
class CosmosTracerTest extends TestSuiteBase { private static final String ITEM_ID = "tracerDoc"; CosmosAsyncClient client; CosmosAsyncDatabase cosmosAsyncDatabase; CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .buildAsyncClient(); cosmosAsyncDatabase = getSharedCosmosDatabase(client); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(client); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncDatabase() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncDatabase.createContainerIfNotExists(cosmosAsyncContainer.getId(), "/pk", 5000).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncDatabase.readThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllUsers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllContainers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncContainer() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.read().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncContainer.readThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosItemProperties properties = new CosmosItemProperties(); properties.setId(ITEM_ID); cosmosAsyncContainer.createItem(properties).block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.upsertItem(properties, new CosmosItemRequestOptions()).block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readItem(ITEM_ID, PartitionKey.NONE, CosmosItemProperties.class).block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.deleteItem(ITEM_ID, PartitionKey.NONE).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readAllItems(new CosmosQueryRequestOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + ITEM_ID + "'"; cosmosAsyncContainer.queryItems(query, new CosmosQueryRequestOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncScripts() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties = getCosmosUserDefinedFunctionProperties(); CosmosUserDefinedFunctionProperties resultUdf = cosmosAsyncContainer.getScripts().createUserDefinedFunction(cosmosUserDefinedFunctionProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosUserDefinedFunctionProperties.setBody("function() {var x = 15;}"); cosmosAsyncContainer.getScripts().getUserDefinedFunction(resultUdf.getId()).replace(resultUdf).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosTriggerProperties cosmosTriggerProperties = getCosmosTriggerProperties(); CosmosTriggerProperties resultTrigger = cosmosAsyncContainer.getScripts().createTrigger(cosmosTriggerProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(9)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(10)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).replace(resultTrigger).block(); Mockito.verify(tracer, Mockito.times(11)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(12)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(13)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosStoredProcedureProperties procedureProperties = getCosmosStoredProcedureProperties(); CosmosStoredProcedureProperties resultSproc = cosmosAsyncContainer.getScripts().createStoredProcedure(procedureProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(14)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(15)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).replace(resultSproc).block(); Mockito.verify(tracer, Mockito.times(16)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new CosmosQueryRequestOptions()).byPage().single().block(); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(18)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @AfterClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void afterClass() { LifeCycleUtils.closeQuietly(client); } private static CosmosUserDefinedFunctionProperties getCosmosUserDefinedFunctionProperties() { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); return udf; } private static CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } private static CosmosStoredProcedureProperties getCosmosStoredProcedureProperties() { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); return storedProcedureDef; } }
Rather than any string could we validate the span names and attributes being set on the span?
public void cosmosAsyncClient() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); client.readAllDatabases(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + cosmosAsyncDatabase.getId() + "'"; client.queryDatabases(query, new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); }
Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(),
public void cosmosAsyncClient() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); client.readAllDatabases(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + cosmosAsyncDatabase.getId() + "'"; client.queryDatabases(query, new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); }
class CosmosTracerTest extends TestSuiteBase { private static final String ITEM_ID = "tracerDoc"; CosmosAsyncClient client; CosmosAsyncDatabase cosmosAsyncDatabase; CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .buildAsyncClient(); cosmosAsyncDatabase = getSharedCosmosDatabase(client); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(client); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncDatabase() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncDatabase.createContainerIfNotExists(cosmosAsyncContainer.getId(), "/pk", 5000).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncDatabase.readProvisionedThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllUsers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllContainers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncContainer() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.read().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncContainer.readProvisionedThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosItemProperties properties = new CosmosItemProperties(); properties.setId(ITEM_ID); cosmosAsyncContainer.createItem(properties).block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.upsertItem(properties, new CosmosItemRequestOptions()).block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readItem(ITEM_ID, PartitionKey.NONE, CosmosItemProperties.class).block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.deleteItem(ITEM_ID, PartitionKey.NONE).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readAllItems(new FeedOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + ITEM_ID + "'"; cosmosAsyncContainer.queryItems(query, new FeedOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncScripts() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties = getCosmosUserDefinedFunctionProperties(); CosmosUserDefinedFunctionProperties resultUdf = cosmosAsyncContainer.getScripts().createUserDefinedFunction(cosmosUserDefinedFunctionProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosUserDefinedFunctionProperties.setBody("function() {var x = 15;}"); cosmosAsyncContainer.getScripts().getUserDefinedFunction(resultUdf.getId()).replace(resultUdf).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosTriggerProperties cosmosTriggerProperties = getCosmosTriggerProperties(); CosmosTriggerProperties resultTrigger = cosmosAsyncContainer.getScripts().createTrigger(cosmosTriggerProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(9)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(10)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).replace(resultTrigger).block(); Mockito.verify(tracer, Mockito.times(11)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(12)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(13)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosStoredProcedureProperties procedureProperties = getCosmosStoredProcedureProperties(); CosmosStoredProcedureProperties resultSproc = cosmosAsyncContainer.getScripts().createStoredProcedure(procedureProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(14)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(15)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).replace(resultSproc).block(); Mockito.verify(tracer, Mockito.times(16)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new FeedOptions()).byPage().single().block(); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(18)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @AfterClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void afterClass() { LifeCycleUtils.closeQuietly(client); } private static CosmosUserDefinedFunctionProperties getCosmosUserDefinedFunctionProperties() { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return udf; } private static CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } private static CosmosStoredProcedureProperties getCosmosStoredProcedureProperties() { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.setId(UUID.randomUUID().toString()); storedProcedureDef.setBody("function() {var x = 10;}"); return storedProcedureDef; } }
class CosmosTracerTest extends TestSuiteBase { private static final String ITEM_ID = "tracerDoc"; CosmosAsyncClient client; CosmosAsyncDatabase cosmosAsyncDatabase; CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .buildAsyncClient(); cosmosAsyncDatabase = getSharedCosmosDatabase(client); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(client); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncDatabase() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncDatabase.createContainerIfNotExists(cosmosAsyncContainer.getId(), "/pk", 5000).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncDatabase.readThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllUsers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllContainers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncContainer() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.read().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncContainer.readThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosItemProperties properties = new CosmosItemProperties(); properties.setId(ITEM_ID); cosmosAsyncContainer.createItem(properties).block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.upsertItem(properties, new CosmosItemRequestOptions()).block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readItem(ITEM_ID, PartitionKey.NONE, CosmosItemProperties.class).block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.deleteItem(ITEM_ID, PartitionKey.NONE).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readAllItems(new CosmosQueryRequestOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + ITEM_ID + "'"; cosmosAsyncContainer.queryItems(query, new CosmosQueryRequestOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncScripts() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties = getCosmosUserDefinedFunctionProperties(); CosmosUserDefinedFunctionProperties resultUdf = cosmosAsyncContainer.getScripts().createUserDefinedFunction(cosmosUserDefinedFunctionProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosUserDefinedFunctionProperties.setBody("function() {var x = 15;}"); cosmosAsyncContainer.getScripts().getUserDefinedFunction(resultUdf.getId()).replace(resultUdf).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosTriggerProperties cosmosTriggerProperties = getCosmosTriggerProperties(); CosmosTriggerProperties resultTrigger = cosmosAsyncContainer.getScripts().createTrigger(cosmosTriggerProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(9)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(10)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).replace(resultTrigger).block(); Mockito.verify(tracer, Mockito.times(11)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(12)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(13)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosStoredProcedureProperties procedureProperties = getCosmosStoredProcedureProperties(); CosmosStoredProcedureProperties resultSproc = cosmosAsyncContainer.getScripts().createStoredProcedure(procedureProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(14)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(15)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).replace(resultSproc).block(); Mockito.verify(tracer, Mockito.times(16)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new CosmosQueryRequestOptions()).byPage().single().block(); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(18)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @AfterClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void afterClass() { LifeCycleUtils.closeQuietly(client); } private static CosmosUserDefinedFunctionProperties getCosmosUserDefinedFunctionProperties() { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); return udf; } private static CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } private static CosmosStoredProcedureProperties getCosmosStoredProcedureProperties() { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); return storedProcedureDef; } }
Should consider adding tests for `TracerProvider`.
protected static void truncateCollection(CosmosAsyncContainer cosmosContainer) { CosmosContainerProperties cosmosContainerProperties = cosmosContainer.read().block().getProperties(); String cosmosContainerId = cosmosContainerProperties.getId(); logger.info("Truncating collection {} ...", cosmosContainerId); List<String> paths = cosmosContainerProperties.getPartitionKeyDefinition().getPaths(); FeedOptions options = new FeedOptions(); options.setMaxDegreeOfParallelism(-1); int maxItemCount = 100; logger.info("Truncating collection {} documents ...", cosmosContainer.getId()); cosmosContainer.queryItems("SELECT * FROM root", options, CosmosItemProperties.class) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(doc -> { PartitionKey partitionKey = null; Object propertyValue = null; if (paths != null && !paths.isEmpty()) { List<String> pkPath = PathParser.getPathParts(paths.get(0)); propertyValue = ModelBridgeInternal.getObjectByPathFromJsonSerializable(doc, pkPath); if (propertyValue == null) { partitionKey = PartitionKey.NONE; } else { partitionKey = new PartitionKey(propertyValue); } } else { partitionKey = new PartitionKey(null); } return cosmosContainer.deleteItem(doc.getId(), partitionKey); }).then().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); cosmosContainer.getScripts().queryTriggers("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(trigger -> { return cosmosContainer.getScripts().getTrigger(trigger.getId()).delete(); }).then().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); cosmosContainer.getScripts().queryStoredProcedures("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(storedProcedure -> { return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.getId()).delete(new CosmosStoredProcedureRequestOptions()); }).then().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); cosmosContainer.getScripts().queryUserDefinedFunctions("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(udf -> { return cosmosContainer.getScripts().getUserDefinedFunction(udf.getId()).delete(); }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); } @SuppressWarnings({"fallthrough"}) protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (CosmosBridgeInternal.getConsistencyLevel(clientBuilder)) { case EVENTUAL: case CONSISTENT_PREFIX: logger.info(" additional wait in EVENTUAL mode so the replica catch up"); try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); } catch (Exception e) { logger.error("unexpected failure", e); } case SESSION: case BOUNDED_STALENESS: case STRONG: default: break; } } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options, int throughput) { return database.createContainer(cosmosContainerProperties, throughput, options).block().getContainer(); } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options) { return database.createContainer(cosmosContainerProperties, options).block().getContainer(); } private static CosmosContainerProperties getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; final String STRING_FIELD_2 = "stringField2"; final String BOOL_FIELD = "boolField"; final String NULL_FIELD = "nullField"; final String OBJECT_FIELD = "objectField"; final String ARRAY_FIELD = "arrayField"; final String SHORT_STRING_FIELD = "shortStringField"; final String MEDIUM_STRING_FIELD = "mediumStringField"; final String LONG_STRING_FIELD = "longStringField"; final String PARTITION_KEY = "pk"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList<String> partitionKeyPaths = new ArrayList<String>(); partitionKeyPaths.add("/" + PARTITION_KEY); partitionKeyDefinition.setPaths(partitionKeyPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<List<CompositePath>> compositeIndexes = new ArrayList<>(); ArrayList<CompositePath> compositeIndexSimple = new ArrayList<CompositePath>(); CompositePath compositePath1 = new CompositePath(); compositePath1.setPath("/" + NUMBER_FIELD); compositePath1.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); compositePath2.setPath("/" + STRING_FIELD); compositePath2.setOrder(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); ArrayList<CompositePath> compositeIndexMaxColumns = new ArrayList<CompositePath>(); CompositePath compositePath3 = new CompositePath(); compositePath3.setPath("/" + NUMBER_FIELD); compositePath3.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); compositePath4.setPath("/" + STRING_FIELD); compositePath4.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); compositePath5.setPath("/" + NUMBER_FIELD_2); compositePath5.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); compositePath6.setPath("/" + STRING_FIELD_2); compositePath6.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); compositeIndexMaxColumns.add(compositePath5); compositeIndexMaxColumns.add(compositePath6); ArrayList<CompositePath> compositeIndexPrimitiveValues = new ArrayList<CompositePath>(); CompositePath compositePath7 = new CompositePath(); compositePath7.setPath("/" + NUMBER_FIELD); compositePath7.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); compositePath8.setPath("/" + STRING_FIELD); compositePath8.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); compositePath9.setPath("/" + BOOL_FIELD); compositePath9.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); compositePath10.setPath("/" + NULL_FIELD); compositePath10.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); compositeIndexPrimitiveValues.add(compositePath9); compositeIndexPrimitiveValues.add(compositePath10); ArrayList<CompositePath> compositeIndexLongStrings = new ArrayList<CompositePath>(); CompositePath compositePath11 = new CompositePath(); compositePath11.setPath("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); compositePath12.setPath("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); compositePath13.setPath("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); compositePath14.setPath("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); compositeIndexLongStrings.add(compositePath13); compositeIndexLongStrings.add(compositePath14); compositeIndexes.add(compositeIndexSimple); compositeIndexes.add(compositeIndexMaxColumns); compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.setCompositeIndexes(compositeIndexes); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static CosmosAsyncContainer createCollection(CosmosAsyncClient client, String dbId, CosmosContainerProperties collectionDefinition) { return client.getDatabase(dbId).createContainer(collectionDefinition).block().getContainer(); } public static void deleteCollection(CosmosAsyncClient client, String dbId, String collectionId) { client.getDatabase(dbId).getContainer(collectionId).delete().block(); } public static CosmosItemProperties createDocument(CosmosAsyncContainer cosmosContainer, CosmosItemProperties item) { return BridgeInternal.getProperties(cosmosContainer.createItem(item).block()); } public <T> Flux<CosmosAsyncItemResponse<T>> bulkInsert(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList, int concurrencyLevel) { List<Mono<CosmosAsyncItemResponse<T>>> result = new ArrayList<>(documentDefinitionList.size()); for (T docDef : documentDefinitionList) { result.add(cosmosContainer.createItem(docDef)); } return Flux.merge(Flux.fromIterable(result), concurrencyLevel); } public <T> List<T> bulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList) { return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> itemResponse.getItem()) .collectList() .block(); } public void voidBulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<CosmosItemProperties> documentDefinitionList) { bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> BridgeInternal.getProperties(itemResponse)) .then() .block(); } public static CosmosAsyncUser createUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties userSettings) { return client.getDatabase(databaseId).read().block().getDatabase().createUser(userSettings).block().getUser(); } public static CosmosAsyncUser safeCreateUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties user) { deleteUserIfExists(client, databaseId, user.getId()); return createUser(client, databaseId, user); } private static CosmosAsyncContainer safeCreateCollection(CosmosAsyncClient client, String databaseId, CosmosContainerProperties collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.getId()); return createCollection(client.getDatabase(databaseId), collection, options); } static protected CosmosContainerProperties getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndexWithIdAsPartitionKey() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/id")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/mypk")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex(List<String> partitionKeyPath) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); partitionKeyDef.setPaths(partitionKeyPath); 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); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static void deleteCollectionIfExists(CosmosAsyncClient client, String databaseId, String collectionId) { CosmosAsyncDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); List<CosmosContainerProperties> res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) .collectList() .block(); if (!res.isEmpty()) { deleteCollection(database, collectionId); } } public static void deleteCollection(CosmosAsyncDatabase cosmosDatabase, String collectionId) { cosmosDatabase.getContainer(collectionId).delete().block(); } public static void deleteCollection(CosmosAsyncContainer cosmosContainer) { cosmosContainer.delete().block(); } public static void deleteDocumentIfExists(CosmosAsyncClient client, String databaseId, String collectionId, String docId) { FeedOptions options = new FeedOptions(); options.setPartitionKey(new PartitionKey(docId)); CosmosAsyncContainer cosmosContainer = client.getDatabase(databaseId).getContainer(collectionId); List<CosmosItemProperties> res = cosmosContainer .queryItems(String.format("SELECT * FROM root r where r.id = '%s'", docId), options, CosmosItemProperties.class) .byPage() .flatMap(page -> Flux.fromIterable(page.getResults())) .collectList().block(); if (!res.isEmpty()) { deleteDocument(cosmosContainer, docId); } } public static void safeDeleteDocument(CosmosAsyncContainer cosmosContainer, String documentId, Object partitionKey) { if (cosmosContainer != null && documentId != null) { try { cosmosContainer.deleteItem(documentId, new PartitionKey(partitionKey)).block(); } catch (Exception e) { CosmosException dce = Utils.as(e, CosmosException.class); if (dce == null || dce.getStatusCode() != 404) { throw e; } } } } public static void deleteDocument(CosmosAsyncContainer cosmosContainer, String documentId) { cosmosContainer.deleteItem(documentId, PartitionKey.NONE).block(); } public static void deleteUserIfExists(CosmosAsyncClient client, String databaseId, String userId) { CosmosAsyncDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); List<CosmosUserProperties> res = database .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) .collectList().block(); if (!res.isEmpty()) { deleteUser(database, userId); } } public static void deleteUser(CosmosAsyncDatabase database, String userId) { database.getUser(userId).read().block().getUser().delete().block(); } static private CosmosAsyncDatabase safeCreateDatabase(CosmosAsyncClient client, CosmosDatabaseProperties databaseSettings) { safeDeleteDatabase(client.getDatabase(databaseSettings.getId())); return client.createDatabase(databaseSettings).block().getDatabase(); } static protected CosmosAsyncDatabase createDatabase(CosmosAsyncClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); return client.createDatabase(databaseSettings).block().getDatabase(); } static protected CosmosDatabase createSyncDatabase(CosmosClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); try { return client.createDatabase(databaseSettings).getDatabase(); } catch (CosmosException e) { e.printStackTrace(); } return null; } static protected CosmosAsyncDatabase createDatabaseIfNotExists(CosmosAsyncClient client, String databaseId) { List<CosmosDatabaseProperties> res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) .collectList() .block(); if (res.size() != 0) { return client.getDatabase(databaseId).read().block().getDatabase(); } else { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); return client.createDatabase(databaseSettings).block().getDatabase(); } } static protected void safeDeleteDatabase(CosmosAsyncDatabase database) { if (database != null) { try { database.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteSyncDatabase(CosmosDatabase database) { if (database != null) { try { logger.info("attempting to delete database ...."); database.delete(); logger.info("database deletion completed"); } catch (Exception e) { logger.error("failed to delete sync database", e); } } } static protected void safeDeleteAllCollections(CosmosAsyncDatabase database) { if (database != null) { List<CosmosContainerProperties> collections = database.readAllContainers() .collectList() .block(); for(CosmosContainerProperties collection: collections) { database.getContainer(collection.getId()).delete().block(); } } } static protected void safeDeleteCollection(CosmosAsyncContainer collection) { if (collection != null) { try { collection.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteCollection(CosmosAsyncDatabase database, String collectionId) { if (database != null && collectionId != null) { try { database.getContainer(collectionId).delete().block(); } catch (Exception e) { } } } static protected void safeCloseAsync(CosmosAsyncClient client) { if (client != null) { new Thread(() -> { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } }).start(); } } static protected void safeClose(CosmosAsyncClient client) { if (client != null) { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } } } static protected void safeCloseSyncClient(CosmosClient client) { if (client != null) { try { logger.info("closing client ..."); client.close(); logger.info("closing client completed"); } catch (Exception e) { logger.error("failed to close client", e); } } } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator) { validateSuccess(single, validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator, long timeout) { validateSuccess(single.flux(), validator, timeout); } @SuppressWarnings("rawtypes") public static <T extends CosmosResponse> void validateSuccess(Flux<T> flowable, CosmosResponseValidator<T> validator, long timeout) { TestSubscriber<T> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T, U extends CosmosResponse> void validateFailure(Mono<U> mono, FailureValidator validator) throws InterruptedException { validateFailure(mono.flux(), validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public static <T extends Resource, U extends CosmosResponse> void validateFailure(Flux<U> flowable, FailureValidator validator, long timeout) throws InterruptedException { TestSubscriber<CosmosResponse> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosAsyncItemResponse> void validateItemSuccess( Mono<T> responseMono, CosmosItemResponseValidator validator) { TestSubscriber<CosmosAsyncItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosAsyncItemResponse> void validateItemFailure( Mono<T> responseMono, FailureValidator validator) { TestSubscriber<CosmosAsyncItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } public <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator) { validateQuerySuccess(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); validator.validate(testSubscriber.values()); } public <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator) { validateQueryFailure(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.getEvents().get(1)).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @DataProvider public static Object[][] clientBuilders() { return new Object[][]{{createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)}}; } @DataProvider public static Object[][] clientBuildersWithSessionConsistency() { return new Object[][]{ {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.HTTPS, false, null, true)}, {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.TCP, false, null, true)}, {createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)} }; } static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); return ConsistencyLevel.valueOf(consistency); } logger.error("INVALID configured test consistency [{}].", consistency); throw new IllegalStateException("INVALID configured test consistency " + consistency); } static List<String> parsePreferredLocation(String preferredLocations) { if (StringUtils.isEmpty(preferredLocations)) { return null; } try { return objectMapper.readValue(preferredLocations, new TypeReference<List<String>>() { }); } catch (Exception e) { logger.error("INVALID configured test preferredLocations [{}].", preferredLocations); throw new IllegalStateException("INVALID configured test preferredLocations " + preferredLocations); } } static List<Protocol> parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } List<Protocol> protocolList = new ArrayList<>(); try { List<String> protocolStrings = objectMapper.readValue(protocols, new TypeReference<List<String>>() { }); for(String protocol : protocolStrings) { protocolList.add(Protocol.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, protocol))); } return protocolList; } catch (Exception e) { logger.error("INVALID configured test protocols [{}].", protocols); throw new IllegalStateException("INVALID configured test protocols " + protocols); } } @DataProvider public static Object[][] simpleClientBuildersWithDirect() { return simpleClientBuildersWithDirect(true, toArray(protocols)); } @DataProvider public static Object[][] simpleClientBuildersWithDirectHttps() { return simpleClientBuildersWithDirect(true, Protocol.HTTPS); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcp() { return simpleClientBuildersWithDirect(true, Protocol.TCP); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return simpleClientBuildersWithDirect(false, Protocol.TCP); } private static Object[][] simpleClientBuildersWithDirect(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); List<ConsistencyLevel> testConsistencies = ImmutableList.of(ConsistencyLevel.EVENTUAL); boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient( consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); } @DataProvider public static Object[][] clientBuildersWithDirect() { return clientBuildersWithDirectAllConsistencies(true, toArray(protocols)); } @DataProvider public static Object[][] clientBuildersWithDirectHttps() { return clientBuildersWithDirectAllConsistencies(true, Protocol.HTTPS); } @DataProvider public static Object[][] clientBuildersWithDirectTcp() { return clientBuildersWithDirectAllConsistencies(true, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return clientBuildersWithDirectAllConsistencies(false, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectSession() { return clientBuildersWithDirectSession(true, toArray(protocols)); } static Protocol[] toArray(List<Protocol> protocols) { return protocols.toArray(new Protocol[protocols.size()]); } private static Object[][] clientBuildersWithDirectSession(boolean contentResponseOnWriteEnabled, Protocol... protocols) { return clientBuildersWithDirect(new ArrayList<ConsistencyLevel>() {{ add(ConsistencyLevel.SESSION); }}, contentResponseOnWriteEnabled, protocols); } private static Object[][] clientBuildersWithDirectAllConsistencies(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); return clientBuildersWithDirect(desiredConsistencies, contentResponseOnWriteEnabled, protocols); } static List<ConsistencyLevel> parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } List<ConsistencyLevel> consistencyLevels = new ArrayList<>(); try { List<String> consistencyStrings = objectMapper.readValue(consistencies, new TypeReference<List<String>>() {}); for(String consistency : consistencyStrings) { consistencyLevels.add(ConsistencyLevel.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency))); } return consistencyLevels; } catch (Exception e) { logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); } } @SuppressWarnings("fallthrough") static List<ConsistencyLevel> allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List<ConsistencyLevel> testConsistencies = new ArrayList<>(); switch (accountConsistency) { case STRONG: testConsistencies.add(ConsistencyLevel.STRONG); case BOUNDED_STALENESS: testConsistencies.add(ConsistencyLevel.BOUNDED_STALENESS); case SESSION: testConsistencies.add(ConsistencyLevel.SESSION); case CONSISTENT_PREFIX: testConsistencies.add(ConsistencyLevel.CONSISTENT_PREFIX); case EVENTUAL: testConsistencies.add(ConsistencyLevel.EVENTUAL); break; default: throw new IllegalStateException("INVALID configured test consistency " + accountConsistency); } return testConsistencies; } private static Object[][] clientBuildersWithDirect(List<ConsistencyLevel> testConsistencies, boolean contentResponseOnWriteEnabled, Protocol... protocols) { boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(c -> new Object[]{c}).collect(Collectors.toList()).toArray(new Object[0][]); } static protected CosmosClientBuilder createGatewayHouseKeepingDocumentClient(boolean contentResponseOnWriteEnabled) { ThrottlingRetryOptions options = new ThrottlingRetryOptions(); options.setMaxRetryWaitTime(Duration.ofSeconds(SUITE_SETUP_TIMEOUT)); GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .throttlingRetryOptions(options) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(ConsistencyLevel.SESSION); } static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .multipleWriteRegionsEnabled(multiMasterEnabled) .preferredRegions(preferredRegions) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); } static protected CosmosClientBuilder createGatewayRxDocumentClient() { return createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true); } static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, Protocol protocol, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { CosmosClientBuilder builder = new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .directMode(DirectConnectionConfig.getDefaultConfig()) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); if (preferredRegions != null) { builder.preferredRegions(preferredRegions); } if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.SESSION) { builder.multipleWriteRegionsEnabled(true); } Configs configs = spy(new Configs()); doAnswer((Answer<Protocol>)invocation -> protocol).when(configs).getProtocol(); return injectConfigs(builder, configs); } protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { return Math.max((totalExpectedResult + maxPageSize - 1 ) / maxPageSize, 1); } @DataProvider(name = "queryMetricsArgProvider") public Object[][] queryMetricsArgProvider() { return new Object[][]{ {true}, {false}, }; } public static CosmosClientBuilder copyCosmosClientBuilder(CosmosClientBuilder builder) { return CosmosBridgeInternal.cloneCosmosClientBuilder(builder); } }
}
protected static void truncateCollection(CosmosAsyncContainer cosmosContainer) { CosmosContainerProperties cosmosContainerProperties = cosmosContainer.read().block().getProperties(); String cosmosContainerId = cosmosContainerProperties.getId(); logger.info("Truncating collection {} ...", cosmosContainerId); List<String> paths = cosmosContainerProperties.getPartitionKeyDefinition().getPaths(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(-1); int maxItemCount = 100; logger.info("Truncating collection {} documents ...", cosmosContainer.getId()); cosmosContainer.queryItems("SELECT * FROM root", options, CosmosItemProperties.class) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(doc -> { PartitionKey partitionKey = null; Object propertyValue = null; if (paths != null && !paths.isEmpty()) { List<String> pkPath = PathParser.getPathParts(paths.get(0)); propertyValue = ModelBridgeInternal.getObjectByPathFromJsonSerializable(doc, pkPath); if (propertyValue == null) { partitionKey = PartitionKey.NONE; } else { partitionKey = new PartitionKey(propertyValue); } } else { partitionKey = new PartitionKey(null); } return cosmosContainer.deleteItem(doc.getId(), partitionKey); }).then().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); cosmosContainer.getScripts().queryTriggers("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(trigger -> { return cosmosContainer.getScripts().getTrigger(trigger.getId()).delete(); }).then().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); cosmosContainer.getScripts().queryStoredProcedures("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(storedProcedure -> { return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.getId()).delete(new CosmosStoredProcedureRequestOptions()); }).then().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); cosmosContainer.getScripts().queryUserDefinedFunctions("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(udf -> { return cosmosContainer.getScripts().getUserDefinedFunction(udf.getId()).delete(); }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); } @SuppressWarnings({"fallthrough"}) protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (CosmosBridgeInternal.getConsistencyLevel(clientBuilder)) { case EVENTUAL: case CONSISTENT_PREFIX: logger.info(" additional wait in EVENTUAL mode so the replica catch up"); try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); } catch (Exception e) { logger.error("unexpected failure", e); } case SESSION: case BOUNDED_STALENESS: case STRONG: default: break; } } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options, int throughput) { database.createContainer(cosmosContainerProperties, ThroughputProperties.createManualThroughput(throughput), options).block(); return database.getContainer(cosmosContainerProperties.getId()); } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options) { database.createContainer(cosmosContainerProperties, options).block(); return database.getContainer(cosmosContainerProperties.getId()); } private static CosmosContainerProperties getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; final String STRING_FIELD_2 = "stringField2"; final String BOOL_FIELD = "boolField"; final String NULL_FIELD = "nullField"; final String OBJECT_FIELD = "objectField"; final String ARRAY_FIELD = "arrayField"; final String SHORT_STRING_FIELD = "shortStringField"; final String MEDIUM_STRING_FIELD = "mediumStringField"; final String LONG_STRING_FIELD = "longStringField"; final String PARTITION_KEY = "pk"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList<String> partitionKeyPaths = new ArrayList<String>(); partitionKeyPaths.add("/" + PARTITION_KEY); partitionKeyDefinition.setPaths(partitionKeyPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<List<CompositePath>> compositeIndexes = new ArrayList<>(); ArrayList<CompositePath> compositeIndexSimple = new ArrayList<CompositePath>(); CompositePath compositePath1 = new CompositePath(); compositePath1.setPath("/" + NUMBER_FIELD); compositePath1.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); compositePath2.setPath("/" + STRING_FIELD); compositePath2.setOrder(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); ArrayList<CompositePath> compositeIndexMaxColumns = new ArrayList<CompositePath>(); CompositePath compositePath3 = new CompositePath(); compositePath3.setPath("/" + NUMBER_FIELD); compositePath3.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); compositePath4.setPath("/" + STRING_FIELD); compositePath4.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); compositePath5.setPath("/" + NUMBER_FIELD_2); compositePath5.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); compositePath6.setPath("/" + STRING_FIELD_2); compositePath6.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); compositeIndexMaxColumns.add(compositePath5); compositeIndexMaxColumns.add(compositePath6); ArrayList<CompositePath> compositeIndexPrimitiveValues = new ArrayList<CompositePath>(); CompositePath compositePath7 = new CompositePath(); compositePath7.setPath("/" + NUMBER_FIELD); compositePath7.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); compositePath8.setPath("/" + STRING_FIELD); compositePath8.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); compositePath9.setPath("/" + BOOL_FIELD); compositePath9.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); compositePath10.setPath("/" + NULL_FIELD); compositePath10.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); compositeIndexPrimitiveValues.add(compositePath9); compositeIndexPrimitiveValues.add(compositePath10); ArrayList<CompositePath> compositeIndexLongStrings = new ArrayList<CompositePath>(); CompositePath compositePath11 = new CompositePath(); compositePath11.setPath("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); compositePath12.setPath("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); compositePath13.setPath("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); compositePath14.setPath("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); compositeIndexLongStrings.add(compositePath13); compositeIndexLongStrings.add(compositePath14); compositeIndexes.add(compositeIndexSimple); compositeIndexes.add(compositeIndexMaxColumns); compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.setCompositeIndexes(compositeIndexes); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static CosmosAsyncContainer createCollection(CosmosAsyncClient client, String dbId, CosmosContainerProperties collectionDefinition) { CosmosAsyncDatabase database = client.getDatabase(dbId); database.createContainer(collectionDefinition).block(); return database.getContainer(collectionDefinition.getId()); } public static void deleteCollection(CosmosAsyncClient client, String dbId, String collectionId) { client.getDatabase(dbId).getContainer(collectionId).delete().block(); } public static CosmosItemProperties createDocument(CosmosAsyncContainer cosmosContainer, CosmosItemProperties item) { return BridgeInternal.getProperties(cosmosContainer.createItem(item).block()); } public <T> Flux<CosmosItemResponse<T>> bulkInsert(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList, int concurrencyLevel) { List<Mono<CosmosItemResponse<T>>> result = new ArrayList<>(documentDefinitionList.size()); for (T docDef : documentDefinitionList) { result.add(cosmosContainer.createItem(docDef)); } return Flux.merge(Flux.fromIterable(result), concurrencyLevel); } public <T> List<T> bulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList) { return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> itemResponse.getItem()) .collectList() .block(); } public void voidBulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<CosmosItemProperties> documentDefinitionList) { bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> BridgeInternal.getProperties(itemResponse)) .then() .block(); } public static CosmosAsyncUser createUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties userSettings) { CosmosAsyncDatabase database = client.getDatabase(databaseId); CosmosUserResponse userResponse = database.createUser(userSettings).block(); return database.getUser(userResponse.getProperties().getId()); } public static CosmosAsyncUser safeCreateUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties user) { deleteUserIfExists(client, databaseId, user.getId()); return createUser(client, databaseId, user); } private static CosmosAsyncContainer safeCreateCollection(CosmosAsyncClient client, String databaseId, CosmosContainerProperties collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.getId()); return createCollection(client.getDatabase(databaseId), collection, options); } static protected CosmosContainerProperties getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndexWithIdAsPartitionKey() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/id")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/mypk")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex(List<String> partitionKeyPath) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); partitionKeyDef.setPaths(partitionKeyPath); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<IncludedPath> includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath("/*"); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static void deleteCollectionIfExists(CosmosAsyncClient client, String databaseId, String collectionId) { CosmosAsyncDatabase database = client.getDatabase(databaseId); database.read().block(); List<CosmosContainerProperties> res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) .collectList() .block(); if (!res.isEmpty()) { deleteCollection(database, collectionId); } } public static void deleteCollection(CosmosAsyncDatabase cosmosDatabase, String collectionId) { cosmosDatabase.getContainer(collectionId).delete().block(); } public static void deleteCollection(CosmosAsyncContainer cosmosContainer) { cosmosContainer.delete().block(); } public static void deleteDocumentIfExists(CosmosAsyncClient client, String databaseId, String collectionId, String docId) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setPartitionKey(new PartitionKey(docId)); CosmosAsyncContainer cosmosContainer = client.getDatabase(databaseId).getContainer(collectionId); List<CosmosItemProperties> res = cosmosContainer .queryItems(String.format("SELECT * FROM root r where r.id = '%s'", docId), options, CosmosItemProperties.class) .byPage() .flatMap(page -> Flux.fromIterable(page.getResults())) .collectList().block(); if (!res.isEmpty()) { deleteDocument(cosmosContainer, docId); } } public static void safeDeleteDocument(CosmosAsyncContainer cosmosContainer, String documentId, Object partitionKey) { if (cosmosContainer != null && documentId != null) { try { cosmosContainer.deleteItem(documentId, new PartitionKey(partitionKey)).block(); } catch (Exception e) { CosmosException dce = Utils.as(e, CosmosException.class); if (dce == null || dce.getStatusCode() != 404) { throw e; } } } } public static void deleteDocument(CosmosAsyncContainer cosmosContainer, String documentId) { cosmosContainer.deleteItem(documentId, PartitionKey.NONE).block(); } public static void deleteUserIfExists(CosmosAsyncClient client, String databaseId, String userId) { CosmosAsyncDatabase database = client.getDatabase(databaseId); client.getDatabase(databaseId).read().block(); List<CosmosUserProperties> res = database .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) .collectList().block(); if (!res.isEmpty()) { deleteUser(database, userId); } } public static void deleteUser(CosmosAsyncDatabase database, String userId) { database.getUser(userId).delete().block(); } static private CosmosAsyncDatabase safeCreateDatabase(CosmosAsyncClient client, CosmosDatabaseProperties databaseSettings) { safeDeleteDatabase(client.getDatabase(databaseSettings.getId())); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } static protected CosmosAsyncDatabase createDatabase(CosmosAsyncClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } static protected CosmosDatabase createSyncDatabase(CosmosClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); try { client.createDatabase(databaseSettings); return client.getDatabase(databaseSettings.getId()); } catch (CosmosException e) { e.printStackTrace(); } return null; } static protected CosmosAsyncDatabase createDatabaseIfNotExists(CosmosAsyncClient client, String databaseId) { List<CosmosDatabaseProperties> res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) .collectList() .block(); if (res.size() != 0) { CosmosAsyncDatabase database = client.getDatabase(databaseId); database.read().block(); return database; } else { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } } static protected void safeDeleteDatabase(CosmosAsyncDatabase database) { if (database != null) { try { database.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteSyncDatabase(CosmosDatabase database) { if (database != null) { try { logger.info("attempting to delete database ...."); database.delete(); logger.info("database deletion completed"); } catch (Exception e) { logger.error("failed to delete sync database", e); } } } static protected void safeDeleteAllCollections(CosmosAsyncDatabase database) { if (database != null) { List<CosmosContainerProperties> collections = database.readAllContainers() .collectList() .block(); for(CosmosContainerProperties collection: collections) { database.getContainer(collection.getId()).delete().block(); } } } static protected void safeDeleteCollection(CosmosAsyncContainer collection) { if (collection != null) { try { collection.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteCollection(CosmosAsyncDatabase database, String collectionId) { if (database != null && collectionId != null) { try { database.getContainer(collectionId).delete().block(); } catch (Exception e) { } } } static protected void safeCloseAsync(CosmosAsyncClient client) { if (client != null) { new Thread(() -> { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } }).start(); } } static protected void safeClose(CosmosAsyncClient client) { if (client != null) { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } } } static protected void safeCloseSyncClient(CosmosClient client) { if (client != null) { try { logger.info("closing client ..."); client.close(); logger.info("closing client completed"); } catch (Exception e) { logger.error("failed to close client", e); } } } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator) { validateSuccess(single, validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator, long timeout) { validateSuccess(single.flux(), validator, timeout); } @SuppressWarnings("rawtypes") public static <T extends CosmosResponse> void validateSuccess(Flux<T> flowable, CosmosResponseValidator<T> validator, long timeout) { TestSubscriber<T> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T, U extends CosmosResponse> void validateFailure(Mono<U> mono, FailureValidator validator) throws InterruptedException { validateFailure(mono.flux(), validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public static <T extends Resource, U extends CosmosResponse> void validateFailure(Flux<U> flowable, FailureValidator validator, long timeout) throws InterruptedException { TestSubscriber<CosmosResponse> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosItemResponse> void validateItemSuccess( Mono<T> responseMono, CosmosItemResponseValidator validator) { TestSubscriber<CosmosItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosItemResponse> void validateItemFailure( Mono<T> responseMono, FailureValidator validator) { TestSubscriber<CosmosItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } public <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator) { validateQuerySuccess(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); validator.validate(testSubscriber.values()); } public <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator) { validateQueryFailure(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.getEvents().get(1)).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @DataProvider public static Object[][] clientBuilders() { return new Object[][]{{createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)}}; } @DataProvider public static Object[][] clientBuildersWithSessionConsistency() { return new Object[][]{ {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.HTTPS, false, null, true)}, {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.TCP, false, null, true)}, {createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)} }; } static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); return ConsistencyLevel.valueOf(consistency); } logger.error("INVALID configured test consistency [{}].", consistency); throw new IllegalStateException("INVALID configured test consistency " + consistency); } static List<String> parsePreferredLocation(String preferredLocations) { if (StringUtils.isEmpty(preferredLocations)) { return null; } try { return objectMapper.readValue(preferredLocations, new TypeReference<List<String>>() { }); } catch (Exception e) { logger.error("INVALID configured test preferredLocations [{}].", preferredLocations); throw new IllegalStateException("INVALID configured test preferredLocations " + preferredLocations); } } static List<Protocol> parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } List<Protocol> protocolList = new ArrayList<>(); try { List<String> protocolStrings = objectMapper.readValue(protocols, new TypeReference<List<String>>() { }); for(String protocol : protocolStrings) { protocolList.add(Protocol.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, protocol))); } return protocolList; } catch (Exception e) { logger.error("INVALID configured test protocols [{}].", protocols); throw new IllegalStateException("INVALID configured test protocols " + protocols); } } @DataProvider public static Object[][] simpleClientBuildersWithDirect() { return simpleClientBuildersWithDirect(true, toArray(protocols)); } @DataProvider public static Object[][] simpleClientBuildersWithDirectHttps() { return simpleClientBuildersWithDirect(true, Protocol.HTTPS); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcp() { return simpleClientBuildersWithDirect(true, Protocol.TCP); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return simpleClientBuildersWithDirect(false, Protocol.TCP); } private static Object[][] simpleClientBuildersWithDirect(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); List<ConsistencyLevel> testConsistencies = ImmutableList.of(ConsistencyLevel.EVENTUAL); boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient( consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); } @DataProvider public static Object[][] clientBuildersWithDirect() { return clientBuildersWithDirectAllConsistencies(true, toArray(protocols)); } @DataProvider public static Object[][] clientBuildersWithDirectHttps() { return clientBuildersWithDirectAllConsistencies(true, Protocol.HTTPS); } @DataProvider public static Object[][] clientBuildersWithDirectTcp() { return clientBuildersWithDirectAllConsistencies(true, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return clientBuildersWithDirectAllConsistencies(false, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectSession() { return clientBuildersWithDirectSession(true, toArray(protocols)); } static Protocol[] toArray(List<Protocol> protocols) { return protocols.toArray(new Protocol[protocols.size()]); } private static Object[][] clientBuildersWithDirectSession(boolean contentResponseOnWriteEnabled, Protocol... protocols) { return clientBuildersWithDirect(new ArrayList<ConsistencyLevel>() {{ add(ConsistencyLevel.SESSION); }}, contentResponseOnWriteEnabled, protocols); } private static Object[][] clientBuildersWithDirectAllConsistencies(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); return clientBuildersWithDirect(desiredConsistencies, contentResponseOnWriteEnabled, protocols); } static List<ConsistencyLevel> parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } List<ConsistencyLevel> consistencyLevels = new ArrayList<>(); try { List<String> consistencyStrings = objectMapper.readValue(consistencies, new TypeReference<List<String>>() {}); for(String consistency : consistencyStrings) { consistencyLevels.add(ConsistencyLevel.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency))); } return consistencyLevels; } catch (Exception e) { logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); } } @SuppressWarnings("fallthrough") static List<ConsistencyLevel> allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List<ConsistencyLevel> testConsistencies = new ArrayList<>(); switch (accountConsistency) { case STRONG: testConsistencies.add(ConsistencyLevel.STRONG); case BOUNDED_STALENESS: testConsistencies.add(ConsistencyLevel.BOUNDED_STALENESS); case SESSION: testConsistencies.add(ConsistencyLevel.SESSION); case CONSISTENT_PREFIX: testConsistencies.add(ConsistencyLevel.CONSISTENT_PREFIX); case EVENTUAL: testConsistencies.add(ConsistencyLevel.EVENTUAL); break; default: throw new IllegalStateException("INVALID configured test consistency " + accountConsistency); } return testConsistencies; } private static Object[][] clientBuildersWithDirect(List<ConsistencyLevel> testConsistencies, boolean contentResponseOnWriteEnabled, Protocol... protocols) { boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(c -> new Object[]{c}).collect(Collectors.toList()).toArray(new Object[0][]); } static protected CosmosClientBuilder createGatewayHouseKeepingDocumentClient(boolean contentResponseOnWriteEnabled) { ThrottlingRetryOptions options = new ThrottlingRetryOptions(); options.setMaxRetryWaitTime(Duration.ofSeconds(SUITE_SETUP_TIMEOUT)); GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .throttlingRetryOptions(options) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(ConsistencyLevel.SESSION); } static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .multipleWriteRegionsEnabled(multiMasterEnabled) .preferredRegions(preferredRegions) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); } static protected CosmosClientBuilder createGatewayRxDocumentClient() { return createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true); } static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, Protocol protocol, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { CosmosClientBuilder builder = new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .directMode(DirectConnectionConfig.getDefaultConfig()) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); if (preferredRegions != null) { builder.preferredRegions(preferredRegions); } if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.SESSION) { builder.multipleWriteRegionsEnabled(true); } Configs configs = spy(new Configs()); doAnswer((Answer<Protocol>)invocation -> protocol).when(configs).getProtocol(); return injectConfigs(builder, configs); } protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { return Math.max((totalExpectedResult + maxPageSize - 1 ) / maxPageSize, 1); } @DataProvider(name = "queryMetricsArgProvider") public Object[][] queryMetricsArgProvider() { return new Object[][]{ {true}, {false}, }; } public static CosmosClientBuilder copyCosmosClientBuilder(CosmosClientBuilder builder) { return CosmosBridgeInternal.cloneCosmosClientBuilder(builder); } }
class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(CosmosAsyncClient client) { return new DatabaseManagerImpl(client); } private final CosmosAsyncClient client; private DatabaseManagerImpl(CosmosAsyncClient client) { this.client = client; } @Override public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override public Mono<CosmosAsyncDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseDefinition) { return client.createDatabase(databaseDefinition); } @Override public CosmosAsyncDatabase getDatabase(String id) { return client.getDatabase(id); } }
class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(CosmosAsyncClient client) { return new DatabaseManagerImpl(client); } private final CosmosAsyncClient client; private DatabaseManagerImpl(CosmosAsyncClient client) { this.client = client; } @Override public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseDefinition) { return client.createDatabase(databaseDefinition); } @Override public CosmosAsyncDatabase getDatabase(String id) { return client.getDatabase(id); } }
Also, consider adding a nesting call example to validate the behavior of spans.
protected static void truncateCollection(CosmosAsyncContainer cosmosContainer) { CosmosContainerProperties cosmosContainerProperties = cosmosContainer.read().block().getProperties(); String cosmosContainerId = cosmosContainerProperties.getId(); logger.info("Truncating collection {} ...", cosmosContainerId); List<String> paths = cosmosContainerProperties.getPartitionKeyDefinition().getPaths(); FeedOptions options = new FeedOptions(); options.setMaxDegreeOfParallelism(-1); int maxItemCount = 100; logger.info("Truncating collection {} documents ...", cosmosContainer.getId()); cosmosContainer.queryItems("SELECT * FROM root", options, CosmosItemProperties.class) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(doc -> { PartitionKey partitionKey = null; Object propertyValue = null; if (paths != null && !paths.isEmpty()) { List<String> pkPath = PathParser.getPathParts(paths.get(0)); propertyValue = ModelBridgeInternal.getObjectByPathFromJsonSerializable(doc, pkPath); if (propertyValue == null) { partitionKey = PartitionKey.NONE; } else { partitionKey = new PartitionKey(propertyValue); } } else { partitionKey = new PartitionKey(null); } return cosmosContainer.deleteItem(doc.getId(), partitionKey); }).then().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); cosmosContainer.getScripts().queryTriggers("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(trigger -> { return cosmosContainer.getScripts().getTrigger(trigger.getId()).delete(); }).then().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); cosmosContainer.getScripts().queryStoredProcedures("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(storedProcedure -> { return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.getId()).delete(new CosmosStoredProcedureRequestOptions()); }).then().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); cosmosContainer.getScripts().queryUserDefinedFunctions("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(udf -> { return cosmosContainer.getScripts().getUserDefinedFunction(udf.getId()).delete(); }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); } @SuppressWarnings({"fallthrough"}) protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (CosmosBridgeInternal.getConsistencyLevel(clientBuilder)) { case EVENTUAL: case CONSISTENT_PREFIX: logger.info(" additional wait in EVENTUAL mode so the replica catch up"); try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); } catch (Exception e) { logger.error("unexpected failure", e); } case SESSION: case BOUNDED_STALENESS: case STRONG: default: break; } } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options, int throughput) { return database.createContainer(cosmosContainerProperties, throughput, options).block().getContainer(); } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options) { return database.createContainer(cosmosContainerProperties, options).block().getContainer(); } private static CosmosContainerProperties getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; final String STRING_FIELD_2 = "stringField2"; final String BOOL_FIELD = "boolField"; final String NULL_FIELD = "nullField"; final String OBJECT_FIELD = "objectField"; final String ARRAY_FIELD = "arrayField"; final String SHORT_STRING_FIELD = "shortStringField"; final String MEDIUM_STRING_FIELD = "mediumStringField"; final String LONG_STRING_FIELD = "longStringField"; final String PARTITION_KEY = "pk"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList<String> partitionKeyPaths = new ArrayList<String>(); partitionKeyPaths.add("/" + PARTITION_KEY); partitionKeyDefinition.setPaths(partitionKeyPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<List<CompositePath>> compositeIndexes = new ArrayList<>(); ArrayList<CompositePath> compositeIndexSimple = new ArrayList<CompositePath>(); CompositePath compositePath1 = new CompositePath(); compositePath1.setPath("/" + NUMBER_FIELD); compositePath1.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); compositePath2.setPath("/" + STRING_FIELD); compositePath2.setOrder(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); ArrayList<CompositePath> compositeIndexMaxColumns = new ArrayList<CompositePath>(); CompositePath compositePath3 = new CompositePath(); compositePath3.setPath("/" + NUMBER_FIELD); compositePath3.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); compositePath4.setPath("/" + STRING_FIELD); compositePath4.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); compositePath5.setPath("/" + NUMBER_FIELD_2); compositePath5.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); compositePath6.setPath("/" + STRING_FIELD_2); compositePath6.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); compositeIndexMaxColumns.add(compositePath5); compositeIndexMaxColumns.add(compositePath6); ArrayList<CompositePath> compositeIndexPrimitiveValues = new ArrayList<CompositePath>(); CompositePath compositePath7 = new CompositePath(); compositePath7.setPath("/" + NUMBER_FIELD); compositePath7.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); compositePath8.setPath("/" + STRING_FIELD); compositePath8.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); compositePath9.setPath("/" + BOOL_FIELD); compositePath9.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); compositePath10.setPath("/" + NULL_FIELD); compositePath10.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); compositeIndexPrimitiveValues.add(compositePath9); compositeIndexPrimitiveValues.add(compositePath10); ArrayList<CompositePath> compositeIndexLongStrings = new ArrayList<CompositePath>(); CompositePath compositePath11 = new CompositePath(); compositePath11.setPath("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); compositePath12.setPath("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); compositePath13.setPath("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); compositePath14.setPath("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); compositeIndexLongStrings.add(compositePath13); compositeIndexLongStrings.add(compositePath14); compositeIndexes.add(compositeIndexSimple); compositeIndexes.add(compositeIndexMaxColumns); compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.setCompositeIndexes(compositeIndexes); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static CosmosAsyncContainer createCollection(CosmosAsyncClient client, String dbId, CosmosContainerProperties collectionDefinition) { return client.getDatabase(dbId).createContainer(collectionDefinition).block().getContainer(); } public static void deleteCollection(CosmosAsyncClient client, String dbId, String collectionId) { client.getDatabase(dbId).getContainer(collectionId).delete().block(); } public static CosmosItemProperties createDocument(CosmosAsyncContainer cosmosContainer, CosmosItemProperties item) { return BridgeInternal.getProperties(cosmosContainer.createItem(item).block()); } public <T> Flux<CosmosAsyncItemResponse<T>> bulkInsert(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList, int concurrencyLevel) { List<Mono<CosmosAsyncItemResponse<T>>> result = new ArrayList<>(documentDefinitionList.size()); for (T docDef : documentDefinitionList) { result.add(cosmosContainer.createItem(docDef)); } return Flux.merge(Flux.fromIterable(result), concurrencyLevel); } public <T> List<T> bulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList) { return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> itemResponse.getItem()) .collectList() .block(); } public void voidBulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<CosmosItemProperties> documentDefinitionList) { bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> BridgeInternal.getProperties(itemResponse)) .then() .block(); } public static CosmosAsyncUser createUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties userSettings) { return client.getDatabase(databaseId).read().block().getDatabase().createUser(userSettings).block().getUser(); } public static CosmosAsyncUser safeCreateUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties user) { deleteUserIfExists(client, databaseId, user.getId()); return createUser(client, databaseId, user); } private static CosmosAsyncContainer safeCreateCollection(CosmosAsyncClient client, String databaseId, CosmosContainerProperties collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.getId()); return createCollection(client.getDatabase(databaseId), collection, options); } static protected CosmosContainerProperties getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndexWithIdAsPartitionKey() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/id")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/mypk")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex(List<String> partitionKeyPath) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); partitionKeyDef.setPaths(partitionKeyPath); 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); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static void deleteCollectionIfExists(CosmosAsyncClient client, String databaseId, String collectionId) { CosmosAsyncDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); List<CosmosContainerProperties> res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) .collectList() .block(); if (!res.isEmpty()) { deleteCollection(database, collectionId); } } public static void deleteCollection(CosmosAsyncDatabase cosmosDatabase, String collectionId) { cosmosDatabase.getContainer(collectionId).delete().block(); } public static void deleteCollection(CosmosAsyncContainer cosmosContainer) { cosmosContainer.delete().block(); } public static void deleteDocumentIfExists(CosmosAsyncClient client, String databaseId, String collectionId, String docId) { FeedOptions options = new FeedOptions(); options.setPartitionKey(new PartitionKey(docId)); CosmosAsyncContainer cosmosContainer = client.getDatabase(databaseId).getContainer(collectionId); List<CosmosItemProperties> res = cosmosContainer .queryItems(String.format("SELECT * FROM root r where r.id = '%s'", docId), options, CosmosItemProperties.class) .byPage() .flatMap(page -> Flux.fromIterable(page.getResults())) .collectList().block(); if (!res.isEmpty()) { deleteDocument(cosmosContainer, docId); } } public static void safeDeleteDocument(CosmosAsyncContainer cosmosContainer, String documentId, Object partitionKey) { if (cosmosContainer != null && documentId != null) { try { cosmosContainer.deleteItem(documentId, new PartitionKey(partitionKey)).block(); } catch (Exception e) { CosmosException dce = Utils.as(e, CosmosException.class); if (dce == null || dce.getStatusCode() != 404) { throw e; } } } } public static void deleteDocument(CosmosAsyncContainer cosmosContainer, String documentId) { cosmosContainer.deleteItem(documentId, PartitionKey.NONE).block(); } public static void deleteUserIfExists(CosmosAsyncClient client, String databaseId, String userId) { CosmosAsyncDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); List<CosmosUserProperties> res = database .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) .collectList().block(); if (!res.isEmpty()) { deleteUser(database, userId); } } public static void deleteUser(CosmosAsyncDatabase database, String userId) { database.getUser(userId).read().block().getUser().delete().block(); } static private CosmosAsyncDatabase safeCreateDatabase(CosmosAsyncClient client, CosmosDatabaseProperties databaseSettings) { safeDeleteDatabase(client.getDatabase(databaseSettings.getId())); return client.createDatabase(databaseSettings).block().getDatabase(); } static protected CosmosAsyncDatabase createDatabase(CosmosAsyncClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); return client.createDatabase(databaseSettings).block().getDatabase(); } static protected CosmosDatabase createSyncDatabase(CosmosClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); try { return client.createDatabase(databaseSettings).getDatabase(); } catch (CosmosException e) { e.printStackTrace(); } return null; } static protected CosmosAsyncDatabase createDatabaseIfNotExists(CosmosAsyncClient client, String databaseId) { List<CosmosDatabaseProperties> res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) .collectList() .block(); if (res.size() != 0) { return client.getDatabase(databaseId).read().block().getDatabase(); } else { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); return client.createDatabase(databaseSettings).block().getDatabase(); } } static protected void safeDeleteDatabase(CosmosAsyncDatabase database) { if (database != null) { try { database.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteSyncDatabase(CosmosDatabase database) { if (database != null) { try { logger.info("attempting to delete database ...."); database.delete(); logger.info("database deletion completed"); } catch (Exception e) { logger.error("failed to delete sync database", e); } } } static protected void safeDeleteAllCollections(CosmosAsyncDatabase database) { if (database != null) { List<CosmosContainerProperties> collections = database.readAllContainers() .collectList() .block(); for(CosmosContainerProperties collection: collections) { database.getContainer(collection.getId()).delete().block(); } } } static protected void safeDeleteCollection(CosmosAsyncContainer collection) { if (collection != null) { try { collection.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteCollection(CosmosAsyncDatabase database, String collectionId) { if (database != null && collectionId != null) { try { database.getContainer(collectionId).delete().block(); } catch (Exception e) { } } } static protected void safeCloseAsync(CosmosAsyncClient client) { if (client != null) { new Thread(() -> { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } }).start(); } } static protected void safeClose(CosmosAsyncClient client) { if (client != null) { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } } } static protected void safeCloseSyncClient(CosmosClient client) { if (client != null) { try { logger.info("closing client ..."); client.close(); logger.info("closing client completed"); } catch (Exception e) { logger.error("failed to close client", e); } } } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator) { validateSuccess(single, validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator, long timeout) { validateSuccess(single.flux(), validator, timeout); } @SuppressWarnings("rawtypes") public static <T extends CosmosResponse> void validateSuccess(Flux<T> flowable, CosmosResponseValidator<T> validator, long timeout) { TestSubscriber<T> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T, U extends CosmosResponse> void validateFailure(Mono<U> mono, FailureValidator validator) throws InterruptedException { validateFailure(mono.flux(), validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public static <T extends Resource, U extends CosmosResponse> void validateFailure(Flux<U> flowable, FailureValidator validator, long timeout) throws InterruptedException { TestSubscriber<CosmosResponse> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosAsyncItemResponse> void validateItemSuccess( Mono<T> responseMono, CosmosItemResponseValidator validator) { TestSubscriber<CosmosAsyncItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosAsyncItemResponse> void validateItemFailure( Mono<T> responseMono, FailureValidator validator) { TestSubscriber<CosmosAsyncItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } public <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator) { validateQuerySuccess(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); validator.validate(testSubscriber.values()); } public <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator) { validateQueryFailure(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.getEvents().get(1)).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @DataProvider public static Object[][] clientBuilders() { return new Object[][]{{createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)}}; } @DataProvider public static Object[][] clientBuildersWithSessionConsistency() { return new Object[][]{ {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.HTTPS, false, null, true)}, {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.TCP, false, null, true)}, {createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)} }; } static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); return ConsistencyLevel.valueOf(consistency); } logger.error("INVALID configured test consistency [{}].", consistency); throw new IllegalStateException("INVALID configured test consistency " + consistency); } static List<String> parsePreferredLocation(String preferredLocations) { if (StringUtils.isEmpty(preferredLocations)) { return null; } try { return objectMapper.readValue(preferredLocations, new TypeReference<List<String>>() { }); } catch (Exception e) { logger.error("INVALID configured test preferredLocations [{}].", preferredLocations); throw new IllegalStateException("INVALID configured test preferredLocations " + preferredLocations); } } static List<Protocol> parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } List<Protocol> protocolList = new ArrayList<>(); try { List<String> protocolStrings = objectMapper.readValue(protocols, new TypeReference<List<String>>() { }); for(String protocol : protocolStrings) { protocolList.add(Protocol.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, protocol))); } return protocolList; } catch (Exception e) { logger.error("INVALID configured test protocols [{}].", protocols); throw new IllegalStateException("INVALID configured test protocols " + protocols); } } @DataProvider public static Object[][] simpleClientBuildersWithDirect() { return simpleClientBuildersWithDirect(true, toArray(protocols)); } @DataProvider public static Object[][] simpleClientBuildersWithDirectHttps() { return simpleClientBuildersWithDirect(true, Protocol.HTTPS); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcp() { return simpleClientBuildersWithDirect(true, Protocol.TCP); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return simpleClientBuildersWithDirect(false, Protocol.TCP); } private static Object[][] simpleClientBuildersWithDirect(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); List<ConsistencyLevel> testConsistencies = ImmutableList.of(ConsistencyLevel.EVENTUAL); boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient( consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); } @DataProvider public static Object[][] clientBuildersWithDirect() { return clientBuildersWithDirectAllConsistencies(true, toArray(protocols)); } @DataProvider public static Object[][] clientBuildersWithDirectHttps() { return clientBuildersWithDirectAllConsistencies(true, Protocol.HTTPS); } @DataProvider public static Object[][] clientBuildersWithDirectTcp() { return clientBuildersWithDirectAllConsistencies(true, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return clientBuildersWithDirectAllConsistencies(false, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectSession() { return clientBuildersWithDirectSession(true, toArray(protocols)); } static Protocol[] toArray(List<Protocol> protocols) { return protocols.toArray(new Protocol[protocols.size()]); } private static Object[][] clientBuildersWithDirectSession(boolean contentResponseOnWriteEnabled, Protocol... protocols) { return clientBuildersWithDirect(new ArrayList<ConsistencyLevel>() {{ add(ConsistencyLevel.SESSION); }}, contentResponseOnWriteEnabled, protocols); } private static Object[][] clientBuildersWithDirectAllConsistencies(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); return clientBuildersWithDirect(desiredConsistencies, contentResponseOnWriteEnabled, protocols); } static List<ConsistencyLevel> parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } List<ConsistencyLevel> consistencyLevels = new ArrayList<>(); try { List<String> consistencyStrings = objectMapper.readValue(consistencies, new TypeReference<List<String>>() {}); for(String consistency : consistencyStrings) { consistencyLevels.add(ConsistencyLevel.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency))); } return consistencyLevels; } catch (Exception e) { logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); } } @SuppressWarnings("fallthrough") static List<ConsistencyLevel> allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List<ConsistencyLevel> testConsistencies = new ArrayList<>(); switch (accountConsistency) { case STRONG: testConsistencies.add(ConsistencyLevel.STRONG); case BOUNDED_STALENESS: testConsistencies.add(ConsistencyLevel.BOUNDED_STALENESS); case SESSION: testConsistencies.add(ConsistencyLevel.SESSION); case CONSISTENT_PREFIX: testConsistencies.add(ConsistencyLevel.CONSISTENT_PREFIX); case EVENTUAL: testConsistencies.add(ConsistencyLevel.EVENTUAL); break; default: throw new IllegalStateException("INVALID configured test consistency " + accountConsistency); } return testConsistencies; } private static Object[][] clientBuildersWithDirect(List<ConsistencyLevel> testConsistencies, boolean contentResponseOnWriteEnabled, Protocol... protocols) { boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(c -> new Object[]{c}).collect(Collectors.toList()).toArray(new Object[0][]); } static protected CosmosClientBuilder createGatewayHouseKeepingDocumentClient(boolean contentResponseOnWriteEnabled) { ThrottlingRetryOptions options = new ThrottlingRetryOptions(); options.setMaxRetryWaitTime(Duration.ofSeconds(SUITE_SETUP_TIMEOUT)); GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .throttlingRetryOptions(options) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(ConsistencyLevel.SESSION); } static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .multipleWriteRegionsEnabled(multiMasterEnabled) .preferredRegions(preferredRegions) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); } static protected CosmosClientBuilder createGatewayRxDocumentClient() { return createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true); } static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, Protocol protocol, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { CosmosClientBuilder builder = new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .directMode(DirectConnectionConfig.getDefaultConfig()) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); if (preferredRegions != null) { builder.preferredRegions(preferredRegions); } if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.SESSION) { builder.multipleWriteRegionsEnabled(true); } Configs configs = spy(new Configs()); doAnswer((Answer<Protocol>)invocation -> protocol).when(configs).getProtocol(); return injectConfigs(builder, configs); } protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { return Math.max((totalExpectedResult + maxPageSize - 1 ) / maxPageSize, 1); } @DataProvider(name = "queryMetricsArgProvider") public Object[][] queryMetricsArgProvider() { return new Object[][]{ {true}, {false}, }; } public static CosmosClientBuilder copyCosmosClientBuilder(CosmosClientBuilder builder) { return CosmosBridgeInternal.cloneCosmosClientBuilder(builder); } }
}
protected static void truncateCollection(CosmosAsyncContainer cosmosContainer) { CosmosContainerProperties cosmosContainerProperties = cosmosContainer.read().block().getProperties(); String cosmosContainerId = cosmosContainerProperties.getId(); logger.info("Truncating collection {} ...", cosmosContainerId); List<String> paths = cosmosContainerProperties.getPartitionKeyDefinition().getPaths(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(-1); int maxItemCount = 100; logger.info("Truncating collection {} documents ...", cosmosContainer.getId()); cosmosContainer.queryItems("SELECT * FROM root", options, CosmosItemProperties.class) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(doc -> { PartitionKey partitionKey = null; Object propertyValue = null; if (paths != null && !paths.isEmpty()) { List<String> pkPath = PathParser.getPathParts(paths.get(0)); propertyValue = ModelBridgeInternal.getObjectByPathFromJsonSerializable(doc, pkPath); if (propertyValue == null) { partitionKey = PartitionKey.NONE; } else { partitionKey = new PartitionKey(propertyValue); } } else { partitionKey = new PartitionKey(null); } return cosmosContainer.deleteItem(doc.getId(), partitionKey); }).then().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); cosmosContainer.getScripts().queryTriggers("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(trigger -> { return cosmosContainer.getScripts().getTrigger(trigger.getId()).delete(); }).then().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); cosmosContainer.getScripts().queryStoredProcedures("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(storedProcedure -> { return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.getId()).delete(new CosmosStoredProcedureRequestOptions()); }).then().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); cosmosContainer.getScripts().queryUserDefinedFunctions("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(udf -> { return cosmosContainer.getScripts().getUserDefinedFunction(udf.getId()).delete(); }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); } @SuppressWarnings({"fallthrough"}) protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (CosmosBridgeInternal.getConsistencyLevel(clientBuilder)) { case EVENTUAL: case CONSISTENT_PREFIX: logger.info(" additional wait in EVENTUAL mode so the replica catch up"); try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); } catch (Exception e) { logger.error("unexpected failure", e); } case SESSION: case BOUNDED_STALENESS: case STRONG: default: break; } } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options, int throughput) { database.createContainer(cosmosContainerProperties, ThroughputProperties.createManualThroughput(throughput), options).block(); return database.getContainer(cosmosContainerProperties.getId()); } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options) { database.createContainer(cosmosContainerProperties, options).block(); return database.getContainer(cosmosContainerProperties.getId()); } private static CosmosContainerProperties getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; final String STRING_FIELD_2 = "stringField2"; final String BOOL_FIELD = "boolField"; final String NULL_FIELD = "nullField"; final String OBJECT_FIELD = "objectField"; final String ARRAY_FIELD = "arrayField"; final String SHORT_STRING_FIELD = "shortStringField"; final String MEDIUM_STRING_FIELD = "mediumStringField"; final String LONG_STRING_FIELD = "longStringField"; final String PARTITION_KEY = "pk"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList<String> partitionKeyPaths = new ArrayList<String>(); partitionKeyPaths.add("/" + PARTITION_KEY); partitionKeyDefinition.setPaths(partitionKeyPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<List<CompositePath>> compositeIndexes = new ArrayList<>(); ArrayList<CompositePath> compositeIndexSimple = new ArrayList<CompositePath>(); CompositePath compositePath1 = new CompositePath(); compositePath1.setPath("/" + NUMBER_FIELD); compositePath1.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); compositePath2.setPath("/" + STRING_FIELD); compositePath2.setOrder(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); ArrayList<CompositePath> compositeIndexMaxColumns = new ArrayList<CompositePath>(); CompositePath compositePath3 = new CompositePath(); compositePath3.setPath("/" + NUMBER_FIELD); compositePath3.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); compositePath4.setPath("/" + STRING_FIELD); compositePath4.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); compositePath5.setPath("/" + NUMBER_FIELD_2); compositePath5.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); compositePath6.setPath("/" + STRING_FIELD_2); compositePath6.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); compositeIndexMaxColumns.add(compositePath5); compositeIndexMaxColumns.add(compositePath6); ArrayList<CompositePath> compositeIndexPrimitiveValues = new ArrayList<CompositePath>(); CompositePath compositePath7 = new CompositePath(); compositePath7.setPath("/" + NUMBER_FIELD); compositePath7.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); compositePath8.setPath("/" + STRING_FIELD); compositePath8.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); compositePath9.setPath("/" + BOOL_FIELD); compositePath9.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); compositePath10.setPath("/" + NULL_FIELD); compositePath10.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); compositeIndexPrimitiveValues.add(compositePath9); compositeIndexPrimitiveValues.add(compositePath10); ArrayList<CompositePath> compositeIndexLongStrings = new ArrayList<CompositePath>(); CompositePath compositePath11 = new CompositePath(); compositePath11.setPath("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); compositePath12.setPath("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); compositePath13.setPath("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); compositePath14.setPath("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); compositeIndexLongStrings.add(compositePath13); compositeIndexLongStrings.add(compositePath14); compositeIndexes.add(compositeIndexSimple); compositeIndexes.add(compositeIndexMaxColumns); compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.setCompositeIndexes(compositeIndexes); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static CosmosAsyncContainer createCollection(CosmosAsyncClient client, String dbId, CosmosContainerProperties collectionDefinition) { CosmosAsyncDatabase database = client.getDatabase(dbId); database.createContainer(collectionDefinition).block(); return database.getContainer(collectionDefinition.getId()); } public static void deleteCollection(CosmosAsyncClient client, String dbId, String collectionId) { client.getDatabase(dbId).getContainer(collectionId).delete().block(); } public static CosmosItemProperties createDocument(CosmosAsyncContainer cosmosContainer, CosmosItemProperties item) { return BridgeInternal.getProperties(cosmosContainer.createItem(item).block()); } public <T> Flux<CosmosItemResponse<T>> bulkInsert(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList, int concurrencyLevel) { List<Mono<CosmosItemResponse<T>>> result = new ArrayList<>(documentDefinitionList.size()); for (T docDef : documentDefinitionList) { result.add(cosmosContainer.createItem(docDef)); } return Flux.merge(Flux.fromIterable(result), concurrencyLevel); } public <T> List<T> bulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList) { return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> itemResponse.getItem()) .collectList() .block(); } public void voidBulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<CosmosItemProperties> documentDefinitionList) { bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> BridgeInternal.getProperties(itemResponse)) .then() .block(); } public static CosmosAsyncUser createUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties userSettings) { CosmosAsyncDatabase database = client.getDatabase(databaseId); CosmosUserResponse userResponse = database.createUser(userSettings).block(); return database.getUser(userResponse.getProperties().getId()); } public static CosmosAsyncUser safeCreateUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties user) { deleteUserIfExists(client, databaseId, user.getId()); return createUser(client, databaseId, user); } private static CosmosAsyncContainer safeCreateCollection(CosmosAsyncClient client, String databaseId, CosmosContainerProperties collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.getId()); return createCollection(client.getDatabase(databaseId), collection, options); } static protected CosmosContainerProperties getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndexWithIdAsPartitionKey() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/id")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/mypk")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex(List<String> partitionKeyPath) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); partitionKeyDef.setPaths(partitionKeyPath); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<IncludedPath> includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath("/*"); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static void deleteCollectionIfExists(CosmosAsyncClient client, String databaseId, String collectionId) { CosmosAsyncDatabase database = client.getDatabase(databaseId); database.read().block(); List<CosmosContainerProperties> res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) .collectList() .block(); if (!res.isEmpty()) { deleteCollection(database, collectionId); } } public static void deleteCollection(CosmosAsyncDatabase cosmosDatabase, String collectionId) { cosmosDatabase.getContainer(collectionId).delete().block(); } public static void deleteCollection(CosmosAsyncContainer cosmosContainer) { cosmosContainer.delete().block(); } public static void deleteDocumentIfExists(CosmosAsyncClient client, String databaseId, String collectionId, String docId) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setPartitionKey(new PartitionKey(docId)); CosmosAsyncContainer cosmosContainer = client.getDatabase(databaseId).getContainer(collectionId); List<CosmosItemProperties> res = cosmosContainer .queryItems(String.format("SELECT * FROM root r where r.id = '%s'", docId), options, CosmosItemProperties.class) .byPage() .flatMap(page -> Flux.fromIterable(page.getResults())) .collectList().block(); if (!res.isEmpty()) { deleteDocument(cosmosContainer, docId); } } public static void safeDeleteDocument(CosmosAsyncContainer cosmosContainer, String documentId, Object partitionKey) { if (cosmosContainer != null && documentId != null) { try { cosmosContainer.deleteItem(documentId, new PartitionKey(partitionKey)).block(); } catch (Exception e) { CosmosException dce = Utils.as(e, CosmosException.class); if (dce == null || dce.getStatusCode() != 404) { throw e; } } } } public static void deleteDocument(CosmosAsyncContainer cosmosContainer, String documentId) { cosmosContainer.deleteItem(documentId, PartitionKey.NONE).block(); } public static void deleteUserIfExists(CosmosAsyncClient client, String databaseId, String userId) { CosmosAsyncDatabase database = client.getDatabase(databaseId); client.getDatabase(databaseId).read().block(); List<CosmosUserProperties> res = database .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) .collectList().block(); if (!res.isEmpty()) { deleteUser(database, userId); } } public static void deleteUser(CosmosAsyncDatabase database, String userId) { database.getUser(userId).delete().block(); } static private CosmosAsyncDatabase safeCreateDatabase(CosmosAsyncClient client, CosmosDatabaseProperties databaseSettings) { safeDeleteDatabase(client.getDatabase(databaseSettings.getId())); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } static protected CosmosAsyncDatabase createDatabase(CosmosAsyncClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } static protected CosmosDatabase createSyncDatabase(CosmosClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); try { client.createDatabase(databaseSettings); return client.getDatabase(databaseSettings.getId()); } catch (CosmosException e) { e.printStackTrace(); } return null; } static protected CosmosAsyncDatabase createDatabaseIfNotExists(CosmosAsyncClient client, String databaseId) { List<CosmosDatabaseProperties> res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) .collectList() .block(); if (res.size() != 0) { CosmosAsyncDatabase database = client.getDatabase(databaseId); database.read().block(); return database; } else { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } } static protected void safeDeleteDatabase(CosmosAsyncDatabase database) { if (database != null) { try { database.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteSyncDatabase(CosmosDatabase database) { if (database != null) { try { logger.info("attempting to delete database ...."); database.delete(); logger.info("database deletion completed"); } catch (Exception e) { logger.error("failed to delete sync database", e); } } } static protected void safeDeleteAllCollections(CosmosAsyncDatabase database) { if (database != null) { List<CosmosContainerProperties> collections = database.readAllContainers() .collectList() .block(); for(CosmosContainerProperties collection: collections) { database.getContainer(collection.getId()).delete().block(); } } } static protected void safeDeleteCollection(CosmosAsyncContainer collection) { if (collection != null) { try { collection.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteCollection(CosmosAsyncDatabase database, String collectionId) { if (database != null && collectionId != null) { try { database.getContainer(collectionId).delete().block(); } catch (Exception e) { } } } static protected void safeCloseAsync(CosmosAsyncClient client) { if (client != null) { new Thread(() -> { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } }).start(); } } static protected void safeClose(CosmosAsyncClient client) { if (client != null) { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } } } static protected void safeCloseSyncClient(CosmosClient client) { if (client != null) { try { logger.info("closing client ..."); client.close(); logger.info("closing client completed"); } catch (Exception e) { logger.error("failed to close client", e); } } } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator) { validateSuccess(single, validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator, long timeout) { validateSuccess(single.flux(), validator, timeout); } @SuppressWarnings("rawtypes") public static <T extends CosmosResponse> void validateSuccess(Flux<T> flowable, CosmosResponseValidator<T> validator, long timeout) { TestSubscriber<T> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T, U extends CosmosResponse> void validateFailure(Mono<U> mono, FailureValidator validator) throws InterruptedException { validateFailure(mono.flux(), validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public static <T extends Resource, U extends CosmosResponse> void validateFailure(Flux<U> flowable, FailureValidator validator, long timeout) throws InterruptedException { TestSubscriber<CosmosResponse> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosItemResponse> void validateItemSuccess( Mono<T> responseMono, CosmosItemResponseValidator validator) { TestSubscriber<CosmosItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosItemResponse> void validateItemFailure( Mono<T> responseMono, FailureValidator validator) { TestSubscriber<CosmosItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } public <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator) { validateQuerySuccess(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); validator.validate(testSubscriber.values()); } public <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator) { validateQueryFailure(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.getEvents().get(1)).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @DataProvider public static Object[][] clientBuilders() { return new Object[][]{{createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)}}; } @DataProvider public static Object[][] clientBuildersWithSessionConsistency() { return new Object[][]{ {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.HTTPS, false, null, true)}, {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.TCP, false, null, true)}, {createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)} }; } static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); return ConsistencyLevel.valueOf(consistency); } logger.error("INVALID configured test consistency [{}].", consistency); throw new IllegalStateException("INVALID configured test consistency " + consistency); } static List<String> parsePreferredLocation(String preferredLocations) { if (StringUtils.isEmpty(preferredLocations)) { return null; } try { return objectMapper.readValue(preferredLocations, new TypeReference<List<String>>() { }); } catch (Exception e) { logger.error("INVALID configured test preferredLocations [{}].", preferredLocations); throw new IllegalStateException("INVALID configured test preferredLocations " + preferredLocations); } } static List<Protocol> parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } List<Protocol> protocolList = new ArrayList<>(); try { List<String> protocolStrings = objectMapper.readValue(protocols, new TypeReference<List<String>>() { }); for(String protocol : protocolStrings) { protocolList.add(Protocol.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, protocol))); } return protocolList; } catch (Exception e) { logger.error("INVALID configured test protocols [{}].", protocols); throw new IllegalStateException("INVALID configured test protocols " + protocols); } } @DataProvider public static Object[][] simpleClientBuildersWithDirect() { return simpleClientBuildersWithDirect(true, toArray(protocols)); } @DataProvider public static Object[][] simpleClientBuildersWithDirectHttps() { return simpleClientBuildersWithDirect(true, Protocol.HTTPS); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcp() { return simpleClientBuildersWithDirect(true, Protocol.TCP); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return simpleClientBuildersWithDirect(false, Protocol.TCP); } private static Object[][] simpleClientBuildersWithDirect(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); List<ConsistencyLevel> testConsistencies = ImmutableList.of(ConsistencyLevel.EVENTUAL); boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient( consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); } @DataProvider public static Object[][] clientBuildersWithDirect() { return clientBuildersWithDirectAllConsistencies(true, toArray(protocols)); } @DataProvider public static Object[][] clientBuildersWithDirectHttps() { return clientBuildersWithDirectAllConsistencies(true, Protocol.HTTPS); } @DataProvider public static Object[][] clientBuildersWithDirectTcp() { return clientBuildersWithDirectAllConsistencies(true, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return clientBuildersWithDirectAllConsistencies(false, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectSession() { return clientBuildersWithDirectSession(true, toArray(protocols)); } static Protocol[] toArray(List<Protocol> protocols) { return protocols.toArray(new Protocol[protocols.size()]); } private static Object[][] clientBuildersWithDirectSession(boolean contentResponseOnWriteEnabled, Protocol... protocols) { return clientBuildersWithDirect(new ArrayList<ConsistencyLevel>() {{ add(ConsistencyLevel.SESSION); }}, contentResponseOnWriteEnabled, protocols); } private static Object[][] clientBuildersWithDirectAllConsistencies(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); return clientBuildersWithDirect(desiredConsistencies, contentResponseOnWriteEnabled, protocols); } static List<ConsistencyLevel> parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } List<ConsistencyLevel> consistencyLevels = new ArrayList<>(); try { List<String> consistencyStrings = objectMapper.readValue(consistencies, new TypeReference<List<String>>() {}); for(String consistency : consistencyStrings) { consistencyLevels.add(ConsistencyLevel.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency))); } return consistencyLevels; } catch (Exception e) { logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); } } @SuppressWarnings("fallthrough") static List<ConsistencyLevel> allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List<ConsistencyLevel> testConsistencies = new ArrayList<>(); switch (accountConsistency) { case STRONG: testConsistencies.add(ConsistencyLevel.STRONG); case BOUNDED_STALENESS: testConsistencies.add(ConsistencyLevel.BOUNDED_STALENESS); case SESSION: testConsistencies.add(ConsistencyLevel.SESSION); case CONSISTENT_PREFIX: testConsistencies.add(ConsistencyLevel.CONSISTENT_PREFIX); case EVENTUAL: testConsistencies.add(ConsistencyLevel.EVENTUAL); break; default: throw new IllegalStateException("INVALID configured test consistency " + accountConsistency); } return testConsistencies; } private static Object[][] clientBuildersWithDirect(List<ConsistencyLevel> testConsistencies, boolean contentResponseOnWriteEnabled, Protocol... protocols) { boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(c -> new Object[]{c}).collect(Collectors.toList()).toArray(new Object[0][]); } static protected CosmosClientBuilder createGatewayHouseKeepingDocumentClient(boolean contentResponseOnWriteEnabled) { ThrottlingRetryOptions options = new ThrottlingRetryOptions(); options.setMaxRetryWaitTime(Duration.ofSeconds(SUITE_SETUP_TIMEOUT)); GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .throttlingRetryOptions(options) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(ConsistencyLevel.SESSION); } static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .multipleWriteRegionsEnabled(multiMasterEnabled) .preferredRegions(preferredRegions) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); } static protected CosmosClientBuilder createGatewayRxDocumentClient() { return createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true); } static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, Protocol protocol, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { CosmosClientBuilder builder = new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .directMode(DirectConnectionConfig.getDefaultConfig()) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); if (preferredRegions != null) { builder.preferredRegions(preferredRegions); } if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.SESSION) { builder.multipleWriteRegionsEnabled(true); } Configs configs = spy(new Configs()); doAnswer((Answer<Protocol>)invocation -> protocol).when(configs).getProtocol(); return injectConfigs(builder, configs); } protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { return Math.max((totalExpectedResult + maxPageSize - 1 ) / maxPageSize, 1); } @DataProvider(name = "queryMetricsArgProvider") public Object[][] queryMetricsArgProvider() { return new Object[][]{ {true}, {false}, }; } public static CosmosClientBuilder copyCosmosClientBuilder(CosmosClientBuilder builder) { return CosmosBridgeInternal.cloneCosmosClientBuilder(builder); } }
class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(CosmosAsyncClient client) { return new DatabaseManagerImpl(client); } private final CosmosAsyncClient client; private DatabaseManagerImpl(CosmosAsyncClient client) { this.client = client; } @Override public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override public Mono<CosmosAsyncDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseDefinition) { return client.createDatabase(databaseDefinition); } @Override public CosmosAsyncDatabase getDatabase(String id) { return client.getDatabase(id); } }
class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(CosmosAsyncClient client) { return new DatabaseManagerImpl(client); } private final CosmosAsyncClient client; private DatabaseManagerImpl(CosmosAsyncClient client) { this.client = client; } @Override public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseDefinition) { return client.createDatabase(databaseDefinition); } @Override public CosmosAsyncDatabase getDatabase(String id) { return client.getDatabase(id); } }
I don't think we should have the entire stacktrace in tracing. It's important to capture that there was an error but the stracktrace is likely not that useful. Stacktrace should be available in logs, if that's necessary. It's also a security issue to capture stacktrace since the user cannot control or turn it off.
private void end(int statusCode, Throwable throwable, Context context) { for (Tracer tracer : tracers) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); StringWriter errorStack = new StringWriter(); throwable.printStackTrace(new PrintWriter(errorStack)); tracer.setAttribute(TracerProvider.ERROR_STACK, errorStack.toString(), context); } tracer.end(statusCode, throwable, context); } }
throwable.printStackTrace(new PrintWriter(errorStack));
private void end(int statusCode, Throwable throwable, Context context) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); } tracer.end(statusCode, throwable, context); }
class TracerProvider { private final List<Tracer> tracers = new ArrayList<>(); private final boolean isEnabled; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); tracers.forEach(this.tracers::add); isEnabled = this.tracers.size() > 0; } public boolean isEnabled() { return isEnabled; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); for (Tracer tracer : tracers) { local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; } /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<T> traceEnabledNonCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName, databaseId, endpoint, (T response) -> HttpConstants.StatusCodes.OK); } public <T> Mono<CosmosAsyncItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosAsyncItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosAsyncItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), 0); } }); } }
class TracerProvider { private Tracer tracer; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final int ERROR_CODE = 0; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); if (tracers.iterator().hasNext()) { tracer = tracers.iterator().next(); } } public boolean isEnabled() { return tracer != null; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; } /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<CosmosItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), ERROR_CODE); } }); } }
This is cover by start span count assert , test will fail if there is nesting . Will add explicit test in next pr covering event
protected static void truncateCollection(CosmosAsyncContainer cosmosContainer) { CosmosContainerProperties cosmosContainerProperties = cosmosContainer.read().block().getProperties(); String cosmosContainerId = cosmosContainerProperties.getId(); logger.info("Truncating collection {} ...", cosmosContainerId); List<String> paths = cosmosContainerProperties.getPartitionKeyDefinition().getPaths(); FeedOptions options = new FeedOptions(); options.setMaxDegreeOfParallelism(-1); int maxItemCount = 100; logger.info("Truncating collection {} documents ...", cosmosContainer.getId()); cosmosContainer.queryItems("SELECT * FROM root", options, CosmosItemProperties.class) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(doc -> { PartitionKey partitionKey = null; Object propertyValue = null; if (paths != null && !paths.isEmpty()) { List<String> pkPath = PathParser.getPathParts(paths.get(0)); propertyValue = ModelBridgeInternal.getObjectByPathFromJsonSerializable(doc, pkPath); if (propertyValue == null) { partitionKey = PartitionKey.NONE; } else { partitionKey = new PartitionKey(propertyValue); } } else { partitionKey = new PartitionKey(null); } return cosmosContainer.deleteItem(doc.getId(), partitionKey); }).then().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); cosmosContainer.getScripts().queryTriggers("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(trigger -> { return cosmosContainer.getScripts().getTrigger(trigger.getId()).delete(); }).then().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); cosmosContainer.getScripts().queryStoredProcedures("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(storedProcedure -> { return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.getId()).delete(new CosmosStoredProcedureRequestOptions()); }).then().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); cosmosContainer.getScripts().queryUserDefinedFunctions("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(udf -> { return cosmosContainer.getScripts().getUserDefinedFunction(udf.getId()).delete(); }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); } @SuppressWarnings({"fallthrough"}) protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (CosmosBridgeInternal.getConsistencyLevel(clientBuilder)) { case EVENTUAL: case CONSISTENT_PREFIX: logger.info(" additional wait in EVENTUAL mode so the replica catch up"); try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); } catch (Exception e) { logger.error("unexpected failure", e); } case SESSION: case BOUNDED_STALENESS: case STRONG: default: break; } } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options, int throughput) { return database.createContainer(cosmosContainerProperties, throughput, options).block().getContainer(); } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options) { return database.createContainer(cosmosContainerProperties, options).block().getContainer(); } private static CosmosContainerProperties getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; final String STRING_FIELD_2 = "stringField2"; final String BOOL_FIELD = "boolField"; final String NULL_FIELD = "nullField"; final String OBJECT_FIELD = "objectField"; final String ARRAY_FIELD = "arrayField"; final String SHORT_STRING_FIELD = "shortStringField"; final String MEDIUM_STRING_FIELD = "mediumStringField"; final String LONG_STRING_FIELD = "longStringField"; final String PARTITION_KEY = "pk"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList<String> partitionKeyPaths = new ArrayList<String>(); partitionKeyPaths.add("/" + PARTITION_KEY); partitionKeyDefinition.setPaths(partitionKeyPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<List<CompositePath>> compositeIndexes = new ArrayList<>(); ArrayList<CompositePath> compositeIndexSimple = new ArrayList<CompositePath>(); CompositePath compositePath1 = new CompositePath(); compositePath1.setPath("/" + NUMBER_FIELD); compositePath1.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); compositePath2.setPath("/" + STRING_FIELD); compositePath2.setOrder(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); ArrayList<CompositePath> compositeIndexMaxColumns = new ArrayList<CompositePath>(); CompositePath compositePath3 = new CompositePath(); compositePath3.setPath("/" + NUMBER_FIELD); compositePath3.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); compositePath4.setPath("/" + STRING_FIELD); compositePath4.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); compositePath5.setPath("/" + NUMBER_FIELD_2); compositePath5.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); compositePath6.setPath("/" + STRING_FIELD_2); compositePath6.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); compositeIndexMaxColumns.add(compositePath5); compositeIndexMaxColumns.add(compositePath6); ArrayList<CompositePath> compositeIndexPrimitiveValues = new ArrayList<CompositePath>(); CompositePath compositePath7 = new CompositePath(); compositePath7.setPath("/" + NUMBER_FIELD); compositePath7.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); compositePath8.setPath("/" + STRING_FIELD); compositePath8.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); compositePath9.setPath("/" + BOOL_FIELD); compositePath9.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); compositePath10.setPath("/" + NULL_FIELD); compositePath10.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); compositeIndexPrimitiveValues.add(compositePath9); compositeIndexPrimitiveValues.add(compositePath10); ArrayList<CompositePath> compositeIndexLongStrings = new ArrayList<CompositePath>(); CompositePath compositePath11 = new CompositePath(); compositePath11.setPath("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); compositePath12.setPath("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); compositePath13.setPath("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); compositePath14.setPath("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); compositeIndexLongStrings.add(compositePath13); compositeIndexLongStrings.add(compositePath14); compositeIndexes.add(compositeIndexSimple); compositeIndexes.add(compositeIndexMaxColumns); compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.setCompositeIndexes(compositeIndexes); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static CosmosAsyncContainer createCollection(CosmosAsyncClient client, String dbId, CosmosContainerProperties collectionDefinition) { return client.getDatabase(dbId).createContainer(collectionDefinition).block().getContainer(); } public static void deleteCollection(CosmosAsyncClient client, String dbId, String collectionId) { client.getDatabase(dbId).getContainer(collectionId).delete().block(); } public static CosmosItemProperties createDocument(CosmosAsyncContainer cosmosContainer, CosmosItemProperties item) { return BridgeInternal.getProperties(cosmosContainer.createItem(item).block()); } public <T> Flux<CosmosAsyncItemResponse<T>> bulkInsert(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList, int concurrencyLevel) { List<Mono<CosmosAsyncItemResponse<T>>> result = new ArrayList<>(documentDefinitionList.size()); for (T docDef : documentDefinitionList) { result.add(cosmosContainer.createItem(docDef)); } return Flux.merge(Flux.fromIterable(result), concurrencyLevel); } public <T> List<T> bulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList) { return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> itemResponse.getItem()) .collectList() .block(); } public void voidBulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<CosmosItemProperties> documentDefinitionList) { bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> BridgeInternal.getProperties(itemResponse)) .then() .block(); } public static CosmosAsyncUser createUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties userSettings) { return client.getDatabase(databaseId).read().block().getDatabase().createUser(userSettings).block().getUser(); } public static CosmosAsyncUser safeCreateUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties user) { deleteUserIfExists(client, databaseId, user.getId()); return createUser(client, databaseId, user); } private static CosmosAsyncContainer safeCreateCollection(CosmosAsyncClient client, String databaseId, CosmosContainerProperties collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.getId()); return createCollection(client.getDatabase(databaseId), collection, options); } static protected CosmosContainerProperties getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndexWithIdAsPartitionKey() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/id")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/mypk")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex(List<String> partitionKeyPath) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); partitionKeyDef.setPaths(partitionKeyPath); 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); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static void deleteCollectionIfExists(CosmosAsyncClient client, String databaseId, String collectionId) { CosmosAsyncDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); List<CosmosContainerProperties> res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) .collectList() .block(); if (!res.isEmpty()) { deleteCollection(database, collectionId); } } public static void deleteCollection(CosmosAsyncDatabase cosmosDatabase, String collectionId) { cosmosDatabase.getContainer(collectionId).delete().block(); } public static void deleteCollection(CosmosAsyncContainer cosmosContainer) { cosmosContainer.delete().block(); } public static void deleteDocumentIfExists(CosmosAsyncClient client, String databaseId, String collectionId, String docId) { FeedOptions options = new FeedOptions(); options.setPartitionKey(new PartitionKey(docId)); CosmosAsyncContainer cosmosContainer = client.getDatabase(databaseId).getContainer(collectionId); List<CosmosItemProperties> res = cosmosContainer .queryItems(String.format("SELECT * FROM root r where r.id = '%s'", docId), options, CosmosItemProperties.class) .byPage() .flatMap(page -> Flux.fromIterable(page.getResults())) .collectList().block(); if (!res.isEmpty()) { deleteDocument(cosmosContainer, docId); } } public static void safeDeleteDocument(CosmosAsyncContainer cosmosContainer, String documentId, Object partitionKey) { if (cosmosContainer != null && documentId != null) { try { cosmosContainer.deleteItem(documentId, new PartitionKey(partitionKey)).block(); } catch (Exception e) { CosmosException dce = Utils.as(e, CosmosException.class); if (dce == null || dce.getStatusCode() != 404) { throw e; } } } } public static void deleteDocument(CosmosAsyncContainer cosmosContainer, String documentId) { cosmosContainer.deleteItem(documentId, PartitionKey.NONE).block(); } public static void deleteUserIfExists(CosmosAsyncClient client, String databaseId, String userId) { CosmosAsyncDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); List<CosmosUserProperties> res = database .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) .collectList().block(); if (!res.isEmpty()) { deleteUser(database, userId); } } public static void deleteUser(CosmosAsyncDatabase database, String userId) { database.getUser(userId).read().block().getUser().delete().block(); } static private CosmosAsyncDatabase safeCreateDatabase(CosmosAsyncClient client, CosmosDatabaseProperties databaseSettings) { safeDeleteDatabase(client.getDatabase(databaseSettings.getId())); return client.createDatabase(databaseSettings).block().getDatabase(); } static protected CosmosAsyncDatabase createDatabase(CosmosAsyncClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); return client.createDatabase(databaseSettings).block().getDatabase(); } static protected CosmosDatabase createSyncDatabase(CosmosClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); try { return client.createDatabase(databaseSettings).getDatabase(); } catch (CosmosException e) { e.printStackTrace(); } return null; } static protected CosmosAsyncDatabase createDatabaseIfNotExists(CosmosAsyncClient client, String databaseId) { List<CosmosDatabaseProperties> res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) .collectList() .block(); if (res.size() != 0) { return client.getDatabase(databaseId).read().block().getDatabase(); } else { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); return client.createDatabase(databaseSettings).block().getDatabase(); } } static protected void safeDeleteDatabase(CosmosAsyncDatabase database) { if (database != null) { try { database.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteSyncDatabase(CosmosDatabase database) { if (database != null) { try { logger.info("attempting to delete database ...."); database.delete(); logger.info("database deletion completed"); } catch (Exception e) { logger.error("failed to delete sync database", e); } } } static protected void safeDeleteAllCollections(CosmosAsyncDatabase database) { if (database != null) { List<CosmosContainerProperties> collections = database.readAllContainers() .collectList() .block(); for(CosmosContainerProperties collection: collections) { database.getContainer(collection.getId()).delete().block(); } } } static protected void safeDeleteCollection(CosmosAsyncContainer collection) { if (collection != null) { try { collection.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteCollection(CosmosAsyncDatabase database, String collectionId) { if (database != null && collectionId != null) { try { database.getContainer(collectionId).delete().block(); } catch (Exception e) { } } } static protected void safeCloseAsync(CosmosAsyncClient client) { if (client != null) { new Thread(() -> { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } }).start(); } } static protected void safeClose(CosmosAsyncClient client) { if (client != null) { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } } } static protected void safeCloseSyncClient(CosmosClient client) { if (client != null) { try { logger.info("closing client ..."); client.close(); logger.info("closing client completed"); } catch (Exception e) { logger.error("failed to close client", e); } } } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator) { validateSuccess(single, validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator, long timeout) { validateSuccess(single.flux(), validator, timeout); } @SuppressWarnings("rawtypes") public static <T extends CosmosResponse> void validateSuccess(Flux<T> flowable, CosmosResponseValidator<T> validator, long timeout) { TestSubscriber<T> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T, U extends CosmosResponse> void validateFailure(Mono<U> mono, FailureValidator validator) throws InterruptedException { validateFailure(mono.flux(), validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public static <T extends Resource, U extends CosmosResponse> void validateFailure(Flux<U> flowable, FailureValidator validator, long timeout) throws InterruptedException { TestSubscriber<CosmosResponse> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosAsyncItemResponse> void validateItemSuccess( Mono<T> responseMono, CosmosItemResponseValidator validator) { TestSubscriber<CosmosAsyncItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosAsyncItemResponse> void validateItemFailure( Mono<T> responseMono, FailureValidator validator) { TestSubscriber<CosmosAsyncItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } public <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator) { validateQuerySuccess(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); validator.validate(testSubscriber.values()); } public <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator) { validateQueryFailure(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.getEvents().get(1)).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @DataProvider public static Object[][] clientBuilders() { return new Object[][]{{createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)}}; } @DataProvider public static Object[][] clientBuildersWithSessionConsistency() { return new Object[][]{ {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.HTTPS, false, null, true)}, {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.TCP, false, null, true)}, {createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)} }; } static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); return ConsistencyLevel.valueOf(consistency); } logger.error("INVALID configured test consistency [{}].", consistency); throw new IllegalStateException("INVALID configured test consistency " + consistency); } static List<String> parsePreferredLocation(String preferredLocations) { if (StringUtils.isEmpty(preferredLocations)) { return null; } try { return objectMapper.readValue(preferredLocations, new TypeReference<List<String>>() { }); } catch (Exception e) { logger.error("INVALID configured test preferredLocations [{}].", preferredLocations); throw new IllegalStateException("INVALID configured test preferredLocations " + preferredLocations); } } static List<Protocol> parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } List<Protocol> protocolList = new ArrayList<>(); try { List<String> protocolStrings = objectMapper.readValue(protocols, new TypeReference<List<String>>() { }); for(String protocol : protocolStrings) { protocolList.add(Protocol.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, protocol))); } return protocolList; } catch (Exception e) { logger.error("INVALID configured test protocols [{}].", protocols); throw new IllegalStateException("INVALID configured test protocols " + protocols); } } @DataProvider public static Object[][] simpleClientBuildersWithDirect() { return simpleClientBuildersWithDirect(true, toArray(protocols)); } @DataProvider public static Object[][] simpleClientBuildersWithDirectHttps() { return simpleClientBuildersWithDirect(true, Protocol.HTTPS); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcp() { return simpleClientBuildersWithDirect(true, Protocol.TCP); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return simpleClientBuildersWithDirect(false, Protocol.TCP); } private static Object[][] simpleClientBuildersWithDirect(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); List<ConsistencyLevel> testConsistencies = ImmutableList.of(ConsistencyLevel.EVENTUAL); boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient( consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); } @DataProvider public static Object[][] clientBuildersWithDirect() { return clientBuildersWithDirectAllConsistencies(true, toArray(protocols)); } @DataProvider public static Object[][] clientBuildersWithDirectHttps() { return clientBuildersWithDirectAllConsistencies(true, Protocol.HTTPS); } @DataProvider public static Object[][] clientBuildersWithDirectTcp() { return clientBuildersWithDirectAllConsistencies(true, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return clientBuildersWithDirectAllConsistencies(false, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectSession() { return clientBuildersWithDirectSession(true, toArray(protocols)); } static Protocol[] toArray(List<Protocol> protocols) { return protocols.toArray(new Protocol[protocols.size()]); } private static Object[][] clientBuildersWithDirectSession(boolean contentResponseOnWriteEnabled, Protocol... protocols) { return clientBuildersWithDirect(new ArrayList<ConsistencyLevel>() {{ add(ConsistencyLevel.SESSION); }}, contentResponseOnWriteEnabled, protocols); } private static Object[][] clientBuildersWithDirectAllConsistencies(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); return clientBuildersWithDirect(desiredConsistencies, contentResponseOnWriteEnabled, protocols); } static List<ConsistencyLevel> parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } List<ConsistencyLevel> consistencyLevels = new ArrayList<>(); try { List<String> consistencyStrings = objectMapper.readValue(consistencies, new TypeReference<List<String>>() {}); for(String consistency : consistencyStrings) { consistencyLevels.add(ConsistencyLevel.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency))); } return consistencyLevels; } catch (Exception e) { logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); } } @SuppressWarnings("fallthrough") static List<ConsistencyLevel> allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List<ConsistencyLevel> testConsistencies = new ArrayList<>(); switch (accountConsistency) { case STRONG: testConsistencies.add(ConsistencyLevel.STRONG); case BOUNDED_STALENESS: testConsistencies.add(ConsistencyLevel.BOUNDED_STALENESS); case SESSION: testConsistencies.add(ConsistencyLevel.SESSION); case CONSISTENT_PREFIX: testConsistencies.add(ConsistencyLevel.CONSISTENT_PREFIX); case EVENTUAL: testConsistencies.add(ConsistencyLevel.EVENTUAL); break; default: throw new IllegalStateException("INVALID configured test consistency " + accountConsistency); } return testConsistencies; } private static Object[][] clientBuildersWithDirect(List<ConsistencyLevel> testConsistencies, boolean contentResponseOnWriteEnabled, Protocol... protocols) { boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(c -> new Object[]{c}).collect(Collectors.toList()).toArray(new Object[0][]); } static protected CosmosClientBuilder createGatewayHouseKeepingDocumentClient(boolean contentResponseOnWriteEnabled) { ThrottlingRetryOptions options = new ThrottlingRetryOptions(); options.setMaxRetryWaitTime(Duration.ofSeconds(SUITE_SETUP_TIMEOUT)); GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .throttlingRetryOptions(options) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(ConsistencyLevel.SESSION); } static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .multipleWriteRegionsEnabled(multiMasterEnabled) .preferredRegions(preferredRegions) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); } static protected CosmosClientBuilder createGatewayRxDocumentClient() { return createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true); } static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, Protocol protocol, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { CosmosClientBuilder builder = new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .directMode(DirectConnectionConfig.getDefaultConfig()) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); if (preferredRegions != null) { builder.preferredRegions(preferredRegions); } if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.SESSION) { builder.multipleWriteRegionsEnabled(true); } Configs configs = spy(new Configs()); doAnswer((Answer<Protocol>)invocation -> protocol).when(configs).getProtocol(); return injectConfigs(builder, configs); } protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { return Math.max((totalExpectedResult + maxPageSize - 1 ) / maxPageSize, 1); } @DataProvider(name = "queryMetricsArgProvider") public Object[][] queryMetricsArgProvider() { return new Object[][]{ {true}, {false}, }; } public static CosmosClientBuilder copyCosmosClientBuilder(CosmosClientBuilder builder) { return CosmosBridgeInternal.cloneCosmosClientBuilder(builder); } }
}
protected static void truncateCollection(CosmosAsyncContainer cosmosContainer) { CosmosContainerProperties cosmosContainerProperties = cosmosContainer.read().block().getProperties(); String cosmosContainerId = cosmosContainerProperties.getId(); logger.info("Truncating collection {} ...", cosmosContainerId); List<String> paths = cosmosContainerProperties.getPartitionKeyDefinition().getPaths(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setMaxDegreeOfParallelism(-1); int maxItemCount = 100; logger.info("Truncating collection {} documents ...", cosmosContainer.getId()); cosmosContainer.queryItems("SELECT * FROM root", options, CosmosItemProperties.class) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(doc -> { PartitionKey partitionKey = null; Object propertyValue = null; if (paths != null && !paths.isEmpty()) { List<String> pkPath = PathParser.getPathParts(paths.get(0)); propertyValue = ModelBridgeInternal.getObjectByPathFromJsonSerializable(doc, pkPath); if (propertyValue == null) { partitionKey = PartitionKey.NONE; } else { partitionKey = new PartitionKey(propertyValue); } } else { partitionKey = new PartitionKey(null); } return cosmosContainer.deleteItem(doc.getId(), partitionKey); }).then().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); cosmosContainer.getScripts().queryTriggers("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(trigger -> { return cosmosContainer.getScripts().getTrigger(trigger.getId()).delete(); }).then().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); cosmosContainer.getScripts().queryStoredProcedures("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(storedProcedure -> { return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.getId()).delete(new CosmosStoredProcedureRequestOptions()); }).then().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); cosmosContainer.getScripts().queryUserDefinedFunctions("SELECT * FROM root", options) .byPage(maxItemCount) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(udf -> { return cosmosContainer.getScripts().getUserDefinedFunction(udf.getId()).delete(); }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); } @SuppressWarnings({"fallthrough"}) protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (CosmosBridgeInternal.getConsistencyLevel(clientBuilder)) { case EVENTUAL: case CONSISTENT_PREFIX: logger.info(" additional wait in EVENTUAL mode so the replica catch up"); try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); } catch (Exception e) { logger.error("unexpected failure", e); } case SESSION: case BOUNDED_STALENESS: case STRONG: default: break; } } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options, int throughput) { database.createContainer(cosmosContainerProperties, ThroughputProperties.createManualThroughput(throughput), options).block(); return database.getContainer(cosmosContainerProperties.getId()); } public static CosmosAsyncContainer createCollection(CosmosAsyncDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options) { database.createContainer(cosmosContainerProperties, options).block(); return database.getContainer(cosmosContainerProperties.getId()); } private static CosmosContainerProperties getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; final String STRING_FIELD_2 = "stringField2"; final String BOOL_FIELD = "boolField"; final String NULL_FIELD = "nullField"; final String OBJECT_FIELD = "objectField"; final String ARRAY_FIELD = "arrayField"; final String SHORT_STRING_FIELD = "shortStringField"; final String MEDIUM_STRING_FIELD = "mediumStringField"; final String LONG_STRING_FIELD = "longStringField"; final String PARTITION_KEY = "pk"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList<String> partitionKeyPaths = new ArrayList<String>(); partitionKeyPaths.add("/" + PARTITION_KEY); partitionKeyDefinition.setPaths(partitionKeyPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<List<CompositePath>> compositeIndexes = new ArrayList<>(); ArrayList<CompositePath> compositeIndexSimple = new ArrayList<CompositePath>(); CompositePath compositePath1 = new CompositePath(); compositePath1.setPath("/" + NUMBER_FIELD); compositePath1.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); compositePath2.setPath("/" + STRING_FIELD); compositePath2.setOrder(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); ArrayList<CompositePath> compositeIndexMaxColumns = new ArrayList<CompositePath>(); CompositePath compositePath3 = new CompositePath(); compositePath3.setPath("/" + NUMBER_FIELD); compositePath3.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); compositePath4.setPath("/" + STRING_FIELD); compositePath4.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); compositePath5.setPath("/" + NUMBER_FIELD_2); compositePath5.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); compositePath6.setPath("/" + STRING_FIELD_2); compositePath6.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); compositeIndexMaxColumns.add(compositePath5); compositeIndexMaxColumns.add(compositePath6); ArrayList<CompositePath> compositeIndexPrimitiveValues = new ArrayList<CompositePath>(); CompositePath compositePath7 = new CompositePath(); compositePath7.setPath("/" + NUMBER_FIELD); compositePath7.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); compositePath8.setPath("/" + STRING_FIELD); compositePath8.setOrder(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); compositePath9.setPath("/" + BOOL_FIELD); compositePath9.setOrder(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); compositePath10.setPath("/" + NULL_FIELD); compositePath10.setOrder(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); compositeIndexPrimitiveValues.add(compositePath9); compositeIndexPrimitiveValues.add(compositePath10); ArrayList<CompositePath> compositeIndexLongStrings = new ArrayList<CompositePath>(); CompositePath compositePath11 = new CompositePath(); compositePath11.setPath("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); compositePath12.setPath("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); compositePath13.setPath("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); compositePath14.setPath("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); compositeIndexLongStrings.add(compositePath13); compositeIndexLongStrings.add(compositePath14); compositeIndexes.add(compositeIndexSimple); compositeIndexes.add(compositeIndexMaxColumns); compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.setCompositeIndexes(compositeIndexes); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static CosmosAsyncContainer createCollection(CosmosAsyncClient client, String dbId, CosmosContainerProperties collectionDefinition) { CosmosAsyncDatabase database = client.getDatabase(dbId); database.createContainer(collectionDefinition).block(); return database.getContainer(collectionDefinition.getId()); } public static void deleteCollection(CosmosAsyncClient client, String dbId, String collectionId) { client.getDatabase(dbId).getContainer(collectionId).delete().block(); } public static CosmosItemProperties createDocument(CosmosAsyncContainer cosmosContainer, CosmosItemProperties item) { return BridgeInternal.getProperties(cosmosContainer.createItem(item).block()); } public <T> Flux<CosmosItemResponse<T>> bulkInsert(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList, int concurrencyLevel) { List<Mono<CosmosItemResponse<T>>> result = new ArrayList<>(documentDefinitionList.size()); for (T docDef : documentDefinitionList) { result.add(cosmosContainer.createItem(docDef)); } return Flux.merge(Flux.fromIterable(result), concurrencyLevel); } public <T> List<T> bulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<T> documentDefinitionList) { return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> itemResponse.getItem()) .collectList() .block(); } public void voidBulkInsertBlocking(CosmosAsyncContainer cosmosContainer, List<CosmosItemProperties> documentDefinitionList) { bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) .map(itemResponse -> BridgeInternal.getProperties(itemResponse)) .then() .block(); } public static CosmosAsyncUser createUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties userSettings) { CosmosAsyncDatabase database = client.getDatabase(databaseId); CosmosUserResponse userResponse = database.createUser(userSettings).block(); return database.getUser(userResponse.getProperties().getId()); } public static CosmosAsyncUser safeCreateUser(CosmosAsyncClient client, String databaseId, CosmosUserProperties user) { deleteUserIfExists(client, databaseId, user.getId()); return createUser(client, databaseId, user); } private static CosmosAsyncContainer safeCreateCollection(CosmosAsyncClient client, String databaseId, CosmosContainerProperties collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.getId()); return createCollection(client.getDatabase(databaseId), collection, options); } static protected CosmosContainerProperties getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList<String> paths = new ArrayList<String>(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndexWithIdAsPartitionKey() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/id")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex() { return getCollectionDefinitionWithRangeRangeIndex(Collections.singletonList("/mypk")); } static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex(List<String> partitionKeyPath) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); partitionKeyDef.setPaths(partitionKeyPath); IndexingPolicy indexingPolicy = new IndexingPolicy(); List<IncludedPath> includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath("/*"); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); cosmosContainerProperties.setIndexingPolicy(indexingPolicy); return cosmosContainerProperties; } public static void deleteCollectionIfExists(CosmosAsyncClient client, String databaseId, String collectionId) { CosmosAsyncDatabase database = client.getDatabase(databaseId); database.read().block(); List<CosmosContainerProperties> res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) .collectList() .block(); if (!res.isEmpty()) { deleteCollection(database, collectionId); } } public static void deleteCollection(CosmosAsyncDatabase cosmosDatabase, String collectionId) { cosmosDatabase.getContainer(collectionId).delete().block(); } public static void deleteCollection(CosmosAsyncContainer cosmosContainer) { cosmosContainer.delete().block(); } public static void deleteDocumentIfExists(CosmosAsyncClient client, String databaseId, String collectionId, String docId) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setPartitionKey(new PartitionKey(docId)); CosmosAsyncContainer cosmosContainer = client.getDatabase(databaseId).getContainer(collectionId); List<CosmosItemProperties> res = cosmosContainer .queryItems(String.format("SELECT * FROM root r where r.id = '%s'", docId), options, CosmosItemProperties.class) .byPage() .flatMap(page -> Flux.fromIterable(page.getResults())) .collectList().block(); if (!res.isEmpty()) { deleteDocument(cosmosContainer, docId); } } public static void safeDeleteDocument(CosmosAsyncContainer cosmosContainer, String documentId, Object partitionKey) { if (cosmosContainer != null && documentId != null) { try { cosmosContainer.deleteItem(documentId, new PartitionKey(partitionKey)).block(); } catch (Exception e) { CosmosException dce = Utils.as(e, CosmosException.class); if (dce == null || dce.getStatusCode() != 404) { throw e; } } } } public static void deleteDocument(CosmosAsyncContainer cosmosContainer, String documentId) { cosmosContainer.deleteItem(documentId, PartitionKey.NONE).block(); } public static void deleteUserIfExists(CosmosAsyncClient client, String databaseId, String userId) { CosmosAsyncDatabase database = client.getDatabase(databaseId); client.getDatabase(databaseId).read().block(); List<CosmosUserProperties> res = database .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) .collectList().block(); if (!res.isEmpty()) { deleteUser(database, userId); } } public static void deleteUser(CosmosAsyncDatabase database, String userId) { database.getUser(userId).delete().block(); } static private CosmosAsyncDatabase safeCreateDatabase(CosmosAsyncClient client, CosmosDatabaseProperties databaseSettings) { safeDeleteDatabase(client.getDatabase(databaseSettings.getId())); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } static protected CosmosAsyncDatabase createDatabase(CosmosAsyncClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } static protected CosmosDatabase createSyncDatabase(CosmosClient client, String databaseId) { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); try { client.createDatabase(databaseSettings); return client.getDatabase(databaseSettings.getId()); } catch (CosmosException e) { e.printStackTrace(); } return null; } static protected CosmosAsyncDatabase createDatabaseIfNotExists(CosmosAsyncClient client, String databaseId) { List<CosmosDatabaseProperties> res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) .collectList() .block(); if (res.size() != 0) { CosmosAsyncDatabase database = client.getDatabase(databaseId); database.read().block(); return database; } else { CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); client.createDatabase(databaseSettings).block(); return client.getDatabase(databaseSettings.getId()); } } static protected void safeDeleteDatabase(CosmosAsyncDatabase database) { if (database != null) { try { database.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteSyncDatabase(CosmosDatabase database) { if (database != null) { try { logger.info("attempting to delete database ...."); database.delete(); logger.info("database deletion completed"); } catch (Exception e) { logger.error("failed to delete sync database", e); } } } static protected void safeDeleteAllCollections(CosmosAsyncDatabase database) { if (database != null) { List<CosmosContainerProperties> collections = database.readAllContainers() .collectList() .block(); for(CosmosContainerProperties collection: collections) { database.getContainer(collection.getId()).delete().block(); } } } static protected void safeDeleteCollection(CosmosAsyncContainer collection) { if (collection != null) { try { collection.delete().block(); } catch (Exception e) { } } } static protected void safeDeleteCollection(CosmosAsyncDatabase database, String collectionId) { if (database != null && collectionId != null) { try { database.getContainer(collectionId).delete().block(); } catch (Exception e) { } } } static protected void safeCloseAsync(CosmosAsyncClient client) { if (client != null) { new Thread(() -> { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } }).start(); } } static protected void safeClose(CosmosAsyncClient client) { if (client != null) { try { client.close(); } catch (Exception e) { logger.error("failed to close client", e); } } } static protected void safeCloseSyncClient(CosmosClient client) { if (client != null) { try { logger.info("closing client ..."); client.close(); logger.info("closing client completed"); } catch (Exception e) { logger.error("failed to close client", e); } } } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator) { validateSuccess(single, validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public <T extends CosmosResponse> void validateSuccess(Mono<T> single, CosmosResponseValidator<T> validator, long timeout) { validateSuccess(single.flux(), validator, timeout); } @SuppressWarnings("rawtypes") public static <T extends CosmosResponse> void validateSuccess(Flux<T> flowable, CosmosResponseValidator<T> validator, long timeout) { TestSubscriber<T> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T, U extends CosmosResponse> void validateFailure(Mono<U> mono, FailureValidator validator) throws InterruptedException { validateFailure(mono.flux(), validator, subscriberValidationTimeout); } @SuppressWarnings("rawtypes") public static <T extends Resource, U extends CosmosResponse> void validateFailure(Flux<U> flowable, FailureValidator validator, long timeout) throws InterruptedException { TestSubscriber<CosmosResponse> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosItemResponse> void validateItemSuccess( Mono<T> responseMono, CosmosItemResponseValidator validator) { TestSubscriber<CosmosItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); validator.validate(testSubscriber.values().get(0)); } @SuppressWarnings("rawtypes") public <T extends CosmosItemResponse> void validateItemFailure( Mono<T> responseMono, FailureValidator validator) { TestSubscriber<CosmosItemResponse> testSubscriber = new TestSubscriber<>(); responseMono.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(subscriberValidationTimeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.errors()).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } public <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator) { validateQuerySuccess(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQuerySuccess(Flux<FeedResponse<T>> flowable, FeedResponseListValidator<T> validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); validator.validate(testSubscriber.values()); } public <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator) { validateQueryFailure(flowable, validator, subscriberValidationTimeout); } public static <T> void validateQueryFailure(Flux<FeedResponse<T>> flowable, FailureValidator validator, long timeout) { TestSubscriber<FeedResponse<T>> testSubscriber = new TestSubscriber<>(); flowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotComplete(); testSubscriber.assertTerminated(); assertThat(testSubscriber.getEvents().get(1)).hasSize(1); validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @DataProvider public static Object[][] clientBuilders() { return new Object[][]{{createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)}}; } @DataProvider public static Object[][] clientBuildersWithSessionConsistency() { return new Object[][]{ {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.HTTPS, false, null, true)}, {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.TCP, false, null, true)}, {createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true)} }; } static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); return ConsistencyLevel.valueOf(consistency); } logger.error("INVALID configured test consistency [{}].", consistency); throw new IllegalStateException("INVALID configured test consistency " + consistency); } static List<String> parsePreferredLocation(String preferredLocations) { if (StringUtils.isEmpty(preferredLocations)) { return null; } try { return objectMapper.readValue(preferredLocations, new TypeReference<List<String>>() { }); } catch (Exception e) { logger.error("INVALID configured test preferredLocations [{}].", preferredLocations); throw new IllegalStateException("INVALID configured test preferredLocations " + preferredLocations); } } static List<Protocol> parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } List<Protocol> protocolList = new ArrayList<>(); try { List<String> protocolStrings = objectMapper.readValue(protocols, new TypeReference<List<String>>() { }); for(String protocol : protocolStrings) { protocolList.add(Protocol.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, protocol))); } return protocolList; } catch (Exception e) { logger.error("INVALID configured test protocols [{}].", protocols); throw new IllegalStateException("INVALID configured test protocols " + protocols); } } @DataProvider public static Object[][] simpleClientBuildersWithDirect() { return simpleClientBuildersWithDirect(true, toArray(protocols)); } @DataProvider public static Object[][] simpleClientBuildersWithDirectHttps() { return simpleClientBuildersWithDirect(true, Protocol.HTTPS); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcp() { return simpleClientBuildersWithDirect(true, Protocol.TCP); } @DataProvider public static Object[][] simpleClientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return simpleClientBuildersWithDirect(false, Protocol.TCP); } private static Object[][] simpleClientBuildersWithDirect(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); List<ConsistencyLevel> testConsistencies = ImmutableList.of(ConsistencyLevel.EVENTUAL); boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient( consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); } @DataProvider public static Object[][] clientBuildersWithDirect() { return clientBuildersWithDirectAllConsistencies(true, toArray(protocols)); } @DataProvider public static Object[][] clientBuildersWithDirectHttps() { return clientBuildersWithDirectAllConsistencies(true, Protocol.HTTPS); } @DataProvider public static Object[][] clientBuildersWithDirectTcp() { return clientBuildersWithDirectAllConsistencies(true, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectTcpWithContentResponseOnWriteDisabled() { return clientBuildersWithDirectAllConsistencies(false, Protocol.TCP); } @DataProvider public static Object[][] clientBuildersWithDirectSession() { return clientBuildersWithDirectSession(true, toArray(protocols)); } static Protocol[] toArray(List<Protocol> protocols) { return protocols.toArray(new Protocol[protocols.size()]); } private static Object[][] clientBuildersWithDirectSession(boolean contentResponseOnWriteEnabled, Protocol... protocols) { return clientBuildersWithDirect(new ArrayList<ConsistencyLevel>() {{ add(ConsistencyLevel.SESSION); }}, contentResponseOnWriteEnabled, protocols); } private static Object[][] clientBuildersWithDirectAllConsistencies(boolean contentResponseOnWriteEnabled, Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); return clientBuildersWithDirect(desiredConsistencies, contentResponseOnWriteEnabled, protocols); } static List<ConsistencyLevel> parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } List<ConsistencyLevel> consistencyLevels = new ArrayList<>(); try { List<String> consistencyStrings = objectMapper.readValue(consistencies, new TypeReference<List<String>>() {}); for(String consistency : consistencyStrings) { consistencyLevels.add(ConsistencyLevel.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency))); } return consistencyLevels; } catch (Exception e) { logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); } } @SuppressWarnings("fallthrough") static List<ConsistencyLevel> allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List<ConsistencyLevel> testConsistencies = new ArrayList<>(); switch (accountConsistency) { case STRONG: testConsistencies.add(ConsistencyLevel.STRONG); case BOUNDED_STALENESS: testConsistencies.add(ConsistencyLevel.BOUNDED_STALENESS); case SESSION: testConsistencies.add(ConsistencyLevel.SESSION); case CONSISTENT_PREFIX: testConsistencies.add(ConsistencyLevel.CONSISTENT_PREFIX); case EVENTUAL: testConsistencies.add(ConsistencyLevel.EVENTUAL); break; default: throw new IllegalStateException("INVALID configured test consistency " + accountConsistency); } return testConsistencies; } private static Object[][] clientBuildersWithDirect(List<ConsistencyLevel> testConsistencies, boolean contentResponseOnWriteEnabled, Protocol... protocols) { boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List<CosmosClientBuilder> cosmosConfigurations = new ArrayList<>(); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled))); } cosmosConfigurations.forEach(c -> { ConnectionPolicy connectionPolicy = CosmosBridgeInternal.getConnectionPolicy(c); ConsistencyLevel consistencyLevel = CosmosBridgeInternal.getConsistencyLevel(c); logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", connectionPolicy.getConnectionMode(), consistencyLevel, extractConfigs(c).getProtocol() ); }); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations, contentResponseOnWriteEnabled)); return cosmosConfigurations.stream().map(c -> new Object[]{c}).collect(Collectors.toList()).toArray(new Object[0][]); } static protected CosmosClientBuilder createGatewayHouseKeepingDocumentClient(boolean contentResponseOnWriteEnabled) { ThrottlingRetryOptions options = new ThrottlingRetryOptions(); options.setMaxRetryWaitTime(Duration.ofSeconds(SUITE_SETUP_TIMEOUT)); GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .throttlingRetryOptions(options) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(ConsistencyLevel.SESSION); } static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); return new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .gatewayMode(gatewayConnectionConfig) .multipleWriteRegionsEnabled(multiMasterEnabled) .preferredRegions(preferredRegions) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); } static protected CosmosClientBuilder createGatewayRxDocumentClient() { return createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null, true); } static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, Protocol protocol, boolean multiMasterEnabled, List<String> preferredRegions, boolean contentResponseOnWriteEnabled) { CosmosClientBuilder builder = new CosmosClientBuilder().endpoint(TestConfigurations.HOST) .credential(credential) .directMode(DirectConnectionConfig.getDefaultConfig()) .contentResponseOnWriteEnabled(contentResponseOnWriteEnabled) .consistencyLevel(consistencyLevel); if (preferredRegions != null) { builder.preferredRegions(preferredRegions); } if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.SESSION) { builder.multipleWriteRegionsEnabled(true); } Configs configs = spy(new Configs()); doAnswer((Answer<Protocol>)invocation -> protocol).when(configs).getProtocol(); return injectConfigs(builder, configs); } protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { return Math.max((totalExpectedResult + maxPageSize - 1 ) / maxPageSize, 1); } @DataProvider(name = "queryMetricsArgProvider") public Object[][] queryMetricsArgProvider() { return new Object[][]{ {true}, {false}, }; } public static CosmosClientBuilder copyCosmosClientBuilder(CosmosClientBuilder builder) { return CosmosBridgeInternal.cloneCosmosClientBuilder(builder); } }
class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(CosmosAsyncClient client) { return new DatabaseManagerImpl(client); } private final CosmosAsyncClient client; private DatabaseManagerImpl(CosmosAsyncClient client) { this.client = client; } @Override public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override public Mono<CosmosAsyncDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseDefinition) { return client.createDatabase(databaseDefinition); } @Override public CosmosAsyncDatabase getDatabase(String id) { return client.getDatabase(id); } }
class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(CosmosAsyncClient client) { return new DatabaseManagerImpl(client); } private final CosmosAsyncClient client; private DatabaseManagerImpl(CosmosAsyncClient client) { this.client = client; } @Override public CosmosPagedFlux<CosmosDatabaseProperties> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseDefinition) { return client.createDatabase(databaseDefinition); } @Override public CosmosAsyncDatabase getDatabase(String id) { return client.getDatabase(id); } }
Will address all testing format comment in next tracer event pr as discussed offline
public void cosmosAsyncClient() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); client.readAllDatabases(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + cosmosAsyncDatabase.getId() + "'"; client.queryDatabases(query, new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); }
Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(),
public void cosmosAsyncClient() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); client.readAllDatabases(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + cosmosAsyncDatabase.getId() + "'"; client.queryDatabases(query, new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); }
class CosmosTracerTest extends TestSuiteBase { private static final String ITEM_ID = "tracerDoc"; CosmosAsyncClient client; CosmosAsyncDatabase cosmosAsyncDatabase; CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .buildAsyncClient(); cosmosAsyncDatabase = getSharedCosmosDatabase(client); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(client); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncDatabase() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncDatabase.createContainerIfNotExists(cosmosAsyncContainer.getId(), "/pk", 5000).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncDatabase.readProvisionedThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllUsers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllContainers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncContainer() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.read().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncContainer.readProvisionedThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosItemProperties properties = new CosmosItemProperties(); properties.setId(ITEM_ID); cosmosAsyncContainer.createItem(properties).block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.upsertItem(properties, new CosmosItemRequestOptions()).block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readItem(ITEM_ID, PartitionKey.NONE, CosmosItemProperties.class).block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.deleteItem(ITEM_ID, PartitionKey.NONE).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readAllItems(new FeedOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + ITEM_ID + "'"; cosmosAsyncContainer.queryItems(query, new FeedOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncScripts() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties = getCosmosUserDefinedFunctionProperties(); CosmosUserDefinedFunctionProperties resultUdf = cosmosAsyncContainer.getScripts().createUserDefinedFunction(cosmosUserDefinedFunctionProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosUserDefinedFunctionProperties.setBody("function() {var x = 15;}"); cosmosAsyncContainer.getScripts().getUserDefinedFunction(resultUdf.getId()).replace(resultUdf).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosTriggerProperties cosmosTriggerProperties = getCosmosTriggerProperties(); CosmosTriggerProperties resultTrigger = cosmosAsyncContainer.getScripts().createTrigger(cosmosTriggerProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(9)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(10)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).replace(resultTrigger).block(); Mockito.verify(tracer, Mockito.times(11)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(12)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(13)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosStoredProcedureProperties procedureProperties = getCosmosStoredProcedureProperties(); CosmosStoredProcedureProperties resultSproc = cosmosAsyncContainer.getScripts().createStoredProcedure(procedureProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(14)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(15)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).replace(resultSproc).block(); Mockito.verify(tracer, Mockito.times(16)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new FeedOptions()).byPage().single().block(); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(18)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @AfterClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void afterClass() { LifeCycleUtils.closeQuietly(client); } private static CosmosUserDefinedFunctionProperties getCosmosUserDefinedFunctionProperties() { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return udf; } private static CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } private static CosmosStoredProcedureProperties getCosmosStoredProcedureProperties() { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.setId(UUID.randomUUID().toString()); storedProcedureDef.setBody("function() {var x = 10;}"); return storedProcedureDef; } }
class CosmosTracerTest extends TestSuiteBase { private static final String ITEM_ID = "tracerDoc"; CosmosAsyncClient client; CosmosAsyncDatabase cosmosAsyncDatabase; CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .buildAsyncClient(); cosmosAsyncDatabase = getSharedCosmosDatabase(client); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(client); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncDatabase() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncDatabase.createContainerIfNotExists(cosmosAsyncContainer.getId(), "/pk", 5000).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncDatabase.readThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllUsers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllContainers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncContainer() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.read().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncContainer.readThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosItemProperties properties = new CosmosItemProperties(); properties.setId(ITEM_ID); cosmosAsyncContainer.createItem(properties).block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.upsertItem(properties, new CosmosItemRequestOptions()).block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readItem(ITEM_ID, PartitionKey.NONE, CosmosItemProperties.class).block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.deleteItem(ITEM_ID, PartitionKey.NONE).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readAllItems(new CosmosQueryRequestOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + ITEM_ID + "'"; cosmosAsyncContainer.queryItems(query, new CosmosQueryRequestOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncScripts() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties = getCosmosUserDefinedFunctionProperties(); CosmosUserDefinedFunctionProperties resultUdf = cosmosAsyncContainer.getScripts().createUserDefinedFunction(cosmosUserDefinedFunctionProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosUserDefinedFunctionProperties.setBody("function() {var x = 15;}"); cosmosAsyncContainer.getScripts().getUserDefinedFunction(resultUdf.getId()).replace(resultUdf).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosTriggerProperties cosmosTriggerProperties = getCosmosTriggerProperties(); CosmosTriggerProperties resultTrigger = cosmosAsyncContainer.getScripts().createTrigger(cosmosTriggerProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(9)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(10)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).replace(resultTrigger).block(); Mockito.verify(tracer, Mockito.times(11)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(12)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(13)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosStoredProcedureProperties procedureProperties = getCosmosStoredProcedureProperties(); CosmosStoredProcedureProperties resultSproc = cosmosAsyncContainer.getScripts().createStoredProcedure(procedureProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(14)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(15)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).replace(resultSproc).block(); Mockito.verify(tracer, Mockito.times(16)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new CosmosQueryRequestOptions()).byPage().single().block(); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(18)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @AfterClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void afterClass() { LifeCycleUtils.closeQuietly(client); } private static CosmosUserDefinedFunctionProperties getCosmosUserDefinedFunctionProperties() { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); return udf; } private static CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } private static CosmosStoredProcedureProperties getCosmosStoredProcedureProperties() { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); return storedProcedureDef; } }
Will address testing format comment in next tracer event pr as discussed offline
public void cosmosAsyncClient() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); client.readAllDatabases(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + cosmosAsyncDatabase.getId() + "'"; client.queryDatabases(query, new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); }
client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block();
public void cosmosAsyncClient() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); client.createDatabaseIfNotExists(cosmosAsyncDatabase.getId()).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); client.readAllDatabases(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + cosmosAsyncDatabase.getId() + "'"; client.queryDatabases(query, new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); }
class CosmosTracerTest extends TestSuiteBase { private static final String ITEM_ID = "tracerDoc"; CosmosAsyncClient client; CosmosAsyncDatabase cosmosAsyncDatabase; CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .buildAsyncClient(); cosmosAsyncDatabase = getSharedCosmosDatabase(client); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(client); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncDatabase() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncDatabase.createContainerIfNotExists(cosmosAsyncContainer.getId(), "/pk", 5000).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncDatabase.readProvisionedThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllUsers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllContainers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncContainer() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.read().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncContainer.readProvisionedThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosItemProperties properties = new CosmosItemProperties(); properties.setId(ITEM_ID); cosmosAsyncContainer.createItem(properties).block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.upsertItem(properties, new CosmosItemRequestOptions()).block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readItem(ITEM_ID, PartitionKey.NONE, CosmosItemProperties.class).block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.deleteItem(ITEM_ID, PartitionKey.NONE).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readAllItems(new FeedOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + ITEM_ID + "'"; cosmosAsyncContainer.queryItems(query, new FeedOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncScripts() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties = getCosmosUserDefinedFunctionProperties(); CosmosUserDefinedFunctionProperties resultUdf = cosmosAsyncContainer.getScripts().createUserDefinedFunction(cosmosUserDefinedFunctionProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosUserDefinedFunctionProperties.setBody("function() {var x = 15;}"); cosmosAsyncContainer.getScripts().getUserDefinedFunction(resultUdf.getId()).replace(resultUdf).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosTriggerProperties cosmosTriggerProperties = getCosmosTriggerProperties(); CosmosTriggerProperties resultTrigger = cosmosAsyncContainer.getScripts().createTrigger(cosmosTriggerProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(9)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(10)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).replace(resultTrigger).block(); Mockito.verify(tracer, Mockito.times(11)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new FeedOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(12)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(13)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosStoredProcedureProperties procedureProperties = getCosmosStoredProcedureProperties(); CosmosStoredProcedureProperties resultSproc = cosmosAsyncContainer.getScripts().createStoredProcedure(procedureProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(14)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(15)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).replace(resultSproc).block(); Mockito.verify(tracer, Mockito.times(16)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new FeedOptions()).byPage().single().block(); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(18)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @AfterClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void afterClass() { LifeCycleUtils.closeQuietly(client); } private static CosmosUserDefinedFunctionProperties getCosmosUserDefinedFunctionProperties() { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return udf; } private static CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } private static CosmosStoredProcedureProperties getCosmosStoredProcedureProperties() { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.setId(UUID.randomUUID().toString()); storedProcedureDef.setBody("function() {var x = 10;}"); return storedProcedureDef; } }
class CosmosTracerTest extends TestSuiteBase { private static final String ITEM_ID = "tracerDoc"; CosmosAsyncClient client; CosmosAsyncDatabase cosmosAsyncDatabase; CosmosAsyncContainer cosmosAsyncContainer; @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .directMode(DirectConnectionConfig.getDefaultConfig()) .buildAsyncClient(); cosmosAsyncDatabase = getSharedCosmosDatabase(client); cosmosAsyncContainer = getSharedMultiPartitionCosmosContainer(client); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncDatabase() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncDatabase.createContainerIfNotExists(cosmosAsyncContainer.getId(), "/pk", 5000).block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncDatabase.readThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllUsers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncDatabase.readAllContainers().byPage().single().block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncContainer() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.read().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); try { cosmosAsyncContainer.readThroughput().block(); } catch (CosmosException ex) { } Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosItemProperties properties = new CosmosItemProperties(); properties.setId(ITEM_ID); cosmosAsyncContainer.createItem(properties).block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.upsertItem(properties, new CosmosItemRequestOptions()).block(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readItem(ITEM_ID, PartitionKey.NONE, CosmosItemProperties.class).block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.deleteItem(ITEM_ID, PartitionKey.NONE).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.readAllItems(new CosmosQueryRequestOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); String query = "select * from c where c.id = '" + ITEM_ID + "'"; cosmosAsyncContainer.queryItems(query, new CosmosQueryRequestOptions(), CosmosItemRequestOptions.class).byPage().single().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void cosmosAsyncScripts() { TracerProvider tracer = Mockito.spy(new TracerProvider(ServiceLoader.load(Tracer.class))); ReflectionUtils.setTracerProvider(client, tracer); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(1)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(2)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(3)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties = getCosmosUserDefinedFunctionProperties(); CosmosUserDefinedFunctionProperties resultUdf = cosmosAsyncContainer.getScripts().createUserDefinedFunction(cosmosUserDefinedFunctionProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(4)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(5)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosUserDefinedFunctionProperties.setBody("function() {var x = 15;}"); cosmosAsyncContainer.getScripts().getUserDefinedFunction(resultUdf.getId()).replace(resultUdf).block(); Mockito.verify(tracer, Mockito.times(6)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllUserDefinedFunctions(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(7)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getUserDefinedFunction(cosmosUserDefinedFunctionProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(8)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosTriggerProperties cosmosTriggerProperties = getCosmosTriggerProperties(); CosmosTriggerProperties resultTrigger = cosmosAsyncContainer.getScripts().createTrigger(cosmosTriggerProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(9)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(10)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).replace(resultTrigger).block(); Mockito.verify(tracer, Mockito.times(11)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllTriggers(new CosmosQueryRequestOptions()).byPage().single().block(); Mockito.verify(tracer, Mockito.times(12)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getTrigger(cosmosTriggerProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(13)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); CosmosStoredProcedureProperties procedureProperties = getCosmosStoredProcedureProperties(); CosmosStoredProcedureProperties resultSproc = cosmosAsyncContainer.getScripts().createStoredProcedure(procedureProperties).block().getProperties(); Mockito.verify(tracer, Mockito.times(14)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).read().block(); Mockito.verify(tracer, Mockito.times(15)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).replace(resultSproc).block(); Mockito.verify(tracer, Mockito.times(16)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); cosmosAsyncContainer.getScripts().readAllStoredProcedures(new CosmosQueryRequestOptions()).byPage().single().block(); cosmosAsyncContainer.getScripts().getStoredProcedure(procedureProperties.getId()).delete().block(); Mockito.verify(tracer, Mockito.times(18)).startSpan(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.any(Context.class)); } @AfterClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void afterClass() { LifeCycleUtils.closeQuietly(client); } private static CosmosUserDefinedFunctionProperties getCosmosUserDefinedFunctionProperties() { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); return udf; } private static CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } private static CosmosStoredProcedureProperties getCosmosStoredProcedureProperties() { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(UUID.randomUUID().toString(), "function() {var x = 10;}"); return storedProcedureDef; } }
removed setting AZ_TRACING_NAMESPACE_KEY explicitly on tracer
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); for (Tracer tracer : tracers) { local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; }
tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local);
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; }
class TracerProvider { private final List<Tracer> tracers = new ArrayList<>(); private final boolean isEnabled; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); tracers.forEach(this.tracers::add); isEnabled = this.tracers.size() > 0; } public boolean isEnabled() { return isEnabled; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<T> traceEnabledNonCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName, databaseId, endpoint, (T response) -> HttpConstants.StatusCodes.OK); } public <T> Mono<CosmosAsyncItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosAsyncItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosAsyncItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), 0); } }); } private void end(int statusCode, Throwable throwable, Context context) { for (Tracer tracer : tracers) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); StringWriter errorStack = new StringWriter(); throwable.printStackTrace(new PrintWriter(errorStack)); tracer.setAttribute(TracerProvider.ERROR_STACK, errorStack.toString(), context); } tracer.end(statusCode, throwable, context); } } }
class TracerProvider { private Tracer tracer; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final int ERROR_CODE = 0; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); if (tracers.iterator().hasNext()) { tracer = tracers.iterator().next(); } } public boolean isEnabled() { return tracer != null; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<CosmosItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), ERROR_CODE); } }); } private void end(int statusCode, Throwable throwable, Context context) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); } tracer.end(statusCode, throwable, context); } }
done
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); for (Tracer tracer : tracers) { local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; }
for (Tracer tracer : tracers) {
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; }
class TracerProvider { private final List<Tracer> tracers = new ArrayList<>(); private final boolean isEnabled; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); tracers.forEach(this.tracers::add); isEnabled = this.tracers.size() > 0; } public boolean isEnabled() { return isEnabled; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<T> traceEnabledNonCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName, databaseId, endpoint, (T response) -> HttpConstants.StatusCodes.OK); } public <T> Mono<CosmosAsyncItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosAsyncItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosAsyncItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), 0); } }); } private void end(int statusCode, Throwable throwable, Context context) { for (Tracer tracer : tracers) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); StringWriter errorStack = new StringWriter(); throwable.printStackTrace(new PrintWriter(errorStack)); tracer.setAttribute(TracerProvider.ERROR_STACK, errorStack.toString(), context); } tracer.end(statusCode, throwable, context); } } }
class TracerProvider { private Tracer tracer; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final int ERROR_CODE = 0; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); if (tracers.iterator().hasNext()) { tracer = tracers.iterator().next(); } } public boolean isEnabled() { return tracer != null; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<CosmosItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), ERROR_CODE); } }); } private void end(int statusCode, Throwable throwable, Context context) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); } tracer.end(statusCode, throwable, context); } }
As discussed keeping it the same i.e. AZ_TRACING_NAMESPACE_KEY on attributes, user will get extra warning log if he don't pass this. Will revisit it again in next tracing PR
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); for (Tracer tracer : tracers) { local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; }
tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local);
public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; }
class TracerProvider { private final List<Tracer> tracers = new ArrayList<>(); private final boolean isEnabled; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); tracers.forEach(this.tracers::add); isEnabled = this.tracers.size() > 0; } public boolean isEnabled() { return isEnabled; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<T> traceEnabledNonCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName, databaseId, endpoint, (T response) -> HttpConstants.StatusCodes.OK); } public <T> Mono<CosmosAsyncItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosAsyncItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosAsyncItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), 0); } }); } private void end(int statusCode, Throwable throwable, Context context) { for (Tracer tracer : tracers) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); StringWriter errorStack = new StringWriter(); throwable.printStackTrace(new PrintWriter(errorStack)); tracer.setAttribute(TracerProvider.ERROR_STACK, errorStack.toString(), context); } tracer.end(statusCode, throwable, context); } } }
class TracerProvider { private Tracer tracer; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final int ERROR_CODE = 0; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); if (tracers.iterator().hasNext()) { tracer = tracers.iterator().next(); } } public boolean isEnabled() { return tracer != null; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<CosmosItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), ERROR_CODE); } }); } private void end(int statusCode, Throwable throwable, Context context) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); } tracer.end(statusCode, throwable, context); } }
Removed the error stacktrace
private void end(int statusCode, Throwable throwable, Context context) { for (Tracer tracer : tracers) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); StringWriter errorStack = new StringWriter(); throwable.printStackTrace(new PrintWriter(errorStack)); tracer.setAttribute(TracerProvider.ERROR_STACK, errorStack.toString(), context); } tracer.end(statusCode, throwable, context); } }
throwable.printStackTrace(new PrintWriter(errorStack));
private void end(int statusCode, Throwable throwable, Context context) { if (throwable != null) { tracer.setAttribute(TracerProvider.ERROR_MSG, throwable.getMessage(), context); tracer.setAttribute(TracerProvider.ERROR_TYPE, throwable.getClass().getName(), context); } tracer.end(statusCode, throwable, context); }
class TracerProvider { private final List<Tracer> tracers = new ArrayList<>(); private final boolean isEnabled; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); tracers.forEach(this.tracers::add); isEnabled = this.tracers.size() > 0; } public boolean isEnabled() { return isEnabled; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); for (Tracer tracer : tracers) { local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME, local); tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); } return local; } /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<T> traceEnabledNonCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName, databaseId, endpoint, (T response) -> HttpConstants.StatusCodes.OK); } public <T> Mono<CosmosAsyncItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosAsyncItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosAsyncItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), 0); } }); } }
class TracerProvider { private Tracer tracer; public final static String DB_TYPE_VALUE = "Cosmos"; public final static String DB_TYPE = "db.type"; public final static String DB_INSTANCE = "db.instance"; public final static String DB_URL = "db.url"; public static final String DB_STATEMENT = "db.statement"; public static final String ERROR_MSG = "error.msg"; public static final String ERROR_TYPE = "error.type"; public static final String ERROR_STACK = "error.stack"; public static final String COSMOS_CALL_DEPTH = "cosmosCallDepth"; public static final String COSMOS_CALL_DEPTH_VAL = "nested"; public static final int ERROR_CODE = 0; public static final String RESOURCE_PROVIDER_NAME = "Microsoft.DocumentDB"; public TracerProvider(Iterable<Tracer> tracers) { Objects.requireNonNull(tracers, "'tracers' cannot be null."); if (tracers.iterator().hasNext()) { tracer = tracers.iterator().next(); } } public boolean isEnabled() { return tracer != null; } /** * For each tracer plugged into the SDK a new tracing span is created. * <p> * The {@code context} will be checked for containing information about a parent span. If a parent span is found the * new span will be added as a child, otherwise the span will be created and added to the context and any downstream * start calls will use the created span as the parent. * * @param context Additional metadata that is passed through the call stack. * @return An updated context object. */ public Context startSpan(String methodName, String databaseId, String endpoint, Context context) { Context local = Objects.requireNonNull(context, "'context' cannot be null."); local = local.addData(AZ_TRACING_NAMESPACE_KEY, RESOURCE_PROVIDER_NAME); local = tracer.start(methodName, local); if (databaseId != null) { tracer.setAttribute(TracerProvider.DB_INSTANCE, databaseId, local); } tracer.setAttribute(TracerProvider.DB_TYPE, DB_TYPE_VALUE, local); tracer.setAttribute(TracerProvider.DB_URL, endpoint, local); tracer.setAttribute(TracerProvider.DB_STATEMENT, methodName, local); return local; } /** * Given a context containing the current tracing span the span is marked completed with status info from * {@link Signal}. For each tracer plugged into the SDK the current tracing span is marked as completed. * * @param context Additional metadata that is passed through the call stack. * @param signal The signal indicates the status and contains the metadata we need to end the tracing span. */ public <T extends CosmosResponse<? extends Resource>> void endSpan(Context context, Signal<T> signal, int statusCode) { Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(signal, "'signal' cannot be null."); switch (signal.getType()) { case ON_COMPLETE: end(statusCode, null, context); break; case ON_ERROR: Throwable throwable = null; if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof CosmosException) { CosmosException exception = (CosmosException) throwable; statusCode = exception.getStatusCode(); } } end(statusCode, throwable, context); break; default: break; } } public <T extends CosmosResponse<?>> Mono<T> traceEnabledCosmosResponsePublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, (T response) -> response.getStatusCode()); } public <T> Mono<CosmosItemResponse<T>> traceEnabledCosmosItemResponsePublisher(Mono<CosmosItemResponse<T>> resultPublisher, Context context, String spanName, String databaseId, String endpoint) { return traceEnabledPublisher(resultPublisher, context, spanName,databaseId, endpoint, CosmosItemResponse::getStatusCode); } public <T> Mono<T> traceEnabledPublisher(Mono<T> resultPublisher, Context context, String spanName, String databaseId, String endpoint, Function<T, Integer> statusCodeFunc) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); Optional<Object> callDepth = context.getData(COSMOS_CALL_DEPTH); final boolean isNestedCall = callDepth.isPresent(); return resultPublisher .doOnSubscribe(ignoredValue -> { if (!isNestedCall) { parentContext.set(this.startSpan(spanName, databaseId, endpoint, context)); } }).doOnSuccess(response -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.complete(), statusCodeFunc.apply(response)); } }).doOnError(throwable -> { if (!isNestedCall) { this.endSpan(parentContext.get(), Signal.error(throwable), ERROR_CODE); } }); } }
These would be a good test cases to include as well. `Arguments.arguments(new PercentEscaper( "ह", false), "ह", "ह")` `new PercentEscaper(" ", true); // this should throw exception`
private static Stream<Arguments> escapeSupplier() { PercentEscaper defaultEscaper = new PercentEscaper(null, false); return Stream.of( Arguments.arguments(defaultEscaper, "$", "%24"), Arguments.arguments(defaultEscaper, "¢", "%C2%A2"), Arguments.arguments(defaultEscaper, "ह", "%E0%A4%B9"), Arguments.arguments(defaultEscaper, "€", "%E2%82%AC"), Arguments.arguments(defaultEscaper, "한", "%ED%95%9C"), Arguments.arguments(defaultEscaper, "円", "%E5%86%86"), Arguments.arguments(defaultEscaper, "\uD800\uDF48", "%F0%90%8D%88"), Arguments.arguments(defaultEscaper, "日本語", "%E6%97%A5%E6%9C%AC%E8%AA%9E"), Arguments.arguments(defaultEscaper, " ", "%20"), Arguments.arguments(new PercentEscaper(null, true), " ", "+"), Arguments.arguments(new PercentEscaper("$", false), "$", "$") ); }
Arguments.arguments(new PercentEscaper("$", false), "$", "$")
private static Stream<Arguments> escapeSupplier() { PercentEscaper defaultEscaper = new PercentEscaper(null, false); return Stream.of( Arguments.arguments(defaultEscaper, null, null), Arguments.arguments(defaultEscaper, "", ""), Arguments.arguments(defaultEscaper, "$", "%24"), Arguments.arguments(defaultEscaper, "¢", "%C2%A2"), Arguments.arguments(defaultEscaper, "ह", "%E0%A4%B9"), Arguments.arguments(defaultEscaper, "€", "%E2%82%AC"), Arguments.arguments(defaultEscaper, "한", "%ED%95%9C"), Arguments.arguments(defaultEscaper, "円", "%E5%86%86"), Arguments.arguments(defaultEscaper, "\uD800\uDF48", "%F0%90%8D%88"), Arguments.arguments(defaultEscaper, "日本語", "%E6%97%A5%E6%9C%AC%E8%AA%9E"), Arguments.arguments(defaultEscaper, " ", "%20"), Arguments.arguments(new PercentEscaper(null, true), " ", "+"), Arguments.arguments(new PercentEscaper("$", false), "$", "$"), Arguments.arguments(new PercentEscaper("ह", false), "ह", "ह") ); }
class PercentEscaperTests { @ParameterizedTest @MethodSource("escapeSupplier") public void escape(PercentEscaper escaper, String original, String expected) { assertEquals(expected, escaper.escape(original)); } }
class PercentEscaperTests { /** * Tests that using {@code ' '} as a safe character and treating {@code ' '} as {@code '+'} is an illegal * configuration. */ @Test public void cannotUseSpaceAsPlusAndSpaceAsSafeCharacter() { assertThrows(IllegalArgumentException.class, () -> new PercentEscaper(" ", true)); } /** * Tests that valid inputs are escaped correctly. */ @ParameterizedTest @MethodSource("escapeSupplier") public void escape(PercentEscaper escaper, String original, String expected) { assertEquals(expected, escaper.escape(original)); } @ParameterizedTest @MethodSource("invalidEscapeSupplier") public void invalidEscape(String original) { assertThrows(IllegalStateException.class, () -> new PercentEscaper(null, false).escape(original)); } private static Stream<Arguments> invalidEscapeSupplier() { return Stream.of( Arguments.arguments("abcd\uD800"), Arguments.arguments("abcd\uDF48\uD800"), Arguments.arguments("\uD800abcd") ); } }
This is a semantic breaking change for users as it now encodes strings differently and requires minor version bump.
private static Stream<Arguments> querySubstitutionSupplier() throws NoSuchMethodException { Class<QuerySubstitutionMethods> clazz = QuerySubstitutionMethods.class; Method substitution = clazz.getDeclaredMethod("substitutions", String.class, boolean.class); Method encodedSubstitution = clazz.getDeclaredMethod("encodedSubstitutions", String.class, boolean.class); return Stream.of( Arguments.of(substitution, null, null), Arguments.of(substitution, toObjectArray("raw", true), createExpectedParameters("raw", true)), Arguments.of(substitution, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(substitution, toObjectArray("{sub1}", false), createExpectedParameters("%7Bsub1%7D", false)), Arguments.of(encodedSubstitution, null, null), Arguments.of(encodedSubstitution, toObjectArray("raw", true), createExpectedParameters("raw", true)), Arguments.of(encodedSubstitution, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(encodedSubstitution, toObjectArray("{sub1}", false), createExpectedParameters("{sub1}", false)) ); }
Arguments.of(substitution, toObjectArray("{sub1}", false), createExpectedParameters("%7Bsub1%7D", false)),
private static Stream<Arguments> querySubstitutionSupplier() throws NoSuchMethodException { Class<QuerySubstitutionMethods> clazz = QuerySubstitutionMethods.class; Method substitution = clazz.getDeclaredMethod("substitutions", String.class, boolean.class); Method encodedSubstitution = clazz.getDeclaredMethod("encodedSubstitutions", String.class, boolean.class); return Stream.of( Arguments.of(substitution, null, null), Arguments.of(substitution, toObjectArray("raw", true), createExpectedParameters("raw", true)), Arguments.of(substitution, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(substitution, toObjectArray("{sub1}", false), createExpectedParameters("%7Bsub1%7D", false)), Arguments.of(encodedSubstitution, null, null), Arguments.of(encodedSubstitution, toObjectArray("raw", true), createExpectedParameters("raw", true)), Arguments.of(encodedSubstitution, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(encodedSubstitution, toObjectArray("{sub1}", false), createExpectedParameters("{sub1}", false)) ); }
class SwaggerMethodParserTests { interface OperationMethods { void noMethod(); @Get("test") void getMethod(); @Put("test") void putMethod(); @Head("test") void headMethod(); @Delete("test") void deleteMethod(); @Post("test") void postMethod(); @Patch("test") void patchMethod(); } @Test public void noHttpMethodAnnotation() throws NoSuchMethodException { Method noHttpMethodAnnotation = OperationMethods.class.getDeclaredMethod("noMethod"); assertThrows(MissingRequiredAnnotationException.class, () -> new SwaggerMethodParser(noHttpMethodAnnotation, "s: } @ParameterizedTest @MethodSource("httpMethodSupplier") public void httpMethod(Method method, HttpMethod expectedMethod, String expectedRelativePath, String expectedFullyQualifiedName) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedMethod, swaggerMethodParser.getHttpMethod()); assertEquals(expectedRelativePath, swaggerMethodParser.setPath(null)); assertEquals(expectedFullyQualifiedName, swaggerMethodParser.getFullyQualifiedMethodName()); } private static Stream<Arguments> httpMethodSupplier() throws NoSuchMethodException { Class<OperationMethods> clazz = OperationMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("getMethod"), HttpMethod.GET, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.getMethod"), Arguments.of(clazz.getDeclaredMethod("putMethod"), HttpMethod.PUT, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.putMethod"), Arguments.of(clazz.getDeclaredMethod("headMethod"), HttpMethod.HEAD, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.headMethod"), Arguments.of(clazz.getDeclaredMethod("deleteMethod"), HttpMethod.DELETE, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.deleteMethod"), Arguments.of(clazz.getDeclaredMethod("postMethod"), HttpMethod.POST, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.postMethod"), Arguments.of(clazz.getDeclaredMethod("patchMethod"), HttpMethod.PATCH, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.patchMethod") ); } interface WireTypesMethods { @Get("test") void noWireType(); @Get("test") @ReturnValueWireType(Base64Url.class) void base64Url(); @Get("test") @ReturnValueWireType(UnixTime.class) void unixTime(); @Get("test") @ReturnValueWireType(DateTimeRfc1123.class) void dateTimeRfc1123(); @Get("test") @ReturnValueWireType(Page.class) void page(); @Get("test") @ReturnValueWireType(Boolean.class) void unknownType(); } @ParameterizedTest @MethodSource("wireTypesSupplier") public void wireTypes(Method method, Class<?> expectedWireType) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedWireType, swaggerMethodParser.getReturnValueWireType()); } private static Stream<Arguments> wireTypesSupplier() throws NoSuchMethodException { Class<WireTypesMethods> clazz = WireTypesMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noWireType"), null), Arguments.of(clazz.getDeclaredMethod("base64Url"), Base64Url.class), Arguments.of(clazz.getDeclaredMethod("unixTime"), UnixTime.class), Arguments.of(clazz.getDeclaredMethod("dateTimeRfc1123"), DateTimeRfc1123.class), Arguments.of(clazz.getDeclaredMethod("page"), Page.class), Arguments.of(clazz.getDeclaredMethod("unknownType"), null) ); } interface HeaderMethods { @Get("test") void noHeaders(); @Get("test") @Headers({"", ":", "nameOnly:", ":valueOnly"}) void malformedHeaders(); @Get("test") @Headers({"name1:value1", " name2: value2", "name3 :value3 "}) void headers(); @Get("test") @Headers({"name:value1", "name:value2"}) void sameKeyTwiceLastWins(); } @ParameterizedTest @MethodSource("headersSupplier") public void headers(Method method, HttpHeaders expectedHeaders) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (HttpHeader header : swaggerMethodParser.setHeaders(null)) { assertEquals(expectedHeaders.getValue(header.getName()), header.getValue()); } } private static Stream<Arguments> headersSupplier() throws NoSuchMethodException { Class<HeaderMethods> clazz = HeaderMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noHeaders"), new HttpHeaders()), Arguments.of(clazz.getDeclaredMethod("malformedHeaders"), new HttpHeaders()), Arguments.of(clazz.getDeclaredMethod("headers"), new HttpHeaders() .put("name1", "value1").put("name2", "value2").put("name3", "value3")), Arguments.of(clazz.getDeclaredMethod("sameKeyTwiceLastWins"), new HttpHeaders().put("name", "value2")) ); } interface HostSubstitutionMethods { @Get("test") void noSubstitutions(String sub1); @Get("test") void substitution(@HostParam("sub1") String sub1); @Get("test") void encodingSubstitution(@HostParam(value = "sub1", encoded = false) String sub1); } @ParameterizedTest @MethodSource("hostSubstitutionSupplier") public void hostSubstitution(Method method, String rawHost, Object[] arguments, String expectedHost) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, rawHost); assertEquals(expectedHost, swaggerMethodParser.setHost(arguments)); } private static Stream<Arguments> hostSubstitutionSupplier() throws NoSuchMethodException { String sub1RawHost = "https: String sub2RawHost = "https: Class<HostSubstitutionMethods> clazz = HostSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodingSubstitution = clazz.getDeclaredMethod("encodingSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, sub1RawHost, toObjectArray("raw"), "{sub1}.host.com"), Arguments.of(noSubstitutions, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray("raw"), "raw.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray("{sub1}"), "{sub1}.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray((String) null), ".host.com"), Arguments.of(substitution, sub1RawHost, null, "{sub1}.host.com"), Arguments.of(substitution, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("raw"), "raw.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("{sub1}"), "%7Bsub1%7D.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray((String) null), ".host.com"), Arguments.of(substitution, sub1RawHost, null, "{sub1}.host.com"), Arguments.of(encodingSubstitution, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com") ); } @ParameterizedTest @MethodSource("schemeSubstitutionSupplier") public void schemeSubstitution(Method method, String rawHost, Object[] arguments, String expectedScheme) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, rawHost); assertEquals(expectedScheme, swaggerMethodParser.setScheme(arguments)); } private static Stream<Arguments> schemeSubstitutionSupplier() throws NoSuchMethodException { String sub1RawHost = "{sub1}: String sub2RawHost = "{sub2}: Class<HostSubstitutionMethods> clazz = HostSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodingSubstitution = clazz.getDeclaredMethod("encodingSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, sub1RawHost, toObjectArray("raw"), "{sub1}"), Arguments.of(noSubstitutions, sub2RawHost, toObjectArray("raw"), "{sub2}"), Arguments.of(substitution, sub1RawHost, toObjectArray("raw"), "raw"), Arguments.of(substitution, sub1RawHost, toObjectArray("{sub1}"), "{sub1}"), Arguments.of(substitution, sub1RawHost, toObjectArray((String) null), ""), Arguments.of(substitution, sub1RawHost, null, "{sub1}"), Arguments.of(substitution, sub2RawHost, toObjectArray("raw"), "{sub2}"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("raw"), "raw"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("{sub1}"), "%7Bsub1%7D"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray((String) null), ""), Arguments.of(substitution, sub1RawHost, null, "{sub1}"), Arguments.of(encodingSubstitution, sub2RawHost, toObjectArray("raw"), "{sub2}") ); } interface PathSubstitutionMethods { @Get("{sub1}") void noSubstitutions(String sub1); @Get("{sub1}") void substitution(@PathParam("sub1") String sub1); @Get("{sub1}") void encodedSubstitution(@PathParam(value = "sub1", encoded = true) String sub1); } @ParameterizedTest @MethodSource("pathSubstitutionSupplier") public void pathSubstitution(Method method, Object[] arguments, String expectedPath) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedPath, swaggerMethodParser.setPath(arguments)); } private static Stream<Arguments> pathSubstitutionSupplier() throws NoSuchMethodException { Class<PathSubstitutionMethods> clazz = PathSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodedSubstitution = clazz.getDeclaredMethod("encodedSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, toObjectArray("path"), "{sub1}"), Arguments.of(encodedSubstitution, toObjectArray("path"), "path"), Arguments.of(encodedSubstitution, toObjectArray("{sub1}"), "{sub1}"), Arguments.of(encodedSubstitution, toObjectArray((String) null), ""), Arguments.of(substitution, toObjectArray("path"), "path"), Arguments.of(substitution, toObjectArray("{sub1}"), "%7Bsub1%7D"), Arguments.of(substitution, toObjectArray((String) null), "") ); } interface QuerySubstitutionMethods { @Get("test") void substitutions(@QueryParam("sub1") String sub1, @QueryParam("sub2") boolean sub2); @Get("test") void encodedSubstitutions(@QueryParam(value = "sub1", encoded = true) String sub1, @QueryParam(value = "sub2", encoded = true) boolean sub2); } @ParameterizedTest @MethodSource("querySubstitutionSupplier") public void querySubstitution(Method method, Object[] arguments, Map<String, String> expectedParameters) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (EncodedParameter encodedParameter : swaggerMethodParser.setEncodedQueryParameters(arguments)) { assertEquals(expectedParameters.get(encodedParameter.getName()), encodedParameter.getEncodedValue()); } } interface HeaderSubstitutionMethods { @Get("test") void addHeaders(@HeaderParam("sub1") String sub1, @HeaderParam("sub2") boolean sub2); @Get("test") @Headers({ "sub1:sub1", "sub2:false" }) void overrideHeaders(@HeaderParam("sub1") String sub1, @HeaderParam("sub2") boolean sub2); @Get("test") void headerMap(@HeaderParam("x-ms-meta-") Map<String, String> headers); } @ParameterizedTest @MethodSource("headerSubstitutionSupplier") public void headerSubstitution(Method method, Object[] arguments, Map<String, String> expectedHeaders) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (HttpHeader header : swaggerMethodParser.setHeaders(arguments)) { assertEquals(expectedHeaders.get(header.getName()), header.getValue()); } } private static Stream<Arguments> headerSubstitutionSupplier() throws NoSuchMethodException { Class<HeaderSubstitutionMethods> clazz = HeaderSubstitutionMethods.class; Method addHeaders = clazz.getDeclaredMethod("addHeaders", String.class, boolean.class); Method overrideHeaders = clazz.getDeclaredMethod("overrideHeaders", String.class, boolean.class); Method headerMap = clazz.getDeclaredMethod("headerMap", Map.class); Map<String, String> simpleHeaderMap = Collections.singletonMap("key", "value"); Map<String, String> expectedSimpleHeadersMap = Collections.singletonMap("x-ms-meta-key", "value"); Map<String, String> complexHeaderMap = new HttpHeaders().put("key1", null).put("key2", "value2").toMap(); Map<String, String> expectedComplexHeaderMap = Collections.singletonMap("x-ms-meta-key2", "value2"); return Stream.of( Arguments.of(addHeaders, null, null), Arguments.of(addHeaders, toObjectArray("header", true), createExpectedParameters("header", true)), Arguments.of(addHeaders, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(addHeaders, toObjectArray("{sub1}", false), createExpectedParameters("{sub1}", false)), Arguments.of(overrideHeaders, null, createExpectedParameters("sub1", false)), Arguments.of(overrideHeaders, toObjectArray(null, true), createExpectedParameters("sub1", true)), Arguments.of(overrideHeaders, toObjectArray("header", false), createExpectedParameters("header", false)), Arguments.of(overrideHeaders, toObjectArray("{sub1}", true), createExpectedParameters("{sub1}", true)), Arguments.of(headerMap, null, null), Arguments.of(headerMap, toObjectArray(simpleHeaderMap), expectedSimpleHeadersMap), Arguments.of(headerMap, toObjectArray(complexHeaderMap), expectedComplexHeaderMap) ); } interface BodySubstitutionMethods { @Get("test") void applicationJsonBody(@BodyParam(ContentType.APPLICATION_JSON) String jsonBody); @Get("test") void formBody(@FormParam("name") String name, @FormParam("age") Integer age, @FormParam("dob") OffsetDateTime dob, @FormParam("favoriteColors") List<String> favoriteColors); @Get("test") void encodedFormBody(@FormParam(value = "name", encoded = true) String name, @FormParam("age") Integer age, @FormParam("dob") OffsetDateTime dob, @FormParam("favoriteColors") List<String> favoriteColors); @Get("test") void encodedFormKey(@FormParam(value = "x:ms:value") String value); @Get("test") void encodedFormKey2(@FormParam(value = "x:ms:value", encoded = true) String value); } @ParameterizedTest @MethodSource("bodySubstitutionSupplier") public void bodySubstitution(Method method, Object[] arguments, String expectedBodyContentType, Object expectedBody) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(void.class, swaggerMethodParser.getReturnType()); assertEquals(String.class, swaggerMethodParser.getBodyJavaType()); assertEquals(expectedBodyContentType, swaggerMethodParser.getBodyContentType()); assertEquals(expectedBody, swaggerMethodParser.setBody(arguments)); } private static Stream<Arguments> bodySubstitutionSupplier() throws NoSuchMethodException { Class<BodySubstitutionMethods> clazz = BodySubstitutionMethods.class; Method jsonBody = clazz.getDeclaredMethod("applicationJsonBody", String.class); Method formBody = clazz.getDeclaredMethod("formBody", String.class, Integer.class, OffsetDateTime.class, List.class); Method encodedFormBody = clazz.getDeclaredMethod("encodedFormBody", String.class, Integer.class, OffsetDateTime.class, List.class); Method encodedFormKey = clazz.getDeclaredMethod("encodedFormKey", String.class); Method encodedFormKey2 = clazz.getDeclaredMethod("encodedFormKey2", String.class); OffsetDateTime dob = OffsetDateTime.of(1980, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); List<String> favoriteColors = Arrays.asList("blue", "green"); List<String> badFavoriteColors = Arrays.asList(null, "green"); return Stream.of( Arguments.of(jsonBody, null, ContentType.APPLICATION_JSON, null), Arguments.of(jsonBody, toObjectArray("{name:John Doe,age:40,dob:01-01-1980}"), ContentType.APPLICATION_JSON, "{name:John Doe,age:40,dob:01-01-1980}"), Arguments.of(formBody, null, APPLICATION_X_WWW_FORM_URLENCODED, null), Arguments.of(formBody, toObjectArray("John Doe", null, dob, null), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&dob=1980-01-01T00%3A00%3A00Z"), Arguments.of(formBody, toObjectArray("John Doe", 40, null, favoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&age=40&favoriteColors=blue&favoriteColors=green"), Arguments.of(formBody, toObjectArray("John Doe", 40, null, badFavoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&age=40&favoriteColors=green"), Arguments.of(encodedFormBody, null, APPLICATION_X_WWW_FORM_URLENCODED, null), Arguments.of(encodedFormBody, toObjectArray("John Doe", null, dob, null), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&dob=1980-01-01T00%3A00%3A00Z"), Arguments.of(encodedFormBody, toObjectArray("John Doe", 40, null, favoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&age=40&favoriteColors=blue&favoriteColors=green"), Arguments.of(encodedFormBody, toObjectArray("John Doe", 40, null, badFavoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&age=40&favoriteColors=green"), Arguments.of(encodedFormKey, toObjectArray("value"), APPLICATION_X_WWW_FORM_URLENCODED, "x%3Ams%3Avalue=value"), Arguments.of(encodedFormKey2, toObjectArray("value"), APPLICATION_X_WWW_FORM_URLENCODED, "x%3Ams%3Avalue=value") ); } @ParameterizedTest @MethodSource("setContextSupplier") public void setContext(SwaggerMethodParser swaggerMethodParser, Object[] arguments, Context expectedContext) { assertEquals(expectedContext, swaggerMethodParser.setContext(arguments)); } private static Stream<Arguments> setContextSupplier() throws NoSuchMethodException { Method method = OperationMethods.class.getDeclaredMethod("getMethod"); SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: Context context = new Context("key", "value"); return Stream.of( Arguments.of(swaggerMethodParser, null, Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray(), Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray("string"), Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray(context), context) ); } interface ExpectedStatusCodeMethods { @Get("test") void noExpectedStatusCodes(); @Get("test") @ExpectedResponses({ 200 }) void only200IsExpected(); @Get("test") @ExpectedResponses({ 429, 503 }) void retryAfterExpected(); } @ParameterizedTest @MethodSource("expectedStatusCodeSupplier") public void expectedStatusCodeSupplier(Method method, int statusCode, int[] expectedStatusCodes, boolean matchesExpected) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertArrayEquals(expectedStatusCodes, swaggerMethodParser.getExpectedStatusCodes()); assertEquals(matchesExpected, swaggerMethodParser.isExpectedResponseStatusCode(statusCode)); } private static Stream<Arguments> expectedStatusCodeSupplier() throws NoSuchMethodException { Class<ExpectedStatusCodeMethods> clazz = ExpectedStatusCodeMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 200, null, true), Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 201, null, true), Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 400, null, false), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 200, new int[] {200}, true), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 201, new int[] {200}, false), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 400, new int[] {200}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 200, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 201, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 400, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 429, new int[] {429, 503}, true), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 503, new int[] {429, 503}, true) ); } interface UnexpectedStatusCodeMethods { @Get("test") void noUnexpectedStatusCodes(); @Get("test") @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = {400, 404}) void notFoundStatusCode(); @Get("test") @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = {400, 404}) @UnexpectedResponseExceptionType(value = ResourceModifiedException.class) void customDefault(); } @ParameterizedTest @MethodSource("unexpectedStatusCodeSupplier") public void unexpectedStatusCode(Method method, int statusCode, Class<?> expectedExceptionType) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedExceptionType, swaggerMethodParser.getUnexpectedException(statusCode).getExceptionType()); } private static Stream<Arguments> unexpectedStatusCodeSupplier() throws NoSuchMethodException { Class<UnexpectedStatusCodeMethods> clazz = UnexpectedStatusCodeMethods.class; Method noUnexpectedStatusCodes = clazz.getDeclaredMethod("noUnexpectedStatusCodes"); Method notFoundStatusCode = clazz.getDeclaredMethod("notFoundStatusCode"); Method customDefault = clazz.getDeclaredMethod("customDefault"); return Stream.of( Arguments.of(noUnexpectedStatusCodes, 500, HttpResponseException.class), Arguments.of(noUnexpectedStatusCodes, 400, HttpResponseException.class), Arguments.of(noUnexpectedStatusCodes, 404, HttpResponseException.class), Arguments.of(notFoundStatusCode, 500, HttpResponseException.class), Arguments.of(notFoundStatusCode, 400, ResourceNotFoundException.class), Arguments.of(notFoundStatusCode, 404, ResourceNotFoundException.class), Arguments.of(customDefault, 500, ResourceModifiedException.class), Arguments.of(customDefault, 400, ResourceNotFoundException.class), Arguments.of(customDefault, 404, ResourceNotFoundException.class) ); } private static Object[] toObjectArray(Object... objects) { return objects; } private static Map<String, String> createExpectedParameters(String sub1Value, boolean sub2Value) { Map<String, String> expectedParameters = new HashMap<>(); if (sub1Value != null) { expectedParameters.put("sub1", sub1Value); } expectedParameters.put("sub2", String.valueOf(sub2Value)); return expectedParameters; } }
class SwaggerMethodParserTests { interface OperationMethods { void noMethod(); @Get("test") void getMethod(); @Put("test") void putMethod(); @Head("test") void headMethod(); @Delete("test") void deleteMethod(); @Post("test") void postMethod(); @Patch("test") void patchMethod(); } @Test public void noHttpMethodAnnotation() throws NoSuchMethodException { Method noHttpMethodAnnotation = OperationMethods.class.getDeclaredMethod("noMethod"); assertThrows(MissingRequiredAnnotationException.class, () -> new SwaggerMethodParser(noHttpMethodAnnotation, "s: } @ParameterizedTest @MethodSource("httpMethodSupplier") public void httpMethod(Method method, HttpMethod expectedMethod, String expectedRelativePath, String expectedFullyQualifiedName) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedMethod, swaggerMethodParser.getHttpMethod()); assertEquals(expectedRelativePath, swaggerMethodParser.setPath(null)); assertEquals(expectedFullyQualifiedName, swaggerMethodParser.getFullyQualifiedMethodName()); } private static Stream<Arguments> httpMethodSupplier() throws NoSuchMethodException { Class<OperationMethods> clazz = OperationMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("getMethod"), HttpMethod.GET, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.getMethod"), Arguments.of(clazz.getDeclaredMethod("putMethod"), HttpMethod.PUT, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.putMethod"), Arguments.of(clazz.getDeclaredMethod("headMethod"), HttpMethod.HEAD, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.headMethod"), Arguments.of(clazz.getDeclaredMethod("deleteMethod"), HttpMethod.DELETE, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.deleteMethod"), Arguments.of(clazz.getDeclaredMethod("postMethod"), HttpMethod.POST, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.postMethod"), Arguments.of(clazz.getDeclaredMethod("patchMethod"), HttpMethod.PATCH, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.patchMethod") ); } interface WireTypesMethods { @Get("test") void noWireType(); @Get("test") @ReturnValueWireType(Base64Url.class) void base64Url(); @Get("test") @ReturnValueWireType(UnixTime.class) void unixTime(); @Get("test") @ReturnValueWireType(DateTimeRfc1123.class) void dateTimeRfc1123(); @Get("test") @ReturnValueWireType(Page.class) void page(); @Get("test") @ReturnValueWireType(Boolean.class) void unknownType(); } @ParameterizedTest @MethodSource("wireTypesSupplier") public void wireTypes(Method method, Class<?> expectedWireType) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedWireType, swaggerMethodParser.getReturnValueWireType()); } private static Stream<Arguments> wireTypesSupplier() throws NoSuchMethodException { Class<WireTypesMethods> clazz = WireTypesMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noWireType"), null), Arguments.of(clazz.getDeclaredMethod("base64Url"), Base64Url.class), Arguments.of(clazz.getDeclaredMethod("unixTime"), UnixTime.class), Arguments.of(clazz.getDeclaredMethod("dateTimeRfc1123"), DateTimeRfc1123.class), Arguments.of(clazz.getDeclaredMethod("page"), Page.class), Arguments.of(clazz.getDeclaredMethod("unknownType"), null) ); } interface HeaderMethods { @Get("test") void noHeaders(); @Get("test") @Headers({"", ":", "nameOnly:", ":valueOnly"}) void malformedHeaders(); @Get("test") @Headers({"name1:value1", " name2: value2", "name3 :value3 "}) void headers(); @Get("test") @Headers({"name:value1", "name:value2"}) void sameKeyTwiceLastWins(); } @ParameterizedTest @MethodSource("headersSupplier") public void headers(Method method, HttpHeaders expectedHeaders) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (HttpHeader header : swaggerMethodParser.setHeaders(null)) { assertEquals(expectedHeaders.getValue(header.getName()), header.getValue()); } } private static Stream<Arguments> headersSupplier() throws NoSuchMethodException { Class<HeaderMethods> clazz = HeaderMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noHeaders"), new HttpHeaders()), Arguments.of(clazz.getDeclaredMethod("malformedHeaders"), new HttpHeaders()), Arguments.of(clazz.getDeclaredMethod("headers"), new HttpHeaders() .put("name1", "value1").put("name2", "value2").put("name3", "value3")), Arguments.of(clazz.getDeclaredMethod("sameKeyTwiceLastWins"), new HttpHeaders().put("name", "value2")) ); } interface HostSubstitutionMethods { @Get("test") void noSubstitutions(String sub1); @Get("test") void substitution(@HostParam("sub1") String sub1); @Get("test") void encodingSubstitution(@HostParam(value = "sub1", encoded = false) String sub1); } @ParameterizedTest @MethodSource("hostSubstitutionSupplier") public void hostSubstitution(Method method, String rawHost, Object[] arguments, String expectedHost) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, rawHost); assertEquals(expectedHost, swaggerMethodParser.setHost(arguments)); } private static Stream<Arguments> hostSubstitutionSupplier() throws NoSuchMethodException { String sub1RawHost = "https: String sub2RawHost = "https: Class<HostSubstitutionMethods> clazz = HostSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodingSubstitution = clazz.getDeclaredMethod("encodingSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, sub1RawHost, toObjectArray("raw"), "{sub1}.host.com"), Arguments.of(noSubstitutions, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray("raw"), "raw.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray("{sub1}"), "{sub1}.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray((String) null), ".host.com"), Arguments.of(substitution, sub1RawHost, null, "{sub1}.host.com"), Arguments.of(substitution, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("raw"), "raw.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("{sub1}"), "%7Bsub1%7D.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray((String) null), ".host.com"), Arguments.of(substitution, sub1RawHost, null, "{sub1}.host.com"), Arguments.of(encodingSubstitution, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com") ); } @ParameterizedTest @MethodSource("schemeSubstitutionSupplier") public void schemeSubstitution(Method method, String rawHost, Object[] arguments, String expectedScheme) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, rawHost); assertEquals(expectedScheme, swaggerMethodParser.setScheme(arguments)); } private static Stream<Arguments> schemeSubstitutionSupplier() throws NoSuchMethodException { String sub1RawHost = "{sub1}: String sub2RawHost = "{sub2}: Class<HostSubstitutionMethods> clazz = HostSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodingSubstitution = clazz.getDeclaredMethod("encodingSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, sub1RawHost, toObjectArray("raw"), "{sub1}"), Arguments.of(noSubstitutions, sub2RawHost, toObjectArray("raw"), "{sub2}"), Arguments.of(substitution, sub1RawHost, toObjectArray("raw"), "raw"), Arguments.of(substitution, sub1RawHost, toObjectArray("{sub1}"), "{sub1}"), Arguments.of(substitution, sub1RawHost, toObjectArray((String) null), ""), Arguments.of(substitution, sub1RawHost, null, "{sub1}"), Arguments.of(substitution, sub2RawHost, toObjectArray("raw"), "{sub2}"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("raw"), "raw"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("{sub1}"), "%7Bsub1%7D"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray((String) null), ""), Arguments.of(substitution, sub1RawHost, null, "{sub1}"), Arguments.of(encodingSubstitution, sub2RawHost, toObjectArray("raw"), "{sub2}") ); } interface PathSubstitutionMethods { @Get("{sub1}") void noSubstitutions(String sub1); @Get("{sub1}") void substitution(@PathParam("sub1") String sub1); @Get("{sub1}") void encodedSubstitution(@PathParam(value = "sub1", encoded = true) String sub1); } @ParameterizedTest @MethodSource("pathSubstitutionSupplier") public void pathSubstitution(Method method, Object[] arguments, String expectedPath) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedPath, swaggerMethodParser.setPath(arguments)); } private static Stream<Arguments> pathSubstitutionSupplier() throws NoSuchMethodException { Class<PathSubstitutionMethods> clazz = PathSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodedSubstitution = clazz.getDeclaredMethod("encodedSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, toObjectArray("path"), "{sub1}"), Arguments.of(encodedSubstitution, toObjectArray("path"), "path"), Arguments.of(encodedSubstitution, toObjectArray("{sub1}"), "{sub1}"), Arguments.of(encodedSubstitution, toObjectArray((String) null), ""), Arguments.of(substitution, toObjectArray("path"), "path"), Arguments.of(substitution, toObjectArray("{sub1}"), "%7Bsub1%7D"), Arguments.of(substitution, toObjectArray((String) null), "") ); } interface QuerySubstitutionMethods { @Get("test") void substitutions(@QueryParam("sub1") String sub1, @QueryParam("sub2") boolean sub2); @Get("test") void encodedSubstitutions(@QueryParam(value = "sub1", encoded = true) String sub1, @QueryParam(value = "sub2", encoded = true) boolean sub2); } @ParameterizedTest @MethodSource("querySubstitutionSupplier") public void querySubstitution(Method method, Object[] arguments, Map<String, String> expectedParameters) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (EncodedParameter encodedParameter : swaggerMethodParser.setEncodedQueryParameters(arguments)) { assertEquals(expectedParameters.get(encodedParameter.getName()), encodedParameter.getEncodedValue()); } } interface HeaderSubstitutionMethods { @Get("test") void addHeaders(@HeaderParam("sub1") String sub1, @HeaderParam("sub2") boolean sub2); @Get("test") @Headers({ "sub1:sub1", "sub2:false" }) void overrideHeaders(@HeaderParam("sub1") String sub1, @HeaderParam("sub2") boolean sub2); @Get("test") void headerMap(@HeaderParam("x-ms-meta-") Map<String, String> headers); } @ParameterizedTest @MethodSource("headerSubstitutionSupplier") public void headerSubstitution(Method method, Object[] arguments, Map<String, String> expectedHeaders) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (HttpHeader header : swaggerMethodParser.setHeaders(arguments)) { assertEquals(expectedHeaders.get(header.getName()), header.getValue()); } } private static Stream<Arguments> headerSubstitutionSupplier() throws NoSuchMethodException { Class<HeaderSubstitutionMethods> clazz = HeaderSubstitutionMethods.class; Method addHeaders = clazz.getDeclaredMethod("addHeaders", String.class, boolean.class); Method overrideHeaders = clazz.getDeclaredMethod("overrideHeaders", String.class, boolean.class); Method headerMap = clazz.getDeclaredMethod("headerMap", Map.class); Map<String, String> simpleHeaderMap = Collections.singletonMap("key", "value"); Map<String, String> expectedSimpleHeadersMap = Collections.singletonMap("x-ms-meta-key", "value"); Map<String, String> complexHeaderMap = new HttpHeaders().put("key1", null).put("key2", "value2").toMap(); Map<String, String> expectedComplexHeaderMap = Collections.singletonMap("x-ms-meta-key2", "value2"); return Stream.of( Arguments.of(addHeaders, null, null), Arguments.of(addHeaders, toObjectArray("header", true), createExpectedParameters("header", true)), Arguments.of(addHeaders, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(addHeaders, toObjectArray("{sub1}", false), createExpectedParameters("{sub1}", false)), Arguments.of(overrideHeaders, null, createExpectedParameters("sub1", false)), Arguments.of(overrideHeaders, toObjectArray(null, true), createExpectedParameters("sub1", true)), Arguments.of(overrideHeaders, toObjectArray("header", false), createExpectedParameters("header", false)), Arguments.of(overrideHeaders, toObjectArray("{sub1}", true), createExpectedParameters("{sub1}", true)), Arguments.of(headerMap, null, null), Arguments.of(headerMap, toObjectArray(simpleHeaderMap), expectedSimpleHeadersMap), Arguments.of(headerMap, toObjectArray(complexHeaderMap), expectedComplexHeaderMap) ); } interface BodySubstitutionMethods { @Get("test") void applicationJsonBody(@BodyParam(ContentType.APPLICATION_JSON) String jsonBody); @Get("test") void formBody(@FormParam("name") String name, @FormParam("age") Integer age, @FormParam("dob") OffsetDateTime dob, @FormParam("favoriteColors") List<String> favoriteColors); @Get("test") void encodedFormBody(@FormParam(value = "name", encoded = true) String name, @FormParam("age") Integer age, @FormParam("dob") OffsetDateTime dob, @FormParam("favoriteColors") List<String> favoriteColors); @Get("test") void encodedFormKey(@FormParam(value = "x:ms:value") String value); @Get("test") void encodedFormKey2(@FormParam(value = "x:ms:value", encoded = true) String value); } @ParameterizedTest @MethodSource("bodySubstitutionSupplier") public void bodySubstitution(Method method, Object[] arguments, String expectedBodyContentType, Object expectedBody) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(void.class, swaggerMethodParser.getReturnType()); assertEquals(String.class, swaggerMethodParser.getBodyJavaType()); assertEquals(expectedBodyContentType, swaggerMethodParser.getBodyContentType()); assertEquals(expectedBody, swaggerMethodParser.setBody(arguments)); } private static Stream<Arguments> bodySubstitutionSupplier() throws NoSuchMethodException { Class<BodySubstitutionMethods> clazz = BodySubstitutionMethods.class; Method jsonBody = clazz.getDeclaredMethod("applicationJsonBody", String.class); Method formBody = clazz.getDeclaredMethod("formBody", String.class, Integer.class, OffsetDateTime.class, List.class); Method encodedFormBody = clazz.getDeclaredMethod("encodedFormBody", String.class, Integer.class, OffsetDateTime.class, List.class); Method encodedFormKey = clazz.getDeclaredMethod("encodedFormKey", String.class); Method encodedFormKey2 = clazz.getDeclaredMethod("encodedFormKey2", String.class); OffsetDateTime dob = OffsetDateTime.of(1980, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); List<String> favoriteColors = Arrays.asList("blue", "green"); List<String> badFavoriteColors = Arrays.asList(null, "green"); return Stream.of( Arguments.of(jsonBody, null, ContentType.APPLICATION_JSON, null), Arguments.of(jsonBody, toObjectArray("{name:John Doe,age:40,dob:01-01-1980}"), ContentType.APPLICATION_JSON, "{name:John Doe,age:40,dob:01-01-1980}"), Arguments.of(formBody, null, APPLICATION_X_WWW_FORM_URLENCODED, null), Arguments.of(formBody, toObjectArray("John Doe", null, dob, null), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&dob=1980-01-01T00%3A00%3A00Z"), Arguments.of(formBody, toObjectArray("John Doe", 40, null, favoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&age=40&favoriteColors=blue&favoriteColors=green"), Arguments.of(formBody, toObjectArray("John Doe", 40, null, badFavoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&age=40&favoriteColors=green"), Arguments.of(encodedFormBody, null, APPLICATION_X_WWW_FORM_URLENCODED, null), Arguments.of(encodedFormBody, toObjectArray("John Doe", null, dob, null), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&dob=1980-01-01T00%3A00%3A00Z"), Arguments.of(encodedFormBody, toObjectArray("John Doe", 40, null, favoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&age=40&favoriteColors=blue&favoriteColors=green"), Arguments.of(encodedFormBody, toObjectArray("John Doe", 40, null, badFavoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&age=40&favoriteColors=green"), Arguments.of(encodedFormKey, toObjectArray("value"), APPLICATION_X_WWW_FORM_URLENCODED, "x%3Ams%3Avalue=value"), Arguments.of(encodedFormKey2, toObjectArray("value"), APPLICATION_X_WWW_FORM_URLENCODED, "x%3Ams%3Avalue=value") ); } @ParameterizedTest @MethodSource("setContextSupplier") public void setContext(SwaggerMethodParser swaggerMethodParser, Object[] arguments, Context expectedContext) { assertEquals(expectedContext, swaggerMethodParser.setContext(arguments)); } private static Stream<Arguments> setContextSupplier() throws NoSuchMethodException { Method method = OperationMethods.class.getDeclaredMethod("getMethod"); SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: Context context = new Context("key", "value"); return Stream.of( Arguments.of(swaggerMethodParser, null, Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray(), Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray("string"), Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray(context), context) ); } interface ExpectedStatusCodeMethods { @Get("test") void noExpectedStatusCodes(); @Get("test") @ExpectedResponses({ 200 }) void only200IsExpected(); @Get("test") @ExpectedResponses({ 429, 503 }) void retryAfterExpected(); } @ParameterizedTest @MethodSource("expectedStatusCodeSupplier") public void expectedStatusCodeSupplier(Method method, int statusCode, int[] expectedStatusCodes, boolean matchesExpected) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertArrayEquals(expectedStatusCodes, swaggerMethodParser.getExpectedStatusCodes()); assertEquals(matchesExpected, swaggerMethodParser.isExpectedResponseStatusCode(statusCode)); } private static Stream<Arguments> expectedStatusCodeSupplier() throws NoSuchMethodException { Class<ExpectedStatusCodeMethods> clazz = ExpectedStatusCodeMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 200, null, true), Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 201, null, true), Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 400, null, false), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 200, new int[] {200}, true), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 201, new int[] {200}, false), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 400, new int[] {200}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 200, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 201, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 400, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 429, new int[] {429, 503}, true), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 503, new int[] {429, 503}, true) ); } interface UnexpectedStatusCodeMethods { @Get("test") void noUnexpectedStatusCodes(); @Get("test") @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = {400, 404}) void notFoundStatusCode(); @Get("test") @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = {400, 404}) @UnexpectedResponseExceptionType(value = ResourceModifiedException.class) void customDefault(); } @ParameterizedTest @MethodSource("unexpectedStatusCodeSupplier") public void unexpectedStatusCode(Method method, int statusCode, Class<?> expectedExceptionType) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedExceptionType, swaggerMethodParser.getUnexpectedException(statusCode).getExceptionType()); } private static Stream<Arguments> unexpectedStatusCodeSupplier() throws NoSuchMethodException { Class<UnexpectedStatusCodeMethods> clazz = UnexpectedStatusCodeMethods.class; Method noUnexpectedStatusCodes = clazz.getDeclaredMethod("noUnexpectedStatusCodes"); Method notFoundStatusCode = clazz.getDeclaredMethod("notFoundStatusCode"); Method customDefault = clazz.getDeclaredMethod("customDefault"); return Stream.of( Arguments.of(noUnexpectedStatusCodes, 500, HttpResponseException.class), Arguments.of(noUnexpectedStatusCodes, 400, HttpResponseException.class), Arguments.of(noUnexpectedStatusCodes, 404, HttpResponseException.class), Arguments.of(notFoundStatusCode, 500, HttpResponseException.class), Arguments.of(notFoundStatusCode, 400, ResourceNotFoundException.class), Arguments.of(notFoundStatusCode, 404, ResourceNotFoundException.class), Arguments.of(customDefault, 500, ResourceModifiedException.class), Arguments.of(customDefault, 400, ResourceNotFoundException.class), Arguments.of(customDefault, 404, ResourceNotFoundException.class) ); } private static Object[] toObjectArray(Object... objects) { return objects; } private static Map<String, String> createExpectedParameters(String sub1Value, boolean sub2Value) { Map<String, String> expectedParameters = new HashMap<>(); if (sub1Value != null) { expectedParameters.put("sub1", sub1Value); } expectedParameters.put("sub2", String.valueOf(sub2Value)); return expectedParameters; } }
PercentEscaper is package private with public static instance available, shouldn't see these inputs, can add tests though.
private static Stream<Arguments> escapeSupplier() { PercentEscaper defaultEscaper = new PercentEscaper(null, false); return Stream.of( Arguments.arguments(defaultEscaper, "$", "%24"), Arguments.arguments(defaultEscaper, "¢", "%C2%A2"), Arguments.arguments(defaultEscaper, "ह", "%E0%A4%B9"), Arguments.arguments(defaultEscaper, "€", "%E2%82%AC"), Arguments.arguments(defaultEscaper, "한", "%ED%95%9C"), Arguments.arguments(defaultEscaper, "円", "%E5%86%86"), Arguments.arguments(defaultEscaper, "\uD800\uDF48", "%F0%90%8D%88"), Arguments.arguments(defaultEscaper, "日本語", "%E6%97%A5%E6%9C%AC%E8%AA%9E"), Arguments.arguments(defaultEscaper, " ", "%20"), Arguments.arguments(new PercentEscaper(null, true), " ", "+"), Arguments.arguments(new PercentEscaper("$", false), "$", "$") ); }
Arguments.arguments(new PercentEscaper("$", false), "$", "$")
private static Stream<Arguments> escapeSupplier() { PercentEscaper defaultEscaper = new PercentEscaper(null, false); return Stream.of( Arguments.arguments(defaultEscaper, null, null), Arguments.arguments(defaultEscaper, "", ""), Arguments.arguments(defaultEscaper, "$", "%24"), Arguments.arguments(defaultEscaper, "¢", "%C2%A2"), Arguments.arguments(defaultEscaper, "ह", "%E0%A4%B9"), Arguments.arguments(defaultEscaper, "€", "%E2%82%AC"), Arguments.arguments(defaultEscaper, "한", "%ED%95%9C"), Arguments.arguments(defaultEscaper, "円", "%E5%86%86"), Arguments.arguments(defaultEscaper, "\uD800\uDF48", "%F0%90%8D%88"), Arguments.arguments(defaultEscaper, "日本語", "%E6%97%A5%E6%9C%AC%E8%AA%9E"), Arguments.arguments(defaultEscaper, " ", "%20"), Arguments.arguments(new PercentEscaper(null, true), " ", "+"), Arguments.arguments(new PercentEscaper("$", false), "$", "$"), Arguments.arguments(new PercentEscaper("ह", false), "ह", "ह") ); }
class PercentEscaperTests { @ParameterizedTest @MethodSource("escapeSupplier") public void escape(PercentEscaper escaper, String original, String expected) { assertEquals(expected, escaper.escape(original)); } }
class PercentEscaperTests { /** * Tests that using {@code ' '} as a safe character and treating {@code ' '} as {@code '+'} is an illegal * configuration. */ @Test public void cannotUseSpaceAsPlusAndSpaceAsSafeCharacter() { assertThrows(IllegalArgumentException.class, () -> new PercentEscaper(" ", true)); } /** * Tests that valid inputs are escaped correctly. */ @ParameterizedTest @MethodSource("escapeSupplier") public void escape(PercentEscaper escaper, String original, String expected) { assertEquals(expected, escaper.escape(original)); } @ParameterizedTest @MethodSource("invalidEscapeSupplier") public void invalidEscape(String original) { assertThrows(IllegalStateException.class, () -> new PercentEscaper(null, false).escape(original)); } private static Stream<Arguments> invalidEscapeSupplier() { return Stream.of( Arguments.arguments("abcd\uD800"), Arguments.arguments("abcd\uDF48\uD800"), Arguments.arguments("\uD800abcd") ); } }
I believe hex characters should be invariant on casing, I just copied the hex array creation from another of our classes and it used uppercase.
private static Stream<Arguments> querySubstitutionSupplier() throws NoSuchMethodException { Class<QuerySubstitutionMethods> clazz = QuerySubstitutionMethods.class; Method substitution = clazz.getDeclaredMethod("substitutions", String.class, boolean.class); Method encodedSubstitution = clazz.getDeclaredMethod("encodedSubstitutions", String.class, boolean.class); return Stream.of( Arguments.of(substitution, null, null), Arguments.of(substitution, toObjectArray("raw", true), createExpectedParameters("raw", true)), Arguments.of(substitution, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(substitution, toObjectArray("{sub1}", false), createExpectedParameters("%7Bsub1%7D", false)), Arguments.of(encodedSubstitution, null, null), Arguments.of(encodedSubstitution, toObjectArray("raw", true), createExpectedParameters("raw", true)), Arguments.of(encodedSubstitution, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(encodedSubstitution, toObjectArray("{sub1}", false), createExpectedParameters("{sub1}", false)) ); }
Arguments.of(substitution, toObjectArray("{sub1}", false), createExpectedParameters("%7Bsub1%7D", false)),
private static Stream<Arguments> querySubstitutionSupplier() throws NoSuchMethodException { Class<QuerySubstitutionMethods> clazz = QuerySubstitutionMethods.class; Method substitution = clazz.getDeclaredMethod("substitutions", String.class, boolean.class); Method encodedSubstitution = clazz.getDeclaredMethod("encodedSubstitutions", String.class, boolean.class); return Stream.of( Arguments.of(substitution, null, null), Arguments.of(substitution, toObjectArray("raw", true), createExpectedParameters("raw", true)), Arguments.of(substitution, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(substitution, toObjectArray("{sub1}", false), createExpectedParameters("%7Bsub1%7D", false)), Arguments.of(encodedSubstitution, null, null), Arguments.of(encodedSubstitution, toObjectArray("raw", true), createExpectedParameters("raw", true)), Arguments.of(encodedSubstitution, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(encodedSubstitution, toObjectArray("{sub1}", false), createExpectedParameters("{sub1}", false)) ); }
class SwaggerMethodParserTests { interface OperationMethods { void noMethod(); @Get("test") void getMethod(); @Put("test") void putMethod(); @Head("test") void headMethod(); @Delete("test") void deleteMethod(); @Post("test") void postMethod(); @Patch("test") void patchMethod(); } @Test public void noHttpMethodAnnotation() throws NoSuchMethodException { Method noHttpMethodAnnotation = OperationMethods.class.getDeclaredMethod("noMethod"); assertThrows(MissingRequiredAnnotationException.class, () -> new SwaggerMethodParser(noHttpMethodAnnotation, "s: } @ParameterizedTest @MethodSource("httpMethodSupplier") public void httpMethod(Method method, HttpMethod expectedMethod, String expectedRelativePath, String expectedFullyQualifiedName) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedMethod, swaggerMethodParser.getHttpMethod()); assertEquals(expectedRelativePath, swaggerMethodParser.setPath(null)); assertEquals(expectedFullyQualifiedName, swaggerMethodParser.getFullyQualifiedMethodName()); } private static Stream<Arguments> httpMethodSupplier() throws NoSuchMethodException { Class<OperationMethods> clazz = OperationMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("getMethod"), HttpMethod.GET, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.getMethod"), Arguments.of(clazz.getDeclaredMethod("putMethod"), HttpMethod.PUT, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.putMethod"), Arguments.of(clazz.getDeclaredMethod("headMethod"), HttpMethod.HEAD, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.headMethod"), Arguments.of(clazz.getDeclaredMethod("deleteMethod"), HttpMethod.DELETE, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.deleteMethod"), Arguments.of(clazz.getDeclaredMethod("postMethod"), HttpMethod.POST, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.postMethod"), Arguments.of(clazz.getDeclaredMethod("patchMethod"), HttpMethod.PATCH, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.patchMethod") ); } interface WireTypesMethods { @Get("test") void noWireType(); @Get("test") @ReturnValueWireType(Base64Url.class) void base64Url(); @Get("test") @ReturnValueWireType(UnixTime.class) void unixTime(); @Get("test") @ReturnValueWireType(DateTimeRfc1123.class) void dateTimeRfc1123(); @Get("test") @ReturnValueWireType(Page.class) void page(); @Get("test") @ReturnValueWireType(Boolean.class) void unknownType(); } @ParameterizedTest @MethodSource("wireTypesSupplier") public void wireTypes(Method method, Class<?> expectedWireType) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedWireType, swaggerMethodParser.getReturnValueWireType()); } private static Stream<Arguments> wireTypesSupplier() throws NoSuchMethodException { Class<WireTypesMethods> clazz = WireTypesMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noWireType"), null), Arguments.of(clazz.getDeclaredMethod("base64Url"), Base64Url.class), Arguments.of(clazz.getDeclaredMethod("unixTime"), UnixTime.class), Arguments.of(clazz.getDeclaredMethod("dateTimeRfc1123"), DateTimeRfc1123.class), Arguments.of(clazz.getDeclaredMethod("page"), Page.class), Arguments.of(clazz.getDeclaredMethod("unknownType"), null) ); } interface HeaderMethods { @Get("test") void noHeaders(); @Get("test") @Headers({"", ":", "nameOnly:", ":valueOnly"}) void malformedHeaders(); @Get("test") @Headers({"name1:value1", " name2: value2", "name3 :value3 "}) void headers(); @Get("test") @Headers({"name:value1", "name:value2"}) void sameKeyTwiceLastWins(); } @ParameterizedTest @MethodSource("headersSupplier") public void headers(Method method, HttpHeaders expectedHeaders) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (HttpHeader header : swaggerMethodParser.setHeaders(null)) { assertEquals(expectedHeaders.getValue(header.getName()), header.getValue()); } } private static Stream<Arguments> headersSupplier() throws NoSuchMethodException { Class<HeaderMethods> clazz = HeaderMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noHeaders"), new HttpHeaders()), Arguments.of(clazz.getDeclaredMethod("malformedHeaders"), new HttpHeaders()), Arguments.of(clazz.getDeclaredMethod("headers"), new HttpHeaders() .put("name1", "value1").put("name2", "value2").put("name3", "value3")), Arguments.of(clazz.getDeclaredMethod("sameKeyTwiceLastWins"), new HttpHeaders().put("name", "value2")) ); } interface HostSubstitutionMethods { @Get("test") void noSubstitutions(String sub1); @Get("test") void substitution(@HostParam("sub1") String sub1); @Get("test") void encodingSubstitution(@HostParam(value = "sub1", encoded = false) String sub1); } @ParameterizedTest @MethodSource("hostSubstitutionSupplier") public void hostSubstitution(Method method, String rawHost, Object[] arguments, String expectedHost) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, rawHost); assertEquals(expectedHost, swaggerMethodParser.setHost(arguments)); } private static Stream<Arguments> hostSubstitutionSupplier() throws NoSuchMethodException { String sub1RawHost = "https: String sub2RawHost = "https: Class<HostSubstitutionMethods> clazz = HostSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodingSubstitution = clazz.getDeclaredMethod("encodingSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, sub1RawHost, toObjectArray("raw"), "{sub1}.host.com"), Arguments.of(noSubstitutions, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray("raw"), "raw.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray("{sub1}"), "{sub1}.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray((String) null), ".host.com"), Arguments.of(substitution, sub1RawHost, null, "{sub1}.host.com"), Arguments.of(substitution, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("raw"), "raw.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("{sub1}"), "%7Bsub1%7D.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray((String) null), ".host.com"), Arguments.of(substitution, sub1RawHost, null, "{sub1}.host.com"), Arguments.of(encodingSubstitution, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com") ); } @ParameterizedTest @MethodSource("schemeSubstitutionSupplier") public void schemeSubstitution(Method method, String rawHost, Object[] arguments, String expectedScheme) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, rawHost); assertEquals(expectedScheme, swaggerMethodParser.setScheme(arguments)); } private static Stream<Arguments> schemeSubstitutionSupplier() throws NoSuchMethodException { String sub1RawHost = "{sub1}: String sub2RawHost = "{sub2}: Class<HostSubstitutionMethods> clazz = HostSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodingSubstitution = clazz.getDeclaredMethod("encodingSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, sub1RawHost, toObjectArray("raw"), "{sub1}"), Arguments.of(noSubstitutions, sub2RawHost, toObjectArray("raw"), "{sub2}"), Arguments.of(substitution, sub1RawHost, toObjectArray("raw"), "raw"), Arguments.of(substitution, sub1RawHost, toObjectArray("{sub1}"), "{sub1}"), Arguments.of(substitution, sub1RawHost, toObjectArray((String) null), ""), Arguments.of(substitution, sub1RawHost, null, "{sub1}"), Arguments.of(substitution, sub2RawHost, toObjectArray("raw"), "{sub2}"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("raw"), "raw"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("{sub1}"), "%7Bsub1%7D"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray((String) null), ""), Arguments.of(substitution, sub1RawHost, null, "{sub1}"), Arguments.of(encodingSubstitution, sub2RawHost, toObjectArray("raw"), "{sub2}") ); } interface PathSubstitutionMethods { @Get("{sub1}") void noSubstitutions(String sub1); @Get("{sub1}") void substitution(@PathParam("sub1") String sub1); @Get("{sub1}") void encodedSubstitution(@PathParam(value = "sub1", encoded = true) String sub1); } @ParameterizedTest @MethodSource("pathSubstitutionSupplier") public void pathSubstitution(Method method, Object[] arguments, String expectedPath) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedPath, swaggerMethodParser.setPath(arguments)); } private static Stream<Arguments> pathSubstitutionSupplier() throws NoSuchMethodException { Class<PathSubstitutionMethods> clazz = PathSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodedSubstitution = clazz.getDeclaredMethod("encodedSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, toObjectArray("path"), "{sub1}"), Arguments.of(encodedSubstitution, toObjectArray("path"), "path"), Arguments.of(encodedSubstitution, toObjectArray("{sub1}"), "{sub1}"), Arguments.of(encodedSubstitution, toObjectArray((String) null), ""), Arguments.of(substitution, toObjectArray("path"), "path"), Arguments.of(substitution, toObjectArray("{sub1}"), "%7Bsub1%7D"), Arguments.of(substitution, toObjectArray((String) null), "") ); } interface QuerySubstitutionMethods { @Get("test") void substitutions(@QueryParam("sub1") String sub1, @QueryParam("sub2") boolean sub2); @Get("test") void encodedSubstitutions(@QueryParam(value = "sub1", encoded = true) String sub1, @QueryParam(value = "sub2", encoded = true) boolean sub2); } @ParameterizedTest @MethodSource("querySubstitutionSupplier") public void querySubstitution(Method method, Object[] arguments, Map<String, String> expectedParameters) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (EncodedParameter encodedParameter : swaggerMethodParser.setEncodedQueryParameters(arguments)) { assertEquals(expectedParameters.get(encodedParameter.getName()), encodedParameter.getEncodedValue()); } } interface HeaderSubstitutionMethods { @Get("test") void addHeaders(@HeaderParam("sub1") String sub1, @HeaderParam("sub2") boolean sub2); @Get("test") @Headers({ "sub1:sub1", "sub2:false" }) void overrideHeaders(@HeaderParam("sub1") String sub1, @HeaderParam("sub2") boolean sub2); @Get("test") void headerMap(@HeaderParam("x-ms-meta-") Map<String, String> headers); } @ParameterizedTest @MethodSource("headerSubstitutionSupplier") public void headerSubstitution(Method method, Object[] arguments, Map<String, String> expectedHeaders) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (HttpHeader header : swaggerMethodParser.setHeaders(arguments)) { assertEquals(expectedHeaders.get(header.getName()), header.getValue()); } } private static Stream<Arguments> headerSubstitutionSupplier() throws NoSuchMethodException { Class<HeaderSubstitutionMethods> clazz = HeaderSubstitutionMethods.class; Method addHeaders = clazz.getDeclaredMethod("addHeaders", String.class, boolean.class); Method overrideHeaders = clazz.getDeclaredMethod("overrideHeaders", String.class, boolean.class); Method headerMap = clazz.getDeclaredMethod("headerMap", Map.class); Map<String, String> simpleHeaderMap = Collections.singletonMap("key", "value"); Map<String, String> expectedSimpleHeadersMap = Collections.singletonMap("x-ms-meta-key", "value"); Map<String, String> complexHeaderMap = new HttpHeaders().put("key1", null).put("key2", "value2").toMap(); Map<String, String> expectedComplexHeaderMap = Collections.singletonMap("x-ms-meta-key2", "value2"); return Stream.of( Arguments.of(addHeaders, null, null), Arguments.of(addHeaders, toObjectArray("header", true), createExpectedParameters("header", true)), Arguments.of(addHeaders, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(addHeaders, toObjectArray("{sub1}", false), createExpectedParameters("{sub1}", false)), Arguments.of(overrideHeaders, null, createExpectedParameters("sub1", false)), Arguments.of(overrideHeaders, toObjectArray(null, true), createExpectedParameters("sub1", true)), Arguments.of(overrideHeaders, toObjectArray("header", false), createExpectedParameters("header", false)), Arguments.of(overrideHeaders, toObjectArray("{sub1}", true), createExpectedParameters("{sub1}", true)), Arguments.of(headerMap, null, null), Arguments.of(headerMap, toObjectArray(simpleHeaderMap), expectedSimpleHeadersMap), Arguments.of(headerMap, toObjectArray(complexHeaderMap), expectedComplexHeaderMap) ); } interface BodySubstitutionMethods { @Get("test") void applicationJsonBody(@BodyParam(ContentType.APPLICATION_JSON) String jsonBody); @Get("test") void formBody(@FormParam("name") String name, @FormParam("age") Integer age, @FormParam("dob") OffsetDateTime dob, @FormParam("favoriteColors") List<String> favoriteColors); @Get("test") void encodedFormBody(@FormParam(value = "name", encoded = true) String name, @FormParam("age") Integer age, @FormParam("dob") OffsetDateTime dob, @FormParam("favoriteColors") List<String> favoriteColors); @Get("test") void encodedFormKey(@FormParam(value = "x:ms:value") String value); @Get("test") void encodedFormKey2(@FormParam(value = "x:ms:value", encoded = true) String value); } @ParameterizedTest @MethodSource("bodySubstitutionSupplier") public void bodySubstitution(Method method, Object[] arguments, String expectedBodyContentType, Object expectedBody) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(void.class, swaggerMethodParser.getReturnType()); assertEquals(String.class, swaggerMethodParser.getBodyJavaType()); assertEquals(expectedBodyContentType, swaggerMethodParser.getBodyContentType()); assertEquals(expectedBody, swaggerMethodParser.setBody(arguments)); } private static Stream<Arguments> bodySubstitutionSupplier() throws NoSuchMethodException { Class<BodySubstitutionMethods> clazz = BodySubstitutionMethods.class; Method jsonBody = clazz.getDeclaredMethod("applicationJsonBody", String.class); Method formBody = clazz.getDeclaredMethod("formBody", String.class, Integer.class, OffsetDateTime.class, List.class); Method encodedFormBody = clazz.getDeclaredMethod("encodedFormBody", String.class, Integer.class, OffsetDateTime.class, List.class); Method encodedFormKey = clazz.getDeclaredMethod("encodedFormKey", String.class); Method encodedFormKey2 = clazz.getDeclaredMethod("encodedFormKey2", String.class); OffsetDateTime dob = OffsetDateTime.of(1980, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); List<String> favoriteColors = Arrays.asList("blue", "green"); List<String> badFavoriteColors = Arrays.asList(null, "green"); return Stream.of( Arguments.of(jsonBody, null, ContentType.APPLICATION_JSON, null), Arguments.of(jsonBody, toObjectArray("{name:John Doe,age:40,dob:01-01-1980}"), ContentType.APPLICATION_JSON, "{name:John Doe,age:40,dob:01-01-1980}"), Arguments.of(formBody, null, APPLICATION_X_WWW_FORM_URLENCODED, null), Arguments.of(formBody, toObjectArray("John Doe", null, dob, null), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&dob=1980-01-01T00%3A00%3A00Z"), Arguments.of(formBody, toObjectArray("John Doe", 40, null, favoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&age=40&favoriteColors=blue&favoriteColors=green"), Arguments.of(formBody, toObjectArray("John Doe", 40, null, badFavoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&age=40&favoriteColors=green"), Arguments.of(encodedFormBody, null, APPLICATION_X_WWW_FORM_URLENCODED, null), Arguments.of(encodedFormBody, toObjectArray("John Doe", null, dob, null), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&dob=1980-01-01T00%3A00%3A00Z"), Arguments.of(encodedFormBody, toObjectArray("John Doe", 40, null, favoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&age=40&favoriteColors=blue&favoriteColors=green"), Arguments.of(encodedFormBody, toObjectArray("John Doe", 40, null, badFavoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&age=40&favoriteColors=green"), Arguments.of(encodedFormKey, toObjectArray("value"), APPLICATION_X_WWW_FORM_URLENCODED, "x%3Ams%3Avalue=value"), Arguments.of(encodedFormKey2, toObjectArray("value"), APPLICATION_X_WWW_FORM_URLENCODED, "x%3Ams%3Avalue=value") ); } @ParameterizedTest @MethodSource("setContextSupplier") public void setContext(SwaggerMethodParser swaggerMethodParser, Object[] arguments, Context expectedContext) { assertEquals(expectedContext, swaggerMethodParser.setContext(arguments)); } private static Stream<Arguments> setContextSupplier() throws NoSuchMethodException { Method method = OperationMethods.class.getDeclaredMethod("getMethod"); SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: Context context = new Context("key", "value"); return Stream.of( Arguments.of(swaggerMethodParser, null, Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray(), Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray("string"), Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray(context), context) ); } interface ExpectedStatusCodeMethods { @Get("test") void noExpectedStatusCodes(); @Get("test") @ExpectedResponses({ 200 }) void only200IsExpected(); @Get("test") @ExpectedResponses({ 429, 503 }) void retryAfterExpected(); } @ParameterizedTest @MethodSource("expectedStatusCodeSupplier") public void expectedStatusCodeSupplier(Method method, int statusCode, int[] expectedStatusCodes, boolean matchesExpected) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertArrayEquals(expectedStatusCodes, swaggerMethodParser.getExpectedStatusCodes()); assertEquals(matchesExpected, swaggerMethodParser.isExpectedResponseStatusCode(statusCode)); } private static Stream<Arguments> expectedStatusCodeSupplier() throws NoSuchMethodException { Class<ExpectedStatusCodeMethods> clazz = ExpectedStatusCodeMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 200, null, true), Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 201, null, true), Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 400, null, false), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 200, new int[] {200}, true), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 201, new int[] {200}, false), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 400, new int[] {200}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 200, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 201, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 400, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 429, new int[] {429, 503}, true), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 503, new int[] {429, 503}, true) ); } interface UnexpectedStatusCodeMethods { @Get("test") void noUnexpectedStatusCodes(); @Get("test") @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = {400, 404}) void notFoundStatusCode(); @Get("test") @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = {400, 404}) @UnexpectedResponseExceptionType(value = ResourceModifiedException.class) void customDefault(); } @ParameterizedTest @MethodSource("unexpectedStatusCodeSupplier") public void unexpectedStatusCode(Method method, int statusCode, Class<?> expectedExceptionType) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedExceptionType, swaggerMethodParser.getUnexpectedException(statusCode).getExceptionType()); } private static Stream<Arguments> unexpectedStatusCodeSupplier() throws NoSuchMethodException { Class<UnexpectedStatusCodeMethods> clazz = UnexpectedStatusCodeMethods.class; Method noUnexpectedStatusCodes = clazz.getDeclaredMethod("noUnexpectedStatusCodes"); Method notFoundStatusCode = clazz.getDeclaredMethod("notFoundStatusCode"); Method customDefault = clazz.getDeclaredMethod("customDefault"); return Stream.of( Arguments.of(noUnexpectedStatusCodes, 500, HttpResponseException.class), Arguments.of(noUnexpectedStatusCodes, 400, HttpResponseException.class), Arguments.of(noUnexpectedStatusCodes, 404, HttpResponseException.class), Arguments.of(notFoundStatusCode, 500, HttpResponseException.class), Arguments.of(notFoundStatusCode, 400, ResourceNotFoundException.class), Arguments.of(notFoundStatusCode, 404, ResourceNotFoundException.class), Arguments.of(customDefault, 500, ResourceModifiedException.class), Arguments.of(customDefault, 400, ResourceNotFoundException.class), Arguments.of(customDefault, 404, ResourceNotFoundException.class) ); } private static Object[] toObjectArray(Object... objects) { return objects; } private static Map<String, String> createExpectedParameters(String sub1Value, boolean sub2Value) { Map<String, String> expectedParameters = new HashMap<>(); if (sub1Value != null) { expectedParameters.put("sub1", sub1Value); } expectedParameters.put("sub2", String.valueOf(sub2Value)); return expectedParameters; } }
class SwaggerMethodParserTests { interface OperationMethods { void noMethod(); @Get("test") void getMethod(); @Put("test") void putMethod(); @Head("test") void headMethod(); @Delete("test") void deleteMethod(); @Post("test") void postMethod(); @Patch("test") void patchMethod(); } @Test public void noHttpMethodAnnotation() throws NoSuchMethodException { Method noHttpMethodAnnotation = OperationMethods.class.getDeclaredMethod("noMethod"); assertThrows(MissingRequiredAnnotationException.class, () -> new SwaggerMethodParser(noHttpMethodAnnotation, "s: } @ParameterizedTest @MethodSource("httpMethodSupplier") public void httpMethod(Method method, HttpMethod expectedMethod, String expectedRelativePath, String expectedFullyQualifiedName) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedMethod, swaggerMethodParser.getHttpMethod()); assertEquals(expectedRelativePath, swaggerMethodParser.setPath(null)); assertEquals(expectedFullyQualifiedName, swaggerMethodParser.getFullyQualifiedMethodName()); } private static Stream<Arguments> httpMethodSupplier() throws NoSuchMethodException { Class<OperationMethods> clazz = OperationMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("getMethod"), HttpMethod.GET, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.getMethod"), Arguments.of(clazz.getDeclaredMethod("putMethod"), HttpMethod.PUT, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.putMethod"), Arguments.of(clazz.getDeclaredMethod("headMethod"), HttpMethod.HEAD, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.headMethod"), Arguments.of(clazz.getDeclaredMethod("deleteMethod"), HttpMethod.DELETE, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.deleteMethod"), Arguments.of(clazz.getDeclaredMethod("postMethod"), HttpMethod.POST, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.postMethod"), Arguments.of(clazz.getDeclaredMethod("patchMethod"), HttpMethod.PATCH, "test", "com.azure.core.http.rest.SwaggerMethodParserTests$OperationMethods.patchMethod") ); } interface WireTypesMethods { @Get("test") void noWireType(); @Get("test") @ReturnValueWireType(Base64Url.class) void base64Url(); @Get("test") @ReturnValueWireType(UnixTime.class) void unixTime(); @Get("test") @ReturnValueWireType(DateTimeRfc1123.class) void dateTimeRfc1123(); @Get("test") @ReturnValueWireType(Page.class) void page(); @Get("test") @ReturnValueWireType(Boolean.class) void unknownType(); } @ParameterizedTest @MethodSource("wireTypesSupplier") public void wireTypes(Method method, Class<?> expectedWireType) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedWireType, swaggerMethodParser.getReturnValueWireType()); } private static Stream<Arguments> wireTypesSupplier() throws NoSuchMethodException { Class<WireTypesMethods> clazz = WireTypesMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noWireType"), null), Arguments.of(clazz.getDeclaredMethod("base64Url"), Base64Url.class), Arguments.of(clazz.getDeclaredMethod("unixTime"), UnixTime.class), Arguments.of(clazz.getDeclaredMethod("dateTimeRfc1123"), DateTimeRfc1123.class), Arguments.of(clazz.getDeclaredMethod("page"), Page.class), Arguments.of(clazz.getDeclaredMethod("unknownType"), null) ); } interface HeaderMethods { @Get("test") void noHeaders(); @Get("test") @Headers({"", ":", "nameOnly:", ":valueOnly"}) void malformedHeaders(); @Get("test") @Headers({"name1:value1", " name2: value2", "name3 :value3 "}) void headers(); @Get("test") @Headers({"name:value1", "name:value2"}) void sameKeyTwiceLastWins(); } @ParameterizedTest @MethodSource("headersSupplier") public void headers(Method method, HttpHeaders expectedHeaders) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (HttpHeader header : swaggerMethodParser.setHeaders(null)) { assertEquals(expectedHeaders.getValue(header.getName()), header.getValue()); } } private static Stream<Arguments> headersSupplier() throws NoSuchMethodException { Class<HeaderMethods> clazz = HeaderMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noHeaders"), new HttpHeaders()), Arguments.of(clazz.getDeclaredMethod("malformedHeaders"), new HttpHeaders()), Arguments.of(clazz.getDeclaredMethod("headers"), new HttpHeaders() .put("name1", "value1").put("name2", "value2").put("name3", "value3")), Arguments.of(clazz.getDeclaredMethod("sameKeyTwiceLastWins"), new HttpHeaders().put("name", "value2")) ); } interface HostSubstitutionMethods { @Get("test") void noSubstitutions(String sub1); @Get("test") void substitution(@HostParam("sub1") String sub1); @Get("test") void encodingSubstitution(@HostParam(value = "sub1", encoded = false) String sub1); } @ParameterizedTest @MethodSource("hostSubstitutionSupplier") public void hostSubstitution(Method method, String rawHost, Object[] arguments, String expectedHost) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, rawHost); assertEquals(expectedHost, swaggerMethodParser.setHost(arguments)); } private static Stream<Arguments> hostSubstitutionSupplier() throws NoSuchMethodException { String sub1RawHost = "https: String sub2RawHost = "https: Class<HostSubstitutionMethods> clazz = HostSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodingSubstitution = clazz.getDeclaredMethod("encodingSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, sub1RawHost, toObjectArray("raw"), "{sub1}.host.com"), Arguments.of(noSubstitutions, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray("raw"), "raw.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray("{sub1}"), "{sub1}.host.com"), Arguments.of(substitution, sub1RawHost, toObjectArray((String) null), ".host.com"), Arguments.of(substitution, sub1RawHost, null, "{sub1}.host.com"), Arguments.of(substitution, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("raw"), "raw.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("{sub1}"), "%7Bsub1%7D.host.com"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray((String) null), ".host.com"), Arguments.of(substitution, sub1RawHost, null, "{sub1}.host.com"), Arguments.of(encodingSubstitution, sub2RawHost, toObjectArray("raw"), "{sub2}.host.com") ); } @ParameterizedTest @MethodSource("schemeSubstitutionSupplier") public void schemeSubstitution(Method method, String rawHost, Object[] arguments, String expectedScheme) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, rawHost); assertEquals(expectedScheme, swaggerMethodParser.setScheme(arguments)); } private static Stream<Arguments> schemeSubstitutionSupplier() throws NoSuchMethodException { String sub1RawHost = "{sub1}: String sub2RawHost = "{sub2}: Class<HostSubstitutionMethods> clazz = HostSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodingSubstitution = clazz.getDeclaredMethod("encodingSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, sub1RawHost, toObjectArray("raw"), "{sub1}"), Arguments.of(noSubstitutions, sub2RawHost, toObjectArray("raw"), "{sub2}"), Arguments.of(substitution, sub1RawHost, toObjectArray("raw"), "raw"), Arguments.of(substitution, sub1RawHost, toObjectArray("{sub1}"), "{sub1}"), Arguments.of(substitution, sub1RawHost, toObjectArray((String) null), ""), Arguments.of(substitution, sub1RawHost, null, "{sub1}"), Arguments.of(substitution, sub2RawHost, toObjectArray("raw"), "{sub2}"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("raw"), "raw"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray("{sub1}"), "%7Bsub1%7D"), Arguments.of(encodingSubstitution, sub1RawHost, toObjectArray((String) null), ""), Arguments.of(substitution, sub1RawHost, null, "{sub1}"), Arguments.of(encodingSubstitution, sub2RawHost, toObjectArray("raw"), "{sub2}") ); } interface PathSubstitutionMethods { @Get("{sub1}") void noSubstitutions(String sub1); @Get("{sub1}") void substitution(@PathParam("sub1") String sub1); @Get("{sub1}") void encodedSubstitution(@PathParam(value = "sub1", encoded = true) String sub1); } @ParameterizedTest @MethodSource("pathSubstitutionSupplier") public void pathSubstitution(Method method, Object[] arguments, String expectedPath) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedPath, swaggerMethodParser.setPath(arguments)); } private static Stream<Arguments> pathSubstitutionSupplier() throws NoSuchMethodException { Class<PathSubstitutionMethods> clazz = PathSubstitutionMethods.class; Method noSubstitutions = clazz.getDeclaredMethod("noSubstitutions", String.class); Method substitution = clazz.getDeclaredMethod("substitution", String.class); Method encodedSubstitution = clazz.getDeclaredMethod("encodedSubstitution", String.class); return Stream.of( Arguments.of(noSubstitutions, toObjectArray("path"), "{sub1}"), Arguments.of(encodedSubstitution, toObjectArray("path"), "path"), Arguments.of(encodedSubstitution, toObjectArray("{sub1}"), "{sub1}"), Arguments.of(encodedSubstitution, toObjectArray((String) null), ""), Arguments.of(substitution, toObjectArray("path"), "path"), Arguments.of(substitution, toObjectArray("{sub1}"), "%7Bsub1%7D"), Arguments.of(substitution, toObjectArray((String) null), "") ); } interface QuerySubstitutionMethods { @Get("test") void substitutions(@QueryParam("sub1") String sub1, @QueryParam("sub2") boolean sub2); @Get("test") void encodedSubstitutions(@QueryParam(value = "sub1", encoded = true) String sub1, @QueryParam(value = "sub2", encoded = true) boolean sub2); } @ParameterizedTest @MethodSource("querySubstitutionSupplier") public void querySubstitution(Method method, Object[] arguments, Map<String, String> expectedParameters) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (EncodedParameter encodedParameter : swaggerMethodParser.setEncodedQueryParameters(arguments)) { assertEquals(expectedParameters.get(encodedParameter.getName()), encodedParameter.getEncodedValue()); } } interface HeaderSubstitutionMethods { @Get("test") void addHeaders(@HeaderParam("sub1") String sub1, @HeaderParam("sub2") boolean sub2); @Get("test") @Headers({ "sub1:sub1", "sub2:false" }) void overrideHeaders(@HeaderParam("sub1") String sub1, @HeaderParam("sub2") boolean sub2); @Get("test") void headerMap(@HeaderParam("x-ms-meta-") Map<String, String> headers); } @ParameterizedTest @MethodSource("headerSubstitutionSupplier") public void headerSubstitution(Method method, Object[] arguments, Map<String, String> expectedHeaders) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: for (HttpHeader header : swaggerMethodParser.setHeaders(arguments)) { assertEquals(expectedHeaders.get(header.getName()), header.getValue()); } } private static Stream<Arguments> headerSubstitutionSupplier() throws NoSuchMethodException { Class<HeaderSubstitutionMethods> clazz = HeaderSubstitutionMethods.class; Method addHeaders = clazz.getDeclaredMethod("addHeaders", String.class, boolean.class); Method overrideHeaders = clazz.getDeclaredMethod("overrideHeaders", String.class, boolean.class); Method headerMap = clazz.getDeclaredMethod("headerMap", Map.class); Map<String, String> simpleHeaderMap = Collections.singletonMap("key", "value"); Map<String, String> expectedSimpleHeadersMap = Collections.singletonMap("x-ms-meta-key", "value"); Map<String, String> complexHeaderMap = new HttpHeaders().put("key1", null).put("key2", "value2").toMap(); Map<String, String> expectedComplexHeaderMap = Collections.singletonMap("x-ms-meta-key2", "value2"); return Stream.of( Arguments.of(addHeaders, null, null), Arguments.of(addHeaders, toObjectArray("header", true), createExpectedParameters("header", true)), Arguments.of(addHeaders, toObjectArray(null, true), createExpectedParameters(null, true)), Arguments.of(addHeaders, toObjectArray("{sub1}", false), createExpectedParameters("{sub1}", false)), Arguments.of(overrideHeaders, null, createExpectedParameters("sub1", false)), Arguments.of(overrideHeaders, toObjectArray(null, true), createExpectedParameters("sub1", true)), Arguments.of(overrideHeaders, toObjectArray("header", false), createExpectedParameters("header", false)), Arguments.of(overrideHeaders, toObjectArray("{sub1}", true), createExpectedParameters("{sub1}", true)), Arguments.of(headerMap, null, null), Arguments.of(headerMap, toObjectArray(simpleHeaderMap), expectedSimpleHeadersMap), Arguments.of(headerMap, toObjectArray(complexHeaderMap), expectedComplexHeaderMap) ); } interface BodySubstitutionMethods { @Get("test") void applicationJsonBody(@BodyParam(ContentType.APPLICATION_JSON) String jsonBody); @Get("test") void formBody(@FormParam("name") String name, @FormParam("age") Integer age, @FormParam("dob") OffsetDateTime dob, @FormParam("favoriteColors") List<String> favoriteColors); @Get("test") void encodedFormBody(@FormParam(value = "name", encoded = true) String name, @FormParam("age") Integer age, @FormParam("dob") OffsetDateTime dob, @FormParam("favoriteColors") List<String> favoriteColors); @Get("test") void encodedFormKey(@FormParam(value = "x:ms:value") String value); @Get("test") void encodedFormKey2(@FormParam(value = "x:ms:value", encoded = true) String value); } @ParameterizedTest @MethodSource("bodySubstitutionSupplier") public void bodySubstitution(Method method, Object[] arguments, String expectedBodyContentType, Object expectedBody) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(void.class, swaggerMethodParser.getReturnType()); assertEquals(String.class, swaggerMethodParser.getBodyJavaType()); assertEquals(expectedBodyContentType, swaggerMethodParser.getBodyContentType()); assertEquals(expectedBody, swaggerMethodParser.setBody(arguments)); } private static Stream<Arguments> bodySubstitutionSupplier() throws NoSuchMethodException { Class<BodySubstitutionMethods> clazz = BodySubstitutionMethods.class; Method jsonBody = clazz.getDeclaredMethod("applicationJsonBody", String.class); Method formBody = clazz.getDeclaredMethod("formBody", String.class, Integer.class, OffsetDateTime.class, List.class); Method encodedFormBody = clazz.getDeclaredMethod("encodedFormBody", String.class, Integer.class, OffsetDateTime.class, List.class); Method encodedFormKey = clazz.getDeclaredMethod("encodedFormKey", String.class); Method encodedFormKey2 = clazz.getDeclaredMethod("encodedFormKey2", String.class); OffsetDateTime dob = OffsetDateTime.of(1980, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); List<String> favoriteColors = Arrays.asList("blue", "green"); List<String> badFavoriteColors = Arrays.asList(null, "green"); return Stream.of( Arguments.of(jsonBody, null, ContentType.APPLICATION_JSON, null), Arguments.of(jsonBody, toObjectArray("{name:John Doe,age:40,dob:01-01-1980}"), ContentType.APPLICATION_JSON, "{name:John Doe,age:40,dob:01-01-1980}"), Arguments.of(formBody, null, APPLICATION_X_WWW_FORM_URLENCODED, null), Arguments.of(formBody, toObjectArray("John Doe", null, dob, null), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&dob=1980-01-01T00%3A00%3A00Z"), Arguments.of(formBody, toObjectArray("John Doe", 40, null, favoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&age=40&favoriteColors=blue&favoriteColors=green"), Arguments.of(formBody, toObjectArray("John Doe", 40, null, badFavoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John+Doe&age=40&favoriteColors=green"), Arguments.of(encodedFormBody, null, APPLICATION_X_WWW_FORM_URLENCODED, null), Arguments.of(encodedFormBody, toObjectArray("John Doe", null, dob, null), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&dob=1980-01-01T00%3A00%3A00Z"), Arguments.of(encodedFormBody, toObjectArray("John Doe", 40, null, favoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&age=40&favoriteColors=blue&favoriteColors=green"), Arguments.of(encodedFormBody, toObjectArray("John Doe", 40, null, badFavoriteColors), APPLICATION_X_WWW_FORM_URLENCODED, "name=John Doe&age=40&favoriteColors=green"), Arguments.of(encodedFormKey, toObjectArray("value"), APPLICATION_X_WWW_FORM_URLENCODED, "x%3Ams%3Avalue=value"), Arguments.of(encodedFormKey2, toObjectArray("value"), APPLICATION_X_WWW_FORM_URLENCODED, "x%3Ams%3Avalue=value") ); } @ParameterizedTest @MethodSource("setContextSupplier") public void setContext(SwaggerMethodParser swaggerMethodParser, Object[] arguments, Context expectedContext) { assertEquals(expectedContext, swaggerMethodParser.setContext(arguments)); } private static Stream<Arguments> setContextSupplier() throws NoSuchMethodException { Method method = OperationMethods.class.getDeclaredMethod("getMethod"); SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: Context context = new Context("key", "value"); return Stream.of( Arguments.of(swaggerMethodParser, null, Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray(), Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray("string"), Context.NONE), Arguments.of(swaggerMethodParser, toObjectArray(context), context) ); } interface ExpectedStatusCodeMethods { @Get("test") void noExpectedStatusCodes(); @Get("test") @ExpectedResponses({ 200 }) void only200IsExpected(); @Get("test") @ExpectedResponses({ 429, 503 }) void retryAfterExpected(); } @ParameterizedTest @MethodSource("expectedStatusCodeSupplier") public void expectedStatusCodeSupplier(Method method, int statusCode, int[] expectedStatusCodes, boolean matchesExpected) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertArrayEquals(expectedStatusCodes, swaggerMethodParser.getExpectedStatusCodes()); assertEquals(matchesExpected, swaggerMethodParser.isExpectedResponseStatusCode(statusCode)); } private static Stream<Arguments> expectedStatusCodeSupplier() throws NoSuchMethodException { Class<ExpectedStatusCodeMethods> clazz = ExpectedStatusCodeMethods.class; return Stream.of( Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 200, null, true), Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 201, null, true), Arguments.of(clazz.getDeclaredMethod("noExpectedStatusCodes"), 400, null, false), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 200, new int[] {200}, true), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 201, new int[] {200}, false), Arguments.of(clazz.getDeclaredMethod("only200IsExpected"), 400, new int[] {200}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 200, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 201, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 400, new int[] {429, 503}, false), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 429, new int[] {429, 503}, true), Arguments.of(clazz.getDeclaredMethod("retryAfterExpected"), 503, new int[] {429, 503}, true) ); } interface UnexpectedStatusCodeMethods { @Get("test") void noUnexpectedStatusCodes(); @Get("test") @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = {400, 404}) void notFoundStatusCode(); @Get("test") @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = {400, 404}) @UnexpectedResponseExceptionType(value = ResourceModifiedException.class) void customDefault(); } @ParameterizedTest @MethodSource("unexpectedStatusCodeSupplier") public void unexpectedStatusCode(Method method, int statusCode, Class<?> expectedExceptionType) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method, "https: assertEquals(expectedExceptionType, swaggerMethodParser.getUnexpectedException(statusCode).getExceptionType()); } private static Stream<Arguments> unexpectedStatusCodeSupplier() throws NoSuchMethodException { Class<UnexpectedStatusCodeMethods> clazz = UnexpectedStatusCodeMethods.class; Method noUnexpectedStatusCodes = clazz.getDeclaredMethod("noUnexpectedStatusCodes"); Method notFoundStatusCode = clazz.getDeclaredMethod("notFoundStatusCode"); Method customDefault = clazz.getDeclaredMethod("customDefault"); return Stream.of( Arguments.of(noUnexpectedStatusCodes, 500, HttpResponseException.class), Arguments.of(noUnexpectedStatusCodes, 400, HttpResponseException.class), Arguments.of(noUnexpectedStatusCodes, 404, HttpResponseException.class), Arguments.of(notFoundStatusCode, 500, HttpResponseException.class), Arguments.of(notFoundStatusCode, 400, ResourceNotFoundException.class), Arguments.of(notFoundStatusCode, 404, ResourceNotFoundException.class), Arguments.of(customDefault, 500, ResourceModifiedException.class), Arguments.of(customDefault, 400, ResourceNotFoundException.class), Arguments.of(customDefault, 404, ResourceNotFoundException.class) ); } private static Object[] toObjectArray(Object... objects) { return objects; } private static Map<String, String> createExpectedParameters(String sub1Value, boolean sub2Value) { Map<String, String> expectedParameters = new HashMap<>(); if (sub1Value != null) { expectedParameters.put("sub1", sub1Value); } expectedParameters.put("sub2", String.valueOf(sub2Value)); return expectedParameters; } }
Added
private static Stream<Arguments> escapeSupplier() { PercentEscaper defaultEscaper = new PercentEscaper(null, false); return Stream.of( Arguments.arguments(defaultEscaper, "$", "%24"), Arguments.arguments(defaultEscaper, "¢", "%C2%A2"), Arguments.arguments(defaultEscaper, "ह", "%E0%A4%B9"), Arguments.arguments(defaultEscaper, "€", "%E2%82%AC"), Arguments.arguments(defaultEscaper, "한", "%ED%95%9C"), Arguments.arguments(defaultEscaper, "円", "%E5%86%86"), Arguments.arguments(defaultEscaper, "\uD800\uDF48", "%F0%90%8D%88"), Arguments.arguments(defaultEscaper, "日本語", "%E6%97%A5%E6%9C%AC%E8%AA%9E"), Arguments.arguments(defaultEscaper, " ", "%20"), Arguments.arguments(new PercentEscaper(null, true), " ", "+"), Arguments.arguments(new PercentEscaper("$", false), "$", "$") ); }
Arguments.arguments(new PercentEscaper("$", false), "$", "$")
private static Stream<Arguments> escapeSupplier() { PercentEscaper defaultEscaper = new PercentEscaper(null, false); return Stream.of( Arguments.arguments(defaultEscaper, null, null), Arguments.arguments(defaultEscaper, "", ""), Arguments.arguments(defaultEscaper, "$", "%24"), Arguments.arguments(defaultEscaper, "¢", "%C2%A2"), Arguments.arguments(defaultEscaper, "ह", "%E0%A4%B9"), Arguments.arguments(defaultEscaper, "€", "%E2%82%AC"), Arguments.arguments(defaultEscaper, "한", "%ED%95%9C"), Arguments.arguments(defaultEscaper, "円", "%E5%86%86"), Arguments.arguments(defaultEscaper, "\uD800\uDF48", "%F0%90%8D%88"), Arguments.arguments(defaultEscaper, "日本語", "%E6%97%A5%E6%9C%AC%E8%AA%9E"), Arguments.arguments(defaultEscaper, " ", "%20"), Arguments.arguments(new PercentEscaper(null, true), " ", "+"), Arguments.arguments(new PercentEscaper("$", false), "$", "$"), Arguments.arguments(new PercentEscaper("ह", false), "ह", "ह") ); }
class PercentEscaperTests { @ParameterizedTest @MethodSource("escapeSupplier") public void escape(PercentEscaper escaper, String original, String expected) { assertEquals(expected, escaper.escape(original)); } }
class PercentEscaperTests { /** * Tests that using {@code ' '} as a safe character and treating {@code ' '} as {@code '+'} is an illegal * configuration. */ @Test public void cannotUseSpaceAsPlusAndSpaceAsSafeCharacter() { assertThrows(IllegalArgumentException.class, () -> new PercentEscaper(" ", true)); } /** * Tests that valid inputs are escaped correctly. */ @ParameterizedTest @MethodSource("escapeSupplier") public void escape(PercentEscaper escaper, String original, String expected) { assertEquals(expected, escaper.escape(original)); } @ParameterizedTest @MethodSource("invalidEscapeSupplier") public void invalidEscape(String original) { assertThrows(IllegalStateException.class, () -> new PercentEscaper(null, false).escape(original)); } private static Stream<Arguments> invalidEscapeSupplier() { return Stream.of( Arguments.arguments("abcd\uD800"), Arguments.arguments("abcd\uDF48\uD800"), Arguments.arguments("\uD800abcd") ); } }
Why are you chaining.`then()`? The send operation already returns a mono void.
public Mono<Void> send(Iterable<ServiceBusMessage> messages) { Objects.requireNonNull(messages, "'messages' cannot be null."); return createBatch().flatMap(messageBatch -> { messages.forEach(serviceBusMessage -> messageBatch.tryAdd(serviceBusMessage)); return send(messageBatch); }).then(); }
}).then();
public Mono<Void> send(Iterable<ServiceBusMessage> messages) { if (Objects.isNull(messages)) { return monoError(logger, new NullPointerException("'messages' cannot be null.")); } return createBatch().flatMap(messageBatch -> { messages.forEach(message -> messageBatch.tryAdd(message)); return send(messageBatch); }); }
class ServiceBusSenderAsyncClient implements AutoCloseable { /** * The default maximum allowable size, in bytes, for a batch to be sent. */ static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024; private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions(); private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final AmqpRetryOptions retryOptions; private final AmqpRetryPolicy retryPolicy; private final MessagingEntityType entityType; private final Runnable onClientClose; private final String entityName; private final ServiceBusConnectionProcessor connectionProcessor; /** * Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to a Service Bus entity. */ ServiceBusSenderAsyncClient(String entityName, MessagingEntityType entityType, ServiceBusConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) { this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = tracerProvider; this.retryPolicy = getRetryPolicy(retryOptions); this.entityType = entityType; this.onClientClose = onClientClose; } /** * Gets the fully qualified namespace. * * @return The fully qualified namespace. */ public String getFullyQualifiedNamespace() { return connectionProcessor.getFullyQualifiedNamespace(); } /** * Gets the name of the Service Bus resource. * * @return The name of the Service Bus resource. */ public String getEntityPath() { return entityName; } /** * Sends a message to a Service Bus queue or topic. * * @param message Message to be sent to Service Bus queue or topic. * * @return The {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code message} is {@code null}. */ public Mono<Void> send(ServiceBusMessage message) { Objects.requireNonNull(message, "'message' cannot be null."); return sendInternal(Flux.just(message)); } /** * Sends a list of messages to a Service Bus queue or topic using a batched approach. If the size of messages * exceed the maximum size of a single batch, an exception will be triggered and the send will fail. * By default, the message size is the max amount allowed on the link. * * @param messages Messages to be sent to Service Bus queue or topic. * * @return The {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code messages} is {@code null}. */ /** * Sends a message to a Service Bus queue or topic. * * @param message Message to be sent to Service Bus queue or topic. * @param sessionId the session id to associate with the message. * * @return A {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code message} or {@code sessionId} is {@code null}. */ public Mono<Void> send(ServiceBusMessage message, String sessionId) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(sessionId, "'sessionId' cannot be null."); return Mono.error(new IllegalStateException("Not implemented.")); } /** * Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows. * * @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows. */ public Mono<ServiceBusMessageBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link ServiceBusMessageBatch} configured with the options specified. * * @param options A set of options used to configure the {@link ServiceBusMessageBatch}. * @return A new {@link ServiceBusMessageBatch} configured with the given options. * @throws NullPointerException if {@code options} is null. */ public Mono<ServiceBusMessageBatch> createBatch(CreateBatchOptions options) { Objects.requireNonNull(options, "'options' cannot be null."); final int maxSize = options.getMaximumSizeInBytes(); return getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (maxSize > maximumLinkSize) { return monoError(logger, new IllegalArgumentException(String.format(Locale.US, "CreateBatchOptions.getMaximumSizeInBytes (%s bytes) is larger than the link size" + " (%s bytes).", maxSize, maximumLinkSize))); } final int batchSize = maxSize > 0 ? maxSize : maximumLinkSize; return Mono.just( new ServiceBusMessageBatch(batchSize, link::getErrorContext, tracerProvider, messageSerializer)); })); } /** * Sends a message batch to the Azure Service Bus entity this sender is connected to. * * @param batch of messages which allows client to send maximum allowed size for a batch of messages. * * @return A {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code batch} is {@code null}. */ public Mono<Void> send(ServiceBusMessageBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); final boolean isTracingEnabled = tracerProvider.isEnabled(); final AtomicReference<Context> parentContext = isTracingEnabled ? new AtomicReference<>(Context.NONE) : null; if (batch.getMessages().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } logger.info("Sending batch with size[{}].", batch.getCount()); Context sharedContext = null; final List<org.apache.qpid.proton.message.Message> messages = new ArrayList<>(); for (int i = 0; i < batch.getMessages().size(); i++) { final ServiceBusMessage event = batch.getMessages().get(i); if (isTracingEnabled) { parentContext.set(event.getContext()); if (i == 0) { sharedContext = tracerProvider.getSharedSpanBuilder(parentContext.get()); } tracerProvider.addSpanLinks(sharedContext.addData(SPAN_CONTEXT_KEY, event.getContext())); } final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(event); final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); message.setMessageAnnotations(messageAnnotations); messages.add(message); } final Context finalSharedContext = sharedContext != null ? sharedContext : Context.NONE; return withRetry( getSendLink().flatMap(link -> { if (isTracingEnabled) { Context entityContext = finalSharedContext.addData(ENTITY_PATH_KEY, link.getEntityPath()); parentContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME_KEY, link.getHostname()), ProcessKind.SEND)); } return messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages); }) .doOnEach(signal -> { if (isTracingEnabled) { tracerProvider.endSpan(parentContext.get(), signal); } }) .doOnError(error -> { if (isTracingEnabled) { tracerProvider.endSpan(parentContext.get(), Signal.error(error)); } }), retryOptions.getTryTimeout(), retryPolicy); } /** * Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is * enqueued and made available to receivers only at the scheduled enqueue time. * * @param message Message to be sent to the Service Bus Queue. * @param scheduledEnqueueTime Instant at which the message should appear in the Service Bus queue or topic. * * @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message. * * @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}. */ public Mono<Long> scheduleMessage(ServiceBusMessage message, Instant scheduledEnqueueTime) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(scheduledEnqueueTime, "'scheduledEnqueueTime' cannot be null."); return getSendLink() .flatMap(link -> link.getLinkSize().flatMap(size -> { int maxSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName, entityType)) .flatMap(managementNode -> managementNode.schedule(message, scheduledEnqueueTime, maxSize)); })); } /** * Cancels the enqueuing of an already scheduled message, if it was not already enqueued. * * @param sequenceNumber of the scheduled message to cancel. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws IllegalArgumentException if {@code sequenceNumber} is negative. */ public Mono<Void> cancelScheduledMessage(long sequenceNumber) { if (sequenceNumber < 0) { return monoError(logger, new IllegalArgumentException("'sequenceNumber' cannot be negative.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName, entityType)) .flatMap(managementNode -> managementNode.cancelScheduledMessage(sequenceNumber)); } /** * Disposes of the {@link ServiceBusSenderAsyncClient}. If the client had a dedicated connection, the underlying * connection is also closed. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } onClientClose.run(); } private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages) { return getSendLink() .flatMap(link -> link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final CreateBatchOptions batchOptions = new CreateBatchOptions() .setMaximumSizeInBytes(batchSize); return messages.collect(new AmqpMessageCollector(batchOptions, 1, link::getErrorContext, tracerProvider, messageSerializer)); }) .flatMap(list -> sendInternalBatch(Flux.fromIterable(list)))); } private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private Mono<AmqpSendLink> getSendLink() { return connectionProcessor .flatMap(connection -> connection.createSendLink(entityName, entityName, retryOptions)); } private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> { private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private final TracerProvider tracerProvider; private final MessageSerializer serializer; private volatile ServiceBusMessageBatch currentBatch; AmqpMessageCollector(CreateBatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider, TracerProvider tracerProvider, MessageSerializer serializer) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.contextProvider = contextProvider; this.tracerProvider = tracerProvider; this.serializer = serializer; currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer); } @Override public Supplier<List<ServiceBusMessageBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() { return (list, event) -> { ServiceBusMessageBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<ServiceBusMessageBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() { return list -> { ServiceBusMessageBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
class ServiceBusSenderAsyncClient implements AutoCloseable { /** * The default maximum allowable size, in bytes, for a batch to be sent. */ static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024; private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions(); private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final AmqpRetryOptions retryOptions; private final AmqpRetryPolicy retryPolicy; private final MessagingEntityType entityType; private final Runnable onClientClose; private final String entityName; private final ServiceBusConnectionProcessor connectionProcessor; /** * Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to a Service Bus entity. */ ServiceBusSenderAsyncClient(String entityName, MessagingEntityType entityType, ServiceBusConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) { this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = tracerProvider; this.retryPolicy = getRetryPolicy(retryOptions); this.entityType = entityType; this.onClientClose = onClientClose; } /** * Gets the fully qualified namespace. * * @return The fully qualified namespace. */ public String getFullyQualifiedNamespace() { return connectionProcessor.getFullyQualifiedNamespace(); } /** * Gets the name of the Service Bus resource. * * @return The name of the Service Bus resource. */ public String getEntityPath() { return entityName; } /** * Sends a message to a Service Bus queue or topic. * * @param message Message to be sent to Service Bus queue or topic. * * @return The {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code message} is {@code null}. */ public Mono<Void> send(ServiceBusMessage message) { if (Objects.isNull(message)) { return monoError(logger, new NullPointerException("'message' cannot be null.")); } return sendInternal(Flux.just(message)); } /** * Sends a set of messages to a Service Bus queue or topic using a batched approach. If the size of messages * exceed the maximum size of a single batch, an exception will be triggered and the send will fail. * By default, the message size is the max amount allowed on the link. * * @param messages Messages to be sent to Service Bus queue or topic. * * @return A {@link Mono} that completes when all messages have been sent to the Service Bus resource. * * @throws NullPointerException if {@code messages} is {@code null}. * @throws AmqpException if {@code messages} is larger than the maximum allowed size of a single batch. */ /** * Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows. * * @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows. */ public Mono<ServiceBusMessageBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link ServiceBusMessageBatch} configured with the options specified. * * @param options A set of options used to configure the {@link ServiceBusMessageBatch}. * @return A new {@link ServiceBusMessageBatch} configured with the given options. * @throws NullPointerException if {@code options} is null. */ public Mono<ServiceBusMessageBatch> createBatch(CreateBatchOptions options) { if (Objects.isNull(options)) { return monoError(logger, new NullPointerException("'options' cannot be null.")); } final int maxSize = options.getMaximumSizeInBytes(); return getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (maxSize > maximumLinkSize) { return monoError(logger, new IllegalArgumentException(String.format(Locale.US, "CreateBatchOptions.getMaximumSizeInBytes (%s bytes) is larger than the link size" + " (%s bytes).", maxSize, maximumLinkSize))); } final int batchSize = maxSize > 0 ? maxSize : maximumLinkSize; return Mono.just( new ServiceBusMessageBatch(batchSize, link::getErrorContext, tracerProvider, messageSerializer)); })); } /** * Sends a message batch to the Azure Service Bus entity this sender is connected to. * * @param batch of messages which allows client to send maximum allowed size for a batch of messages. * * @return A {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code batch} is {@code null}. */ public Mono<Void> send(ServiceBusMessageBatch batch) { if (Objects.isNull(batch)) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } final boolean isTracingEnabled = tracerProvider.isEnabled(); final AtomicReference<Context> parentContext = isTracingEnabled ? new AtomicReference<>(Context.NONE) : null; if (batch.getMessages().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } logger.info("Sending batch with size[{}].", batch.getCount()); Context sharedContext = null; final List<org.apache.qpid.proton.message.Message> messages = new ArrayList<>(); for (int i = 0; i < batch.getMessages().size(); i++) { final ServiceBusMessage event = batch.getMessages().get(i); if (isTracingEnabled) { parentContext.set(event.getContext()); if (i == 0) { sharedContext = tracerProvider.getSharedSpanBuilder(parentContext.get()); } tracerProvider.addSpanLinks(sharedContext.addData(SPAN_CONTEXT_KEY, event.getContext())); } final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(event); final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); message.setMessageAnnotations(messageAnnotations); messages.add(message); } final Context finalSharedContext = sharedContext != null ? sharedContext : Context.NONE; return withRetry( getSendLink().flatMap(link -> { if (isTracingEnabled) { Context entityContext = finalSharedContext.addData(ENTITY_PATH_KEY, link.getEntityPath()); parentContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME_KEY, link.getHostname()), ProcessKind.SEND)); } return messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages); }) .doOnEach(signal -> { if (isTracingEnabled) { tracerProvider.endSpan(parentContext.get(), signal); } }) .doOnError(error -> { if (isTracingEnabled) { tracerProvider.endSpan(parentContext.get(), Signal.error(error)); } }), retryOptions.getTryTimeout(), retryPolicy); } /** * Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is * enqueued and made available to receivers only at the scheduled enqueue time. * * @param message Message to be sent to the Service Bus Queue. * @param scheduledEnqueueTime Instant at which the message should appear in the Service Bus queue or topic. * * @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message. * * @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}. */ public Mono<Long> scheduleMessage(ServiceBusMessage message, Instant scheduledEnqueueTime) { if (Objects.isNull(message)) { return monoError(logger, new NullPointerException("'message' cannot be null.")); } if (Objects.isNull(scheduledEnqueueTime)) { return monoError(logger, new NullPointerException("'scheduledEnqueueTime' cannot be null.")); } return getSendLink() .flatMap(link -> link.getLinkSize().flatMap(size -> { int maxSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName, entityType)) .flatMap(managementNode -> managementNode.schedule(message, scheduledEnqueueTime, maxSize)); })); } /** * Cancels the enqueuing of an already scheduled message, if it was not already enqueued. * * @param sequenceNumber of the scheduled message to cancel. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws IllegalArgumentException if {@code sequenceNumber} is negative. */ public Mono<Void> cancelScheduledMessage(long sequenceNumber) { if (sequenceNumber < 0) { return monoError(logger, new IllegalArgumentException("'sequenceNumber' cannot be negative.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName, entityType)) .flatMap(managementNode -> managementNode.cancelScheduledMessage(sequenceNumber)); } /** * Disposes of the {@link ServiceBusSenderAsyncClient}. If the client had a dedicated connection, the underlying * connection is also closed. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } onClientClose.run(); } private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages) { return getSendLink() .flatMap(link -> link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final CreateBatchOptions batchOptions = new CreateBatchOptions() .setMaximumSizeInBytes(batchSize); return messages.collect(new AmqpMessageCollector(batchOptions, 1, link::getErrorContext, tracerProvider, messageSerializer)); }) .flatMap(list -> sendInternalBatch(Flux.fromIterable(list)))); } private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private Mono<AmqpSendLink> getSendLink() { return connectionProcessor .flatMap(connection -> connection.createSendLink(entityName, entityName, retryOptions)); } private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> { private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private final TracerProvider tracerProvider; private final MessageSerializer serializer; private volatile ServiceBusMessageBatch currentBatch; AmqpMessageCollector(CreateBatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider, TracerProvider tracerProvider, MessageSerializer serializer) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.contextProvider = contextProvider; this.tracerProvider = tracerProvider; this.serializer = serializer; currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer); } @Override public Supplier<List<ServiceBusMessageBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() { return (list, event) -> { ServiceBusMessageBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<ServiceBusMessageBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() { return list -> { ServiceBusMessageBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
Should we remove "either of them" since the list of credentials we try can be more than 2?
public Mono<AccessToken> getToken(TokenRequestContext request) { AtomicReference<Throwable> cause = new AtomicReference<>(); List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for either of them" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }
+ " environment for either of them"
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for the credentials" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
nit: don't need to specify concurrency as 1 for flatmap. It's 1 by default.
public Mono<AccessToken> getToken(TokenRequestContext request) { AtomicReference<Throwable> cause = new AtomicReference<>(); List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for either of them" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }
}), 1)
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for the credentials" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
That's not true. Default concurrency is computed via: Math.max(16, Integer.parseInt(System.getProperty("reactor.bufferSize.small", "256")));
public Mono<AccessToken> getToken(TokenRequestContext request) { AtomicReference<Throwable> cause = new AtomicReference<>(); List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for either of them" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }
}), 1)
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for the credentials" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
```suggestion System.out.printf("HttpClient is %s; Service Version is %s", httpClient, serviceVersion); ```
static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(CertificateServiceVersion.values()).filter( CertificateClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> { argumentsList.add(Arguments.of(httpClient, serviceVersion)); System.out.println("-----------------------------------------------------------"); System.out.println(httpClient); System.out.println(serviceVersion); System.out.println("-----------------------------------------------------------"); }); }); return argumentsList.stream(); }
System.out.println(serviceVersion);
static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(CertificateServiceVersion.values()).filter( CertificateClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> { argumentsList.add(Arguments.of(httpClient, serviceVersion)); }); }); return argumentsList.stream(); }
class CertificateClientTestBase extends TestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS); private static final String AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL = "ALL"; @Override protected String getTestName() { return ""; } void beforeTestSetup() { } HttpPipeline getHttpPipeline(HttpClient httpClient, CertificateServiceVersion serviceVersion) { TokenCredential credential = null; if (!interceptorManager.isPlaybackMode()) { String clientId = System.getenv("ARM_CLIENTID"); String clientKey = System.getenv("ARM_CLIENTKEY"); String tenantId = System.getenv("AZURE_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .build(); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone(), serviceVersion)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); if (credential != null) { policies.add(new BearerTokenAuthenticationPolicy(credential, CertificateAsyncClient.KEY_VAULT_SCOPE)); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (!interceptorManager.isPlaybackMode()) { policies.add(interceptorManager.getRecordPolicy()); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; } @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createCertificateRunner(Consumer<CertificatePolicy> testRunner) { final CertificatePolicy certificatePolicy = CertificatePolicy.getDefault(); testRunner.accept(certificatePolicy); } @Test public abstract void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertoificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateDisabledCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate4")); } @Test public abstract void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateSpecificVersionRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate9")); } @Test public abstract void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCert5")); } @Test public abstract void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getDeletedCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCert6")); } @Test public abstract void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void recoverDeletedKeyRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCert7")); } @Test public abstract void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void backupCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCert8")); } @Test public abstract void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void restoreCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate9")); } @Test public abstract void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate10")); } @Test public abstract void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void cancelCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate11")); } @Test public abstract void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate12")); } @Test public abstract void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate13")); } @Test public abstract void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate14")); } @Test public abstract void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = generateResourceId("listCertKey" + i); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createIssuereRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(generateResourceId("testIssuer01")); testRunner.accept(certificateIssuer); } @Test public abstract void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(generateResourceId("testIssuer02")); testRunner.accept(certificateIssuer); } @Test public abstract void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(generateResourceId("testIssuer03")); testRunner.accept(certificateIssuer); } @Test public abstract void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateIssuersRunner(Consumer<HashMap<String, CertificateIssuer>> testRunner) { HashMap<String, CertificateIssuer> certificateIssuers = new HashMap<>(); String certificateIssuerName; for (int i = 0; i < 10; i++) { certificateIssuerName = generateResourceId("listCertIssuer" + i); certificateIssuers.put(certificateIssuerName, setupIssuer(certificateIssuerName)); } testRunner.accept(certificateIssuers); } @Test public abstract void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateOperatioNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); CertificateContact setupContact() { return new CertificateContact().setName("name").setEmail("first.last@gmail.com").setPhone("2323-31232"); } Boolean validateContact(CertificateContact expected, CertificateContact actual) { return expected.getEmail().equals(actual.getEmail()) && expected.getName().equals(actual.getName()) && expected.getPhone().equals(actual.getPhone()); } @Test public abstract void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateVersionsRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName = generateResourceId("listCertVersionTest"); for (int i = 1; i < 5; i++) { certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listDeletedCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 3; i++) { certificateName = generateResourceId("listDeletedCertificate" + i); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void importCertificateRunner(Consumer<ImportCertificateOptions> testRunner) { String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO String certificatePassword = "123"; String certificateName = generateResourceId("importCertPkcs"); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, Base64.getDecoder().decode(certificateContent)) .setPassword(certificatePassword) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = generateResourceId("importCertPem"); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); String pemCert = ""; BufferedReader br = new BufferedReader(new FileReader(pemPath)); try { String line; while ((line = br.readLine()) != null) { pemCert += line + "\n"; } } finally { br.close(); } return pemCert.getBytes(); } CertificateIssuer setupIssuer(String issuerName) { return new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact().setFirstName("first").setLastName("last").setEmail("first.last@hotmail.com").setPhone("12345"))) .setAccountId("issuerAccountId") .setEnabled(true) .setOrganizationId("orgId") .setPassword("test123"); } String toHexString(byte[] x5t) { if (x5t == null) { return ""; } StringBuilder hexString = new StringBuilder(); for (int i = 0; i < x5t.length; i++) { String hex = Integer.toHexString(0xFF & x5t[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString().replace("-", ""); } X509Certificate loadCerToX509Certificate(KeyVaultCertificateWithPolicy certificate) throws CertificateException, IOException { assertNotNull(certificate.getCer()); ByteArrayInputStream cerStream = new ByteArrayInputStream(certificate.getCer()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); cerStream.close(); return x509Certificate; } Boolean validateIssuer(CertificateIssuer expected, CertificateIssuer actual) { return expected.getAccountId().equals(actual.getAccountId()) && expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } CertificatePolicy setupPolicy() { return new CertificatePolicy(WellKnownIssuerNames.SELF, "CN=default") .setKeyUsage(CertificateKeyUsage.KEY_CERT_SIGN, CertificateKeyUsage.KEY_AGREEMENT) .setContentType(CertificateContentType.PKCS12) .setExportable(true) .setKeyType(CertificateKeyType.EC) .setCertificateTransparent(false) .setEnabled(true) .setKeyCurveName(CertificateKeyCurveName.P_384) .setKeyReusable(true) .setValidityInMonths(24) .setLifetimeActions(new LifetimeAction(CertificatePolicyAction.AUTO_RENEW).setDaysBeforeExpiry(40)); } boolean validatePolicy(CertificatePolicy expected, CertificatePolicy actual) { return expected.getKeyType().equals(actual.getKeyType()) && expected.getContentType().equals(actual.getContentType()) && actual.getCreatedOn() != null && expected.getIssuerName().equals(actual.getIssuerName()) && expected.getKeyCurveName().equals(actual.getKeyCurveName()) && expected.isExportable().equals(actual.isExportable()) && expected.isCertificateTransparent().equals(actual.isCertificateTransparent()) && expected.isEnabled().equals(actual.isEnabled()) && expected.isKeyReusable().equals(actual.isKeyReusable()) && expected.getValidityInMonths().equals(actual.getValidityInMonths()) && expected.getLifetimeActions().size() == actual.getLifetimeActions().size() && expected.getKeyUsage().size() == actual.getKeyUsage().size(); } boolean validateCertificate(KeyVaultCertificate expected, KeyVaultCertificate actual) { return expected.getId().equals(actual.getId()) && expected.getKeyId().equals(actual.getKeyId()) && expected.getName().equals(actual.getName()) && expected.getSecretId().equals(actual.getSecretId()) && expected.getProperties().getVersion().equals(actual.getProperties().getVersion()) && expected.getProperties().getCreatedOn().equals(actual.getProperties().getCreatedOn()) && expected.getProperties().getExpiresOn().equals(actual.getProperties().getExpiresOn()) && expected.getProperties().getRecoveryLevel().equals(actual.getProperties().getRecoveryLevel()) && expected.getProperties().getX509Thumbprint().length == actual.getProperties().getX509Thumbprint().length && expected.getCer().length == actual.getCer().length; } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "http: : System.getenv("AZURE_KEYVAULT_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } String generateResourceId(String suffix) { if (interceptorManager.isPlaybackMode()) { return suffix; } String id = UUID.randomUUID().toString(); return suffix.length() > 0 ? id + "-" + suffix : id; } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link CertificateServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(CertificateServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return CertificateServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
class CertificateClientTestBase extends TestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS); private static final String AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL = "ALL"; @Override protected String getTestName() { return ""; } void beforeTestSetup() { } HttpPipeline getHttpPipeline(HttpClient httpClient, CertificateServiceVersion serviceVersion) { TokenCredential credential = null; if (!interceptorManager.isPlaybackMode()) { String clientId = System.getenv("ARM_CLIENTID"); String clientKey = System.getenv("ARM_CLIENTKEY"); String tenantId = System.getenv("AZURE_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .build(); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone(), serviceVersion)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); if (credential != null) { policies.add(new BearerTokenAuthenticationPolicy(credential, CertificateAsyncClient.KEY_VAULT_SCOPE)); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (!interceptorManager.isPlaybackMode()) { policies.add(interceptorManager.getRecordPolicy()); } HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .build(); return pipeline; } @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createCertificateRunner(Consumer<CertificatePolicy> testRunner) { final CertificatePolicy certificatePolicy = CertificatePolicy.getDefault(); testRunner.accept(certificatePolicy); } @Test public abstract void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertoificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateDisabledCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate4")); } @Test public abstract void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateSpecificVersionRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate9")); } @Test public abstract void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCert5")); } @Test public abstract void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getDeletedCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCert6")); } @Test public abstract void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void recoverDeletedKeyRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCert7")); } @Test public abstract void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void backupCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCert8")); } @Test public abstract void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void restoreCertificateRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate9")); } @Test public abstract void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate10")); } @Test public abstract void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void cancelCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate11")); } @Test public abstract void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate12")); } @Test public abstract void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate13")); } @Test public abstract void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(generateResourceId("testCertificate14")); } @Test public abstract void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = generateResourceId("listCertKey" + i); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createIssuereRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(generateResourceId("testIssuer01")); testRunner.accept(certificateIssuer); } @Test public abstract void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(generateResourceId("testIssuer02")); testRunner.accept(certificateIssuer); } @Test public abstract void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(generateResourceId("testIssuer03")); testRunner.accept(certificateIssuer); } @Test public abstract void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateIssuersRunner(Consumer<HashMap<String, CertificateIssuer>> testRunner) { HashMap<String, CertificateIssuer> certificateIssuers = new HashMap<>(); String certificateIssuerName; for (int i = 0; i < 10; i++) { certificateIssuerName = generateResourceId("listCertIssuer" + i); certificateIssuers.put(certificateIssuerName, setupIssuer(certificateIssuerName)); } testRunner.accept(certificateIssuers); } @Test public abstract void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateOperatioNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); CertificateContact setupContact() { return new CertificateContact().setName("name").setEmail("first.last@gmail.com").setPhone("2323-31232"); } Boolean validateContact(CertificateContact expected, CertificateContact actual) { return expected.getEmail().equals(actual.getEmail()) && expected.getName().equals(actual.getName()) && expected.getPhone().equals(actual.getPhone()); } @Test public abstract void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateVersionsRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName = generateResourceId("listCertVersionTest"); for (int i = 1; i < 5; i++) { certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listDeletedCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 3; i++) { certificateName = generateResourceId("listDeletedCertificate" + i); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void importCertificateRunner(Consumer<ImportCertificateOptions> testRunner) { String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YSd0fIT3U0A5NLEvJ9rfkx6JiHjRLx6V1tqsrtT6BsGtmCQR1UCJPLqsKVDvAINx3cPA/CGqr5OX2BGZlAihGmN6n7gv8w4O0k0LPTAe5YefgXN3m9pE867N31GtHVZaJ/UVgDNYS2jused4rw76ZWN41akx2QN0JSeMJqHXqVz6AKfz8ICS/dFnEGyBNpXiMRxrY/QPKi/wONwqsbDxRW7vZRVKs78pBkE0ksaShlZk5GkeayDWC/7Hi/NqUFtIloK9XB3paLxo1DGu5qqaF34jZdktzkXp0uZqpp+FfKZaiovMjt8F7yHCPk+LYpRsU2Cyc9DVoDA6rIgf+uEP4jppgehsxyT0lJHax2t869R2jYdsXwYUXjgwHIV0voj7bJYPGFlFjXOp6ZW86scsHM5xfsGQoK2Fp838VT34SHE1ZXU/puM7rviREHYW72pfpgGZUILQMohuTPnd8tFtAkbrmjLDo+k9xx7HUvgoFTiNNWuq/cRjr70FKNguMMTIrid+HwfmbRoaxENWdLcOTNeascER2a+37UQolKD5ksrPJG6RdNA7O2pzp3micDYRs/+s28cCIxO String certificatePassword = "123"; String certificateName = generateResourceId("importCertPkcs"); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, Base64.getDecoder().decode(certificateContent)) .setPassword(certificatePassword) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = generateResourceId("importCertPem"); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); String pemCert = ""; BufferedReader br = new BufferedReader(new FileReader(pemPath)); try { String line; while ((line = br.readLine()) != null) { pemCert += line + "\n"; } } finally { br.close(); } return pemCert.getBytes(); } CertificateIssuer setupIssuer(String issuerName) { return new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact().setFirstName("first").setLastName("last").setEmail("first.last@hotmail.com").setPhone("12345"))) .setAccountId("issuerAccountId") .setEnabled(true) .setOrganizationId("orgId") .setPassword("test123"); } String toHexString(byte[] x5t) { if (x5t == null) { return ""; } StringBuilder hexString = new StringBuilder(); for (int i = 0; i < x5t.length; i++) { String hex = Integer.toHexString(0xFF & x5t[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString().replace("-", ""); } X509Certificate loadCerToX509Certificate(KeyVaultCertificateWithPolicy certificate) throws CertificateException, IOException { assertNotNull(certificate.getCer()); ByteArrayInputStream cerStream = new ByteArrayInputStream(certificate.getCer()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); cerStream.close(); return x509Certificate; } Boolean validateIssuer(CertificateIssuer expected, CertificateIssuer actual) { return expected.getAccountId().equals(actual.getAccountId()) && expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } CertificatePolicy setupPolicy() { return new CertificatePolicy(WellKnownIssuerNames.SELF, "CN=default") .setKeyUsage(CertificateKeyUsage.KEY_CERT_SIGN, CertificateKeyUsage.KEY_AGREEMENT) .setContentType(CertificateContentType.PKCS12) .setExportable(true) .setKeyType(CertificateKeyType.EC) .setCertificateTransparent(false) .setEnabled(true) .setKeyCurveName(CertificateKeyCurveName.P_384) .setKeyReusable(true) .setValidityInMonths(24) .setLifetimeActions(new LifetimeAction(CertificatePolicyAction.AUTO_RENEW).setDaysBeforeExpiry(40)); } boolean validatePolicy(CertificatePolicy expected, CertificatePolicy actual) { return expected.getKeyType().equals(actual.getKeyType()) && expected.getContentType().equals(actual.getContentType()) && actual.getCreatedOn() != null && expected.getIssuerName().equals(actual.getIssuerName()) && expected.getKeyCurveName().equals(actual.getKeyCurveName()) && expected.isExportable().equals(actual.isExportable()) && expected.isCertificateTransparent().equals(actual.isCertificateTransparent()) && expected.isEnabled().equals(actual.isEnabled()) && expected.isKeyReusable().equals(actual.isKeyReusable()) && expected.getValidityInMonths().equals(actual.getValidityInMonths()) && expected.getLifetimeActions().size() == actual.getLifetimeActions().size() && expected.getKeyUsage().size() == actual.getKeyUsage().size(); } boolean validateCertificate(KeyVaultCertificate expected, KeyVaultCertificate actual) { return expected.getId().equals(actual.getId()) && expected.getKeyId().equals(actual.getKeyId()) && expected.getName().equals(actual.getName()) && expected.getSecretId().equals(actual.getSecretId()) && expected.getProperties().getVersion().equals(actual.getProperties().getVersion()) && expected.getProperties().getCreatedOn().equals(actual.getProperties().getCreatedOn()) && expected.getProperties().getExpiresOn().equals(actual.getProperties().getExpiresOn()) && expected.getProperties().getRecoveryLevel().equals(actual.getProperties().getRecoveryLevel()) && expected.getProperties().getX509Thumbprint().length == actual.getProperties().getX509Thumbprint().length && expected.getCer().length == actual.getCer().length; } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "http: : System.getenv("AZURE_KEYVAULT_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } String generateResourceId(String suffix) { if (interceptorManager.isPlaybackMode()) { return suffix; } String id = UUID.randomUUID().toString(); return suffix.length() > 0 ? id + "-" + suffix : id; } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link CertificateServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(CertificateServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return CertificateServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } }
nit: completed -> Completed
public void afterTestExecution(ExtensionContext context) { Method testMethod = context.getRequiredTestMethod(); long start = getStore(context).remove(testMethod, long.class); long duration = System.currentTimeMillis() - start; System.out.printf("completed in %d ms.%n", duration); }
System.out.printf("completed in %d ms.%n", duration);
public void afterTestExecution(ExtensionContext context) { TestInformation testInformation = getStore(context) .remove(context.getRequiredTestMethod(), TestInformation.class); long duration = System.currentTimeMillis() - testInformation.startMillis; System.out.printf("%s completed in %d ms.%n", testInformation.logPrefix, duration); }
class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback { @Override public void beforeTestExecution(ExtensionContext extensionContext) { String displayName = extensionContext.getDisplayName(); getStore(extensionContext).put(extensionContext.getRequiredTestMethod(), System.currentTimeMillis()); String testName = ""; String fullyQualifiedTestName = ""; if (extensionContext.getTestMethod().isPresent()) { Method method = extensionContext.getTestMethod().get(); testName = method.getName(); fullyQualifiedTestName = method.getDeclaringClass().getName() + "." + testName; } if (!Objects.equals(displayName, testName)) { System.out.printf("Starting test %s (%s), ", fullyQualifiedTestName, displayName); } else { System.out.printf("Starting test %s, ", fullyQualifiedTestName); } } @Override private ExtensionContext.Store getStore(ExtensionContext context) { return context.getStore(ExtensionContext.Namespace.create(getClass(), context)); } }
class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback { @Override public void beforeTestExecution(ExtensionContext extensionContext) { String displayName = extensionContext.getDisplayName(); String testName = ""; String fullyQualifiedTestName = ""; if (extensionContext.getTestMethod().isPresent()) { Method method = extensionContext.getTestMethod().get(); testName = method.getName(); fullyQualifiedTestName = method.getDeclaringClass().getName() + "." + testName; } StringBuilder logPrefixBuilder = new StringBuilder("Starting test ") .append(fullyQualifiedTestName); if (!Objects.equals(displayName, testName)) { logPrefixBuilder.append("(") .append(displayName) .append(")"); } logPrefixBuilder.append(","); getStore(extensionContext).put(extensionContext.getRequiredTestMethod(), new TestInformation(logPrefixBuilder.toString(), System.currentTimeMillis())); } @Override private static ExtensionContext.Store getStore(ExtensionContext context) { return context.getStore(ExtensionContext.Namespace.create(AzureTestWatcher.class, context)); } private static final class TestInformation { private final String logPrefix; private final long startMillis; private TestInformation(String logPrefix, long startMillis) { this.logPrefix = logPrefix; this.startMillis = startMillis; } } }
Do you need a `%n` for these too?
public void beforeTestExecution(ExtensionContext extensionContext) { String displayName = extensionContext.getDisplayName(); getStore(extensionContext).put(extensionContext.getRequiredTestMethod(), System.currentTimeMillis()); String testName = ""; String fullyQualifiedTestName = ""; if (extensionContext.getTestMethod().isPresent()) { Method method = extensionContext.getTestMethod().get(); testName = method.getName(); fullyQualifiedTestName = method.getDeclaringClass().getName() + "." + testName; } if (!Objects.equals(displayName, testName)) { System.out.printf("Starting test %s (%s), ", fullyQualifiedTestName, displayName); } else { System.out.printf("Starting test %s, ", fullyQualifiedTestName); } }
System.out.printf("Starting test %s (%s), ", fullyQualifiedTestName, displayName);
public void beforeTestExecution(ExtensionContext extensionContext) { String displayName = extensionContext.getDisplayName(); String testName = ""; String fullyQualifiedTestName = ""; if (extensionContext.getTestMethod().isPresent()) { Method method = extensionContext.getTestMethod().get(); testName = method.getName(); fullyQualifiedTestName = method.getDeclaringClass().getName() + "." + testName; } StringBuilder logPrefixBuilder = new StringBuilder("Starting test ") .append(fullyQualifiedTestName); if (!Objects.equals(displayName, testName)) { logPrefixBuilder.append("(") .append(displayName) .append(")"); } logPrefixBuilder.append(","); getStore(extensionContext).put(extensionContext.getRequiredTestMethod(), new TestInformation(logPrefixBuilder.toString(), System.currentTimeMillis())); }
class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback { @Override @Override public void afterTestExecution(ExtensionContext context) { Method testMethod = context.getRequiredTestMethod(); long start = getStore(context).remove(testMethod, long.class); long duration = System.currentTimeMillis() - start; System.out.printf("completed in %d ms.%n", duration); } private ExtensionContext.Store getStore(ExtensionContext context) { return context.getStore(ExtensionContext.Namespace.create(getClass(), context)); } }
class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback { @Override @Override public void afterTestExecution(ExtensionContext context) { TestInformation testInformation = getStore(context) .remove(context.getRequiredTestMethod(), TestInformation.class); long duration = System.currentTimeMillis() - testInformation.startMillis; System.out.printf("%s completed in %d ms.%n", testInformation.logPrefix, duration); } private static ExtensionContext.Store getStore(ExtensionContext context) { return context.getStore(ExtensionContext.Namespace.create(AzureTestWatcher.class, context)); } private static final class TestInformation { private final String logPrefix; private final long startMillis; private TestInformation(String logPrefix, long startMillis) { this.logPrefix = logPrefix; this.startMillis = startMillis; } } }
The idea was that this and the other print statement would form a single line. Test begins, console view: `Starting test {qualified name} ({display name})` Test completes, console view: `Starting test {qualified name} ({display name}), completed in {millis} ms.{newline}`.
public void afterTestExecution(ExtensionContext context) { Method testMethod = context.getRequiredTestMethod(); long start = getStore(context).remove(testMethod, long.class); long duration = System.currentTimeMillis() - start; System.out.printf("completed in %d ms.%n", duration); }
System.out.printf("completed in %d ms.%n", duration);
public void afterTestExecution(ExtensionContext context) { TestInformation testInformation = getStore(context) .remove(context.getRequiredTestMethod(), TestInformation.class); long duration = System.currentTimeMillis() - testInformation.startMillis; System.out.printf("%s completed in %d ms.%n", testInformation.logPrefix, duration); }
class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback { @Override public void beforeTestExecution(ExtensionContext extensionContext) { String displayName = extensionContext.getDisplayName(); getStore(extensionContext).put(extensionContext.getRequiredTestMethod(), System.currentTimeMillis()); String testName = ""; String fullyQualifiedTestName = ""; if (extensionContext.getTestMethod().isPresent()) { Method method = extensionContext.getTestMethod().get(); testName = method.getName(); fullyQualifiedTestName = method.getDeclaringClass().getName() + "." + testName; } if (!Objects.equals(displayName, testName)) { System.out.printf("Starting test %s (%s), ", fullyQualifiedTestName, displayName); } else { System.out.printf("Starting test %s, ", fullyQualifiedTestName); } } @Override private ExtensionContext.Store getStore(ExtensionContext context) { return context.getStore(ExtensionContext.Namespace.create(getClass(), context)); } }
class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback { @Override public void beforeTestExecution(ExtensionContext extensionContext) { String displayName = extensionContext.getDisplayName(); String testName = ""; String fullyQualifiedTestName = ""; if (extensionContext.getTestMethod().isPresent()) { Method method = extensionContext.getTestMethod().get(); testName = method.getName(); fullyQualifiedTestName = method.getDeclaringClass().getName() + "." + testName; } StringBuilder logPrefixBuilder = new StringBuilder("Starting test ") .append(fullyQualifiedTestName); if (!Objects.equals(displayName, testName)) { logPrefixBuilder.append("(") .append(displayName) .append(")"); } logPrefixBuilder.append(","); getStore(extensionContext).put(extensionContext.getRequiredTestMethod(), new TestInformation(logPrefixBuilder.toString(), System.currentTimeMillis())); } @Override private static ExtensionContext.Store getStore(ExtensionContext context) { return context.getStore(ExtensionContext.Namespace.create(AzureTestWatcher.class, context)); } private static final class TestInformation { private final String logPrefix; private final long startMillis; private TestInformation(String logPrefix, long startMillis) { this.logPrefix = logPrefix; this.startMillis = startMillis; } } }
constants code?
public void deserialization() throws IOException { final String errorBody = "{\"error\":{\"code\":\"ResourceGroupNotFound\",\"message\":\"Resource group 'rg-not-exist' could not be found.\"}}"; AzureJacksonAdapter serializerAdapter = new AzureJacksonAdapter(); CloudError cloudError = serializerAdapter.deserialize(errorBody, CloudError.class, SerializerEncoding.JSON); Assertions.assertEquals("ResourceGroupNotFound", cloudError.getCode()); }
final String errorBody = "{\"error\":{\"code\":\"ResourceGroupNotFound\",\"message\":\"Resource group 'rg-not-exist' could not be found.\"}}";
public void deserialization() throws IOException { final String errorBody = "{\"error\":{\"code\":\"ResourceGroupNotFound\",\"message\":\"Resource group 'rg-not-exist' could not be found.\"}}"; AzureJacksonAdapter serializerAdapter = new AzureJacksonAdapter(); CloudError cloudError = serializerAdapter.deserialize(errorBody, CloudError.class, SerializerEncoding.JSON); Assertions.assertEquals("ResourceGroupNotFound", cloudError.getCode()); }
class CloudExceptionTests { @Test }
class CloudExceptionTests { @Test }
A sample response from ARM. Java does not have constants, so `final` should be all?
public void deserialization() throws IOException { final String errorBody = "{\"error\":{\"code\":\"ResourceGroupNotFound\",\"message\":\"Resource group 'rg-not-exist' could not be found.\"}}"; AzureJacksonAdapter serializerAdapter = new AzureJacksonAdapter(); CloudError cloudError = serializerAdapter.deserialize(errorBody, CloudError.class, SerializerEncoding.JSON); Assertions.assertEquals("ResourceGroupNotFound", cloudError.getCode()); }
final String errorBody = "{\"error\":{\"code\":\"ResourceGroupNotFound\",\"message\":\"Resource group 'rg-not-exist' could not be found.\"}}";
public void deserialization() throws IOException { final String errorBody = "{\"error\":{\"code\":\"ResourceGroupNotFound\",\"message\":\"Resource group 'rg-not-exist' could not be found.\"}}"; AzureJacksonAdapter serializerAdapter = new AzureJacksonAdapter(); CloudError cloudError = serializerAdapter.deserialize(errorBody, CloudError.class, SerializerEncoding.JSON); Assertions.assertEquals("ResourceGroupNotFound", cloudError.getCode()); }
class CloudExceptionTests { @Test }
class CloudExceptionTests { @Test }
This code can be replaced by `return str.matches("^[-_.a-zA-Z0-9]+$")`
private boolean isRefreshTokenString(String str) { for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'Z') && (ch < 'a' || ch > 'z') && ch != '_' && ch != '-' && ch != '.') { return false; } } return true; }
return true;
private boolean isRefreshTokenString(String str) { return REFRESH_TOKEN_PATTERN.matcher(str).matches(); }
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); /** * Creates an instance of {@link VisualStudioCacheAccessor} */ public VisualStudioCacheAccessor() { } private JsonNode getUserSettings() { JsonNode output = null; String homeDir = System.getProperty("user.home"); String settingsPath = ""; ObjectMapper mapper = new ObjectMapper(); try { if (Platform.isWindows()) { settingsPath = Paths.get(System.getenv("APPDATA"), "Code", "User", "settings.json") .toString(); } else if (Platform.isMac()) { settingsPath = Paths.get(homeDir, "Library", "Application Support", "Code", "User", "settings.json").toString(); } else if (Platform.isLinux()) { settingsPath = Paths.get(homeDir, ".config", "Code", "User", "settings.json") .toString(); } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } File settingsFile = new File(settingsPath); output = mapper.readTree(settingsFile); } catch (Exception e) { return null; } return output; } /** * Get the user configured settings of Visual Studio code. * * @param tenantId the user specified tenant id. * @return a Map containing Vs Code user settings */ public Map<String, String> getUserSettingsDetails(String tenantId) { JsonNode userSettings = getUserSettings(); Map<String, String> details = new HashMap<>(); String tenant = tenantId; String cloud = "Azure"; if (!userSettings.isNull()) { if (userSettings.has("azure.tenant") && CoreUtils.isNullOrEmpty(tenant)) { tenant = userSettings.get("azure.tenant").asText(); } if (userSettings.has("azure.cloud")) { cloud = userSettings.get("azure.cloud").asText(); } } details.put("tenant", tenant); details.put("cloud", cloud); return details; } /** * Get the credential for the specified service and account name. * * @param serviceName the name of the service to lookup. * @param accountName the account of the service to lookup. * @return the credential. */ public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (RuntimeException e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Windows Credential API.", e)); } } else if (Platform.isMac()) { try { KeyChainAccessor keyChainAccessor = new KeyChainAccessor(null, serviceName, accountName); byte[] readCreds = keyChainAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (RuntimeException e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Mac Native Key Chain.", e)); } } else if (Platform.isLinux()) { try { LinuxKeyRingAccessor keyRingAccessor = new LinuxKeyRingAccessor( "org.freedesktop.Secret.Generic", "service", serviceName, "account", accountName); byte[] readCreds = keyRingAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (RuntimeException e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Linux Key Ring.", e)); } } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } if (CoreUtils.isNullOrEmpty(credential) || !isRefreshTokenString(credential)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please authenticate via Azure Tools plugin in VS Code IDE.")); } return credential; } /** * Get the auth host of the specified {@code azureEnvironment}. * * @return the auth host. */ public String getAzureAuthHost(String cloud) { switch (cloud) { case "Azure": return KnownAuthorityHosts.AZURE_CLOUD; case "AzureChina": return KnownAuthorityHosts.AZURE_CHINA_CLOUD; case "AzureGermanCloud": return KnownAuthorityHosts.AZURE_GERMAN_CLOUD; case "AzureUSGovernment": return KnownAuthorityHosts.AZURE_US_GOVERNMENT; default: return KnownAuthorityHosts.AZURE_CLOUD; } } }
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern.compile("^[-_.a-zA-Z0-9]+$"); private JsonNode getUserSettings() { JsonNode output = null; String homeDir = System.getProperty("user.home"); String settingsPath = ""; ObjectMapper mapper = new ObjectMapper(); try { if (Platform.isWindows()) { settingsPath = Paths.get(System.getenv("APPDATA"), "Code", "User", "settings.json") .toString(); } else if (Platform.isMac()) { settingsPath = Paths.get(homeDir, "Library", "Application Support", "Code", "User", "settings.json").toString(); } else if (Platform.isLinux()) { settingsPath = Paths.get(homeDir, ".config", "Code", "User", "settings.json") .toString(); } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } File settingsFile = new File(settingsPath); output = mapper.readTree(settingsFile); } catch (Exception e) { return null; } return output; } /** * Get the user configured settings of Visual Studio code. * * @param tenantId the user specified tenant id. * @return a Map containing Vs Code user settings */ public Map<String, String> getUserSettingsDetails(String tenantId) { JsonNode userSettings = getUserSettings(); Map<String, String> details = new HashMap<>(); String tenant = tenantId; String cloud = "Azure"; if (userSettings != null && !userSettings.isNull()) { if (userSettings.has("azure.tenant") && CoreUtils.isNullOrEmpty(tenant)) { tenant = userSettings.get("azure.tenant").asText(); } if (userSettings.has("azure.cloud")) { cloud = userSettings.get("azure.cloud").asText(); } } details.put("tenant", tenant); details.put("cloud", cloud); return details; } /** * Get the credential for the specified service and account name. * * @param serviceName the name of the service to lookup. * @param accountName the account of the service to lookup. * @return the credential. */ public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (RuntimeException e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Windows Credential API.", e)); } } else if (Platform.isMac()) { try { KeyChainAccessor keyChainAccessor = new KeyChainAccessor(null, serviceName, accountName); byte[] readCreds = keyChainAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (RuntimeException e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Mac Native Key Chain.", e)); } } else if (Platform.isLinux()) { try { LinuxKeyRingAccessor keyRingAccessor = new LinuxKeyRingAccessor( "org.freedesktop.Secret.Generic", "service", serviceName, "account", accountName); byte[] readCreds = keyRingAccessor.read(); credential = new String(readCreds, StandardCharsets.UTF_8); } catch (RuntimeException e) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Failed to read Vs Code credentials from Linux Key Ring.", e)); } } else { throw logger.logExceptionAsError( new CredentialUnavailableException(PLATFORM_NOT_SUPPORTED_ERROR)); } if (CoreUtils.isNullOrEmpty(credential) || !isRefreshTokenString(credential)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please authenticate via Azure Tools plugin in VS Code IDE.")); } return credential; } /** * Get the auth host of the specified {@code azureEnvironment}. * * @return the auth host. */ public String getAzureAuthHost(String cloud) { switch (cloud) { case "Azure": return KnownAuthorityHosts.AZURE_CLOUD; case "AzureChina": return KnownAuthorityHosts.AZURE_CHINA_CLOUD; case "AzureGermanCloud": return KnownAuthorityHosts.AZURE_GERMAN_CLOUD; case "AzureUSGovernment": return KnownAuthorityHosts.AZURE_US_GOVERNMENT; default: return KnownAuthorityHosts.AZURE_CLOUD; } } }
why `parent()`? maybe only delete this line?
public Mono<T> getByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() == null) { return null; } return getByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); }
if (resourceId.parent() == null) {
public Mono<T> getByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() == null) { return null; } return getByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); }
class IndependentChildrenImpl< T extends IndependentChild<ManagerT>, ImplT extends T, InnerT, InnerCollectionT, ManagerT extends ManagerBase, ParentT extends Resource & HasResourceGroup> extends CreatableResourcesImpl<T, ImplT, InnerT> implements SupportsGettingById<T>, SupportsGettingByParent<T, ParentT, ManagerT>, SupportsListingByParent<T, ParentT, ManagerT>, SupportsDeletingByParent, HasManager<ManagerT>, HasInner<InnerCollectionT> { protected final InnerCollectionT innerCollection; protected final ManagerT manager; protected IndependentChildrenImpl(InnerCollectionT innerCollection, ManagerT manager) { this.innerCollection = innerCollection; this.manager = manager; } @Override public InnerCollectionT inner() { return this.innerCollection; } @Override public T getByParent(String resourceGroup, String parentName, String name) { return getByParentAsync(resourceGroup, parentName, name).block(); } @Override public T getByParent(ParentT parentResource, String name) { return getByParentAsync(parentResource, name).block(); } @Override public Mono<T> getByParentAsync(ParentT parentResource, String name) { return getByParentAsync(parentResource.resourceGroupName(), parentResource.name(), name); } @Override public T getById(String id) { return getByIdAsync(id).block(); } @Override @Override public PagedIterable<T> listByParent(ParentT parentResource) { return listByParent(parentResource.resourceGroupName(), parentResource.name()); } @Override public void deleteByParent(String groupName, String parentName, String name) { deleteByParentAsync(groupName, parentName, name).block(); } @Override public Mono<Void> deleteByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); return deleteByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override public ManagerT manager() { return this.manager; } }
class IndependentChildrenImpl< T extends IndependentChild<ManagerT>, ImplT extends T, InnerT, InnerCollectionT, ManagerT extends ManagerBase, ParentT extends Resource & HasResourceGroup> extends CreatableResourcesImpl<T, ImplT, InnerT> implements SupportsGettingById<T>, SupportsGettingByParent<T, ParentT, ManagerT>, SupportsListingByParent<T, ParentT, ManagerT>, SupportsDeletingByParent, HasManager<ManagerT>, HasInner<InnerCollectionT> { protected final InnerCollectionT innerCollection; protected final ManagerT manager; protected IndependentChildrenImpl(InnerCollectionT innerCollection, ManagerT manager) { this.innerCollection = innerCollection; this.manager = manager; } @Override public InnerCollectionT inner() { return this.innerCollection; } @Override public T getByParent(String resourceGroup, String parentName, String name) { return getByParentAsync(resourceGroup, parentName, name).block(); } @Override public T getByParent(ParentT parentResource, String name) { return getByParentAsync(parentResource, name).block(); } @Override public Mono<T> getByParentAsync(ParentT parentResource, String name) { return getByParentAsync(parentResource.resourceGroupName(), parentResource.name(), name); } @Override public T getById(String id) { return getByIdAsync(id).block(); } @Override @Override public PagedIterable<T> listByParent(ParentT parentResource) { return listByParent(parentResource.resourceGroupName(), parentResource.name()); } @Override public void deleteByParent(String groupName, String parentName, String name) { deleteByParentAsync(groupName, parentName, name).block(); } @Override public Mono<Void> deleteByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); return deleteByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override public ManagerT manager() { return this.manager; } }
Since the next line has `resourceId.parent().name()`, so I add `parent()` in it. Is it better not to check this NPE?
public Mono<T> getByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() == null) { return null; } return getByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); }
if (resourceId.parent() == null) {
public Mono<T> getByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); if (resourceId.parent() == null) { return null; } return getByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); }
class IndependentChildrenImpl< T extends IndependentChild<ManagerT>, ImplT extends T, InnerT, InnerCollectionT, ManagerT extends ManagerBase, ParentT extends Resource & HasResourceGroup> extends CreatableResourcesImpl<T, ImplT, InnerT> implements SupportsGettingById<T>, SupportsGettingByParent<T, ParentT, ManagerT>, SupportsListingByParent<T, ParentT, ManagerT>, SupportsDeletingByParent, HasManager<ManagerT>, HasInner<InnerCollectionT> { protected final InnerCollectionT innerCollection; protected final ManagerT manager; protected IndependentChildrenImpl(InnerCollectionT innerCollection, ManagerT manager) { this.innerCollection = innerCollection; this.manager = manager; } @Override public InnerCollectionT inner() { return this.innerCollection; } @Override public T getByParent(String resourceGroup, String parentName, String name) { return getByParentAsync(resourceGroup, parentName, name).block(); } @Override public T getByParent(ParentT parentResource, String name) { return getByParentAsync(parentResource, name).block(); } @Override public Mono<T> getByParentAsync(ParentT parentResource, String name) { return getByParentAsync(parentResource.resourceGroupName(), parentResource.name(), name); } @Override public T getById(String id) { return getByIdAsync(id).block(); } @Override @Override public PagedIterable<T> listByParent(ParentT parentResource) { return listByParent(parentResource.resourceGroupName(), parentResource.name()); } @Override public void deleteByParent(String groupName, String parentName, String name) { deleteByParentAsync(groupName, parentName, name).block(); } @Override public Mono<Void> deleteByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); return deleteByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override public ManagerT manager() { return this.manager; } }
class IndependentChildrenImpl< T extends IndependentChild<ManagerT>, ImplT extends T, InnerT, InnerCollectionT, ManagerT extends ManagerBase, ParentT extends Resource & HasResourceGroup> extends CreatableResourcesImpl<T, ImplT, InnerT> implements SupportsGettingById<T>, SupportsGettingByParent<T, ParentT, ManagerT>, SupportsListingByParent<T, ParentT, ManagerT>, SupportsDeletingByParent, HasManager<ManagerT>, HasInner<InnerCollectionT> { protected final InnerCollectionT innerCollection; protected final ManagerT manager; protected IndependentChildrenImpl(InnerCollectionT innerCollection, ManagerT manager) { this.innerCollection = innerCollection; this.manager = manager; } @Override public InnerCollectionT inner() { return this.innerCollection; } @Override public T getByParent(String resourceGroup, String parentName, String name) { return getByParentAsync(resourceGroup, parentName, name).block(); } @Override public T getByParent(ParentT parentResource, String name) { return getByParentAsync(parentResource, name).block(); } @Override public Mono<T> getByParentAsync(ParentT parentResource, String name) { return getByParentAsync(parentResource.resourceGroupName(), parentResource.name(), name); } @Override public T getById(String id) { return getByIdAsync(id).block(); } @Override @Override public PagedIterable<T> listByParent(ParentT parentResource) { return listByParent(parentResource.resourceGroupName(), parentResource.name()); } @Override public void deleteByParent(String groupName, String parentName, String name) { deleteByParentAsync(groupName, parentName, name).block(); } @Override public Mono<Void> deleteByIdAsync(String id) { ResourceId resourceId = ResourceId.fromString(id); return deleteByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name()); } @Override public ManagerT manager() { return this.manager; } }
create/use a static final variable for the model id.
static CustomFormModel getExpectedUnlabeledModel() { Map<String, CustomFormModelField> fieldMap = new HashMap<String, CustomFormModelField>() { { put("field-0", new CustomFormModelField("field-0", "Address", null)); put("field-1", new CustomFormModelField("field-1", "Charges", null)); put("field-2", new CustomFormModelField("field-2", "Invoice Date", null)); put("field-3", new CustomFormModelField("field-3", "Invoice Due Date", null)); put("field-4", new CustomFormModelField("field-4", "Invoice For:", null)); put("field-5", new CustomFormModelField("field-5", "Invoice Number", null)); put("field-6", new CustomFormModelField("field-6", "Microsoft", null)); put("field-7", new CustomFormModelField("field-7", "Page", null)); put("field-8", new CustomFormModelField("field-8", "VAT ID", null)); } }; CustomFormSubModel customFormSubModel = new CustomFormSubModel(null, fieldMap, "form-0"); return new CustomFormModel("95537f1b-aac4-4da8-8292-f1b93ac4c8f8", CustomFormModelStatus.READY, OffsetDateTime.parse("2020-04-09T21:30:28Z"), OffsetDateTime.parse("2020-04-09T18:24:56Z"), new IterableStream<>(Collections.singletonList(customFormSubModel)), Collections.emptyList(), getExpectedTrainingDocuments()); }
return new CustomFormModel("95537f1b-aac4-4da8-8292-f1b93ac4c8f8", CustomFormModelStatus.READY,
static CustomFormModel getExpectedUnlabeledModel() { Map<String, CustomFormModelField> fieldMap = new HashMap<String, CustomFormModelField>() { { put("field-0", new CustomFormModelField("field-0", "Address", null)); put("field-1", new CustomFormModelField("field-1", "Charges", null)); put("field-2", new CustomFormModelField("field-2", "Invoice Date", null)); put("field-3", new CustomFormModelField("field-3", "Invoice Due Date", null)); put("field-4", new CustomFormModelField("field-4", "Invoice For:", null)); put("field-5", new CustomFormModelField("field-5", "Invoice Number", null)); put("field-6", new CustomFormModelField("field-6", "Microsoft", null)); put("field-7", new CustomFormModelField("field-7", "Page", null)); put("field-8", new CustomFormModelField("field-8", "VAT ID", null)); } }; CustomFormSubModel customFormSubModel = new CustomFormSubModel(null, fieldMap, "form-0"); return new CustomFormModel("95537f1b-aac4-4da8-8292-f1b93ac4c8f8", CustomFormModelStatus.READY, OffsetDateTime.parse("2020-04-09T21:30:28Z"), OffsetDateTime.parse("2020-04-09T18:24:56Z"), new IterableStream<>(Collections.singletonList(customFormSubModel)), Collections.emptyList(), getExpectedTrainingDocuments()); }
class TestUtils { static final String INVALID_MODEL_ID = "a0a3998a-4c4affe66b7"; static final String INVALID_STATUS_MODEL_ID = "22138c4e-c4b0-4901-a0e1-6c5beb73fc1d"; static final String INVALID_RECEIPT_URL = "https: static final String INVALID_SOURCE_URL_ERROR = "Status code 400, \"{\"error\":{\"code\":\"1003\"," + "\"message\":\"Parameter 'Source' is not a valid Uri.\"}}\""; static final String INVALID_MODEL_ID_ERROR = "Invalid UUID string: " + INVALID_MODEL_ID; static final String NULL_SOURCE_URL_ERROR = "'fileSourceUrl' cannot be null."; static final String INVALID_URL = "htttttttps: static final String LABELED_MODEL_ID = "a0a3998a-b3c0-4075-aa6b-c4c4affe66b7"; static final String VALID_HTTPS_LOCALHOST = "https: static final String RECEIPT_LOCAL_URL = "src/test/resources/sample_files/Test/contoso-allinone.jpg"; static final String LAYOUT_LOCAL_URL = "src/test/resources/sample_files/Test/layout1.jpg"; static final String FORM_LOCAL_URL = "src/test/resources/sample_files/Test/Invoice_6.pdf"; static final long RECEIPT_FILE_LENGTH = new File(RECEIPT_LOCAL_URL).length(); static final long LAYOUT_FILE_LENGTH = new File(LAYOUT_LOCAL_URL).length(); static final long CUSTOM_FORM_FILE_LENGTH = new File(FORM_LOCAL_URL).length(); static final String RECEIPT_URL = "https: + ".com/Azure/azure-sdk-for-java/master/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources" + "/sample-files/contoso-allinone.jpg"; static final String LAYOUT_URL = "https: + ".com/Azure/azure-sdk-for-java/master/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources" + "/sample-files/layout1.jpg"; private static final String CUSTOM_FORM_LABELED_DATA = "src/test/resources/sample_files/Content" + "/customFormLabeledContent.json"; private static final String CUSTOM_FORM_DATA = "src/test/resources/sample_files/Content/customFormContent.json"; private static final String RECEIPT_FORM_DATA = "src/test/resources/sample_files/Content/receiptContent.json"; private static final String LAYOUT_FORM_DATA = "src/test/resources/sample_files/Content/layoutContent.json"; private TestUtils() { } static AnalyzeOperationResult getRawResponse(String filePath) { String content; try { content = new String(Files.readAllBytes(Paths.get(filePath))); return getSerializerAdapter().deserialize(content, AnalyzeOperationResult.class, SerializerEncoding.JSON); } catch (IOException e) { e.printStackTrace(); } return null; } static List<List<FormTable>> getPagedTables() { List<PageResult> pageResults = getRawResponse(LAYOUT_FORM_DATA).getAnalyzeResult().getPageResults(); List<ReadResult> readResults = getRawResponse(LAYOUT_FORM_DATA).getAnalyzeResult().getReadResults(); return IntStream.range(0, pageResults.size()) .mapToObj(i -> Transforms.getPageTables(pageResults.get(i), readResults, i + 1)) .collect(Collectors.toList()); } static List<List<FormLine>> getPagedLines() { List<ReadResult> readResults = getRawResponse(LAYOUT_FORM_DATA).getAnalyzeResult().getReadResults(); return readResults.stream().map(Transforms::getReadResultFormLines).collect(Collectors.toList()); } static IterableStream<RecognizedReceipt> getRawExpectedReceipt(boolean includeTextDetails) { return toReceipt(getRawResponse(RECEIPT_FORM_DATA).getAnalyzeResult(), includeTextDetails); } static IterableStream<FormPage> getExpectedFormPages() { FormPage formPage = new FormPage(2200, 0, DimensionUnit.PIXEL, 1700, new IterableStream<FormLine>(getPagedLines().get(0)), new IterableStream<FormTable>(getPagedTables().get(0))); return new IterableStream<>(Collections.singletonList(formPage)); } static IterableStream<RecognizedReceipt> getExpectedReceipts(boolean includeTextDetails) { return getRawExpectedReceipt(includeTextDetails); } static USReceipt getExpectedUSReceipt() { USReceipt usReceipt = null; for (RecognizedReceipt recognizedReceipt : getRawExpectedReceipt(true)) { usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); } return usReceipt; } static IterableStream<RecognizedForm> getExpectedRecognizedForms() { return new IterableStream<RecognizedForm>(toRecognizedForm(getRawResponse(CUSTOM_FORM_DATA).getAnalyzeResult(), false)); } static IterableStream<RecognizedForm> getExpectedRecognizedLabeledForms() { return new IterableStream<RecognizedForm>( toRecognizedForm(getRawResponse(CUSTOM_FORM_LABELED_DATA).getAnalyzeResult(), true)); } static List<TrainingDocumentInfo> getExpectedTrainingDocuments() { TrainingDocumentInfo trainingDocumentInfo1 = new TrainingDocumentInfo("Invoice_1.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); TrainingDocumentInfo trainingDocumentInfo2 = new TrainingDocumentInfo("Invoice_2.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); TrainingDocumentInfo trainingDocumentInfo3 = new TrainingDocumentInfo("Invoice_3.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); TrainingDocumentInfo trainingDocumentInfo4 = new TrainingDocumentInfo("Invoice_4.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); TrainingDocumentInfo trainingDocumentInfo5 = new TrainingDocumentInfo("Invoice_5.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); return Arrays.asList(trainingDocumentInfo1, trainingDocumentInfo2, trainingDocumentInfo3, trainingDocumentInfo4, trainingDocumentInfo5); } static CustomFormModel getExpectedLabeledModel() { Map<String, CustomFormModelField> fieldMap = new HashMap<String, CustomFormModelField>() { { put("InvoiceCharges", new CustomFormModelField(null, "InvoiceCharges", 1.0f)); put("InvoiceDate", new CustomFormModelField(null, "InvoiceDate", 0.8f)); put("InvoiceDueDate", new CustomFormModelField(null, "InvoiceDueDate", 0.8f)); put("InvoiceNumber", new CustomFormModelField(null, "InvoiceNumber", 1.0f)); put("InvoiceVatId", new CustomFormModelField(null, "InvoiceVatId", 1.0f)); } }; CustomFormSubModel customFormSubModel = new CustomFormSubModel(0.92f, fieldMap, "form-" + LABELED_MODEL_ID); return new CustomFormModel(LABELED_MODEL_ID, CustomFormModelStatus.READY, OffsetDateTime.parse("2020-04-09T18:24:49Z"), OffsetDateTime.parse("2020-04-09T18:24:56Z"), new IterableStream<>(Collections.singletonList(customFormSubModel)), Collections.emptyList(), getExpectedTrainingDocuments()); } static AccountProperties getExpectedAccountProperties() { return new AccountProperties(14, 5000); } static InputStream getFileData(String localFileUrl) { try { return new FileInputStream(localFileUrl); } catch (FileNotFoundException e) { throw new RuntimeException("Local Receipt file not found.", e); } } static Flux<ByteBuffer> getFileBufferData(InputStream data) { return Utility.convertStreamToByteBuffer(data); } private static SerializerAdapter getSerializerAdapter() { return JacksonAdapter.createDefaultSerializerAdapter(); } }
class TestUtils { static final String INVALID_MODEL_ID = "a0a3998a-4c4affe66b7"; static final String INVALID_RECEIPT_URL = "https: static final String INVALID_SOURCE_URL_ERROR = "Status code 400, \"{\"error\":{\"code\":\"1003\"," + "\"message\":\"Parameter 'Source' is not a valid Uri.\"}}\""; static final String INVALID_MODEL_ID_ERROR = "Invalid UUID string: " + INVALID_MODEL_ID; static final String NULL_SOURCE_URL_ERROR = "'fileSourceUrl' cannot be null."; static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String RECEIPT_LOCAL_URL = "src/test/resources/sample_files/Test/contoso-allinone.jpg"; static final String LAYOUT_LOCAL_URL = "src/test/resources/sample_files/Test/layout1.jpg"; static final String FORM_LOCAL_URL = "src/test/resources/sample_files/Test/Invoice_6.pdf"; static final long RECEIPT_FILE_LENGTH = new File(RECEIPT_LOCAL_URL).length(); static final long LAYOUT_FILE_LENGTH = new File(LAYOUT_LOCAL_URL).length(); static final long CUSTOM_FORM_FILE_LENGTH = new File(FORM_LOCAL_URL).length(); static final String RECEIPT_URL = "https: + ".com/Azure/azure-sdk-for-java/master/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources" + "/sample_files/Test/contoso-allinone.jpg"; static final String LAYOUT_URL = "https: + ".com/Azure/azure-sdk-for-java/master/sdk/formrecognizer/azure-ai-formrecognizer/src/test/resources" + "/sample_files/Test/layout1.jpg"; private static final String CUSTOM_FORM_LABELED_DATA = "src/test/resources/sample_files/Content" + "/customFormLabeledContent.json"; private static final String CUSTOM_FORM_DATA = "src/test/resources/sample_files/Content/customFormContent.json"; private static final String RECEIPT_FORM_DATA = "src/test/resources/sample_files/Content/receiptContent.json"; private static final String LAYOUT_FORM_DATA = "src/test/resources/sample_files/Content/layoutContent.json"; private TestUtils() { } static AnalyzeOperationResult getRawResponse(String filePath) { String content; try { content = new String(Files.readAllBytes(Paths.get(filePath))); return getSerializerAdapter().deserialize(content, AnalyzeOperationResult.class, SerializerEncoding.JSON); } catch (IOException e) { e.printStackTrace(); } return null; } static List<List<FormTable>> getPagedTables() { List<PageResult> pageResults = getRawResponse(LAYOUT_FORM_DATA).getAnalyzeResult().getPageResults(); List<ReadResult> readResults = getRawResponse(LAYOUT_FORM_DATA).getAnalyzeResult().getReadResults(); return IntStream.range(0, pageResults.size()) .mapToObj(i -> Transforms.getPageTables(pageResults.get(i), readResults, i + 1)) .collect(Collectors.toList()); } static List<List<FormLine>> getPagedLines() { List<ReadResult> readResults = getRawResponse(LAYOUT_FORM_DATA).getAnalyzeResult().getReadResults(); return readResults.stream().map(Transforms::getReadResultFormLines).collect(Collectors.toList()); } static IterableStream<RecognizedReceipt> getRawExpectedReceipt(boolean includeTextDetails) { return toReceipt(getRawResponse(RECEIPT_FORM_DATA).getAnalyzeResult(), includeTextDetails); } static IterableStream<FormPage> getExpectedFormPages() { FormPage formPage = new FormPage(2200, 0, DimensionUnit.PIXEL, 1700, new IterableStream<FormLine>(getPagedLines().get(0)), new IterableStream<FormTable>(getPagedTables().get(0))); return new IterableStream<>(Collections.singletonList(formPage)); } static IterableStream<RecognizedReceipt> getExpectedReceipts(boolean includeTextDetails) { return getRawExpectedReceipt(includeTextDetails); } static USReceipt getExpectedUSReceipt() { USReceipt usReceipt = null; for (RecognizedReceipt recognizedReceipt : getRawExpectedReceipt(true)) { usReceipt = ReceiptExtensions.asUSReceipt(recognizedReceipt); } return usReceipt; } static IterableStream<RecognizedForm> getExpectedRecognizedForms() { return new IterableStream<RecognizedForm>(toRecognizedForm(getRawResponse(CUSTOM_FORM_DATA).getAnalyzeResult(), false)); } static IterableStream<RecognizedForm> getExpectedRecognizedLabeledForms() { return new IterableStream<RecognizedForm>( toRecognizedForm(getRawResponse(CUSTOM_FORM_LABELED_DATA).getAnalyzeResult(), true)); } static List<TrainingDocumentInfo> getExpectedTrainingDocuments() { TrainingDocumentInfo trainingDocumentInfo1 = new TrainingDocumentInfo("Invoice_1.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); TrainingDocumentInfo trainingDocumentInfo2 = new TrainingDocumentInfo("Invoice_2.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); TrainingDocumentInfo trainingDocumentInfo3 = new TrainingDocumentInfo("Invoice_3.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); TrainingDocumentInfo trainingDocumentInfo4 = new TrainingDocumentInfo("Invoice_4.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); TrainingDocumentInfo trainingDocumentInfo5 = new TrainingDocumentInfo("Invoice_5.pdf", TrainingStatus.SUCCEEDED, 1, Collections.emptyList()); return Arrays.asList(trainingDocumentInfo1, trainingDocumentInfo2, trainingDocumentInfo3, trainingDocumentInfo4, trainingDocumentInfo5); } static CustomFormModel getExpectedLabeledModel() { Map<String, CustomFormModelField> fieldMap = new HashMap<String, CustomFormModelField>() { { put("InvoiceCharges", new CustomFormModelField(null, "InvoiceCharges", 1.0f)); put("InvoiceDate", new CustomFormModelField(null, "InvoiceDate", 0.8f)); put("InvoiceDueDate", new CustomFormModelField(null, "InvoiceDueDate", 0.8f)); put("InvoiceNumber", new CustomFormModelField(null, "InvoiceNumber", 1.0f)); put("InvoiceVatId", new CustomFormModelField(null, "InvoiceVatId", 1.0f)); } }; CustomFormSubModel customFormSubModel = new CustomFormSubModel(0.92f, fieldMap, "form-" + "{labeled_model_Id}"); return new CustomFormModel("{labeled_model_Id}", CustomFormModelStatus.READY, OffsetDateTime.parse("2020-04-09T18:24:49Z"), OffsetDateTime.parse("2020-04-09T18:24:56Z"), new IterableStream<>(Collections.singletonList(customFormSubModel)), Collections.emptyList(), getExpectedTrainingDocuments()); } static AccountProperties getExpectedAccountProperties() { return new AccountProperties(14, 5000); } static InputStream getFileData(String localFileUrl) { try { return new FileInputStream(localFileUrl); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } static Flux<ByteBuffer> getReplayableBufferData(String localFileUrl) { Mono<InputStream> dataMono = Mono.defer(() -> { try { return Mono.just(new FileInputStream(localFileUrl)); } catch (FileNotFoundException e) { return Mono.error(new RuntimeException("Local file not found.", e)); } }); return dataMono.flatMapMany(new Function<InputStream, Flux<ByteBuffer>>() { @Override public Flux<ByteBuffer> apply(InputStream inputStream) { return Utility.toFluxByteBuffer(inputStream); } }); } private static SerializerAdapter getSerializerAdapter() { return JacksonAdapter.createDefaultSerializerAdapter(); } }